@geminilight/mindos 0.5.9 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +1 -1
  2. package/app/app/api/skills/route.ts +1 -1
  3. package/app/app/globals.css +10 -2
  4. package/app/app/login/page.tsx +1 -1
  5. package/app/app/view/[...path]/ViewPageClient.tsx +6 -1
  6. package/app/app/view/[...path]/not-found.tsx +1 -1
  7. package/app/components/AskModal.tsx +4 -4
  8. package/app/components/Breadcrumb.tsx +2 -2
  9. package/app/components/DirView.tsx +6 -6
  10. package/app/components/FileTree.tsx +2 -2
  11. package/app/components/HomeContent.tsx +7 -7
  12. package/app/components/OnboardingView.tsx +1 -1
  13. package/app/components/SearchModal.tsx +1 -1
  14. package/app/components/SettingsModal.tsx +2 -2
  15. package/app/components/SetupWizard.tsx +1 -1400
  16. package/app/components/Sidebar.tsx +4 -4
  17. package/app/components/SidebarLayout.tsx +9 -0
  18. package/app/components/SyncStatusBar.tsx +3 -3
  19. package/app/components/TableOfContents.tsx +1 -1
  20. package/app/components/UpdateBanner.tsx +1 -1
  21. package/app/components/ask/FileChip.tsx +1 -1
  22. package/app/components/ask/MentionPopover.tsx +4 -4
  23. package/app/components/ask/MessageList.tsx +1 -1
  24. package/app/components/ask/SessionHistory.tsx +2 -2
  25. package/app/components/renderers/config/ConfigRenderer.tsx +1 -1
  26. package/app/components/renderers/csv/BoardView.tsx +2 -2
  27. package/app/components/renderers/csv/ConfigPanel.tsx +5 -5
  28. package/app/components/renderers/csv/GalleryView.tsx +1 -1
  29. package/app/components/renderers/graph/GraphRenderer.tsx +1 -1
  30. package/app/components/renderers/summary/SummaryRenderer.tsx +1 -1
  31. package/app/components/renderers/workflow/WorkflowRenderer.tsx +2 -2
  32. package/app/components/settings/KnowledgeTab.tsx +1 -1
  33. package/app/components/settings/McpTab.tsx +27 -23
  34. package/app/components/settings/PluginsTab.tsx +4 -4
  35. package/app/components/settings/Primitives.tsx +1 -1
  36. package/app/components/settings/SyncTab.tsx +8 -8
  37. package/app/components/setup/StepAI.tsx +67 -0
  38. package/app/components/setup/StepAgents.tsx +237 -0
  39. package/app/components/setup/StepDots.tsx +39 -0
  40. package/app/components/setup/StepKB.tsx +237 -0
  41. package/app/components/setup/StepPorts.tsx +121 -0
  42. package/app/components/setup/StepReview.tsx +211 -0
  43. package/app/components/setup/StepSecurity.tsx +78 -0
  44. package/app/components/setup/constants.tsx +13 -0
  45. package/app/components/setup/index.tsx +464 -0
  46. package/app/components/setup/types.ts +53 -0
  47. package/app/lib/i18n.ts +4 -4
  48. package/package.json +1 -1
  49. package/skills/project-wiki/SKILL.md +92 -63
@@ -1,1400 +1 @@
1
- 'use client';
2
-
3
- import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
4
- import {
5
- Sparkles, Globe, BookOpen, FileText, Copy, Check, RefreshCw,
6
- Loader2, ChevronLeft, ChevronRight, AlertTriangle, CheckCircle2,
7
- XCircle, Zap, Brain, SkipForward, Info, ChevronDown,
8
- } from 'lucide-react';
9
- import { useLocale } from '@/lib/LocaleContext';
10
- import { Field, Input, Select, ApiKeyInput } from '@/components/settings/Primitives';
11
-
12
- type Template = 'en' | 'zh' | 'empty' | '';
13
-
14
- interface SetupState {
15
- mindRoot: string;
16
- template: Template;
17
- provider: 'anthropic' | 'openai' | 'skip';
18
- anthropicKey: string;
19
- anthropicModel: string;
20
- openaiKey: string;
21
- openaiModel: string;
22
- openaiBaseUrl: string;
23
- webPort: number;
24
- mcpPort: number;
25
- authToken: string;
26
- webPassword: string;
27
- }
28
-
29
- interface PortStatus {
30
- checking: boolean;
31
- available: boolean | null;
32
- isSelf: boolean;
33
- suggestion: number | null;
34
- }
35
-
36
- interface AgentEntry {
37
- key: string;
38
- name: string;
39
- present: boolean;
40
- installed: boolean;
41
- hasProjectScope: boolean;
42
- hasGlobalScope: boolean;
43
- preferredTransport: 'stdio' | 'http';
44
- }
45
-
46
- type AgentInstallState = 'pending' | 'installing' | 'ok' | 'error';
47
- interface AgentInstallStatus {
48
- state: AgentInstallState;
49
- message?: string;
50
- transport?: string;
51
- verified?: boolean;
52
- verifyError?: string;
53
- }
54
-
55
- const TEMPLATES: Array<{ id: Template; icon: React.ReactNode; dirs: string[] }> = [
56
- { id: 'en', icon: <Globe size={18} />, dirs: ['Profile/', 'Connections/', 'Notes/', 'Workflows/', 'Resources/', 'Projects/'] },
57
- { id: 'zh', icon: <BookOpen size={18} />, dirs: ['画像/', '关系/', '笔记/', '流程/', '资源/', '项目/'] },
58
- { id: 'empty', icon: <FileText size={18} />, dirs: ['README.md', 'CONFIG.json', 'INSTRUCTION.md'] },
59
- ];
60
-
61
- const TOTAL_STEPS = 6;
62
- const STEP_KB = 0;
63
- const STEP_PORTS = 2;
64
- const STEP_AGENTS = 4;
65
-
66
- // ─── Step 4 (Security) ────────────────────────────────────────────────────────
67
- // Extracted at module level so its local seed/showSeed state survives parent re-renders
68
- function Step4Inner({
69
- authToken, tokenCopied, onCopy, onGenerate, webPassword, onPasswordChange, s,
70
- }: {
71
- authToken: string;
72
- tokenCopied: boolean;
73
- onCopy: () => void;
74
- onGenerate: (seed?: string) => void;
75
- webPassword: string;
76
- onPasswordChange: (v: string) => void;
77
- s: {
78
- authToken: string; authTokenHint: string; authTokenUsage: string; authTokenUsageWhat: string;
79
- authTokenSeed: string; authTokenSeedHint: string;
80
- generateToken: string; copyToken: string; copiedToken: string;
81
- webPassword: string; webPasswordHint: string;
82
- };
83
- }) {
84
- const [seed, setSeed] = useState('');
85
- const [showSeed, setShowSeed] = useState(false);
86
- const [showUsage, setShowUsage] = useState(false);
87
- return (
88
- <div className="space-y-5">
89
- <Field label={s.authToken} hint={s.authTokenHint}>
90
- <div className="flex gap-2">
91
- <Input value={authToken} readOnly className="font-mono text-xs" />
92
- <button onClick={onCopy}
93
- className="flex items-center gap-1 px-3 py-2 text-xs rounded-lg border border-border hover:bg-muted transition-colors shrink-0"
94
- style={{ color: 'var(--foreground)' }}>
95
- {tokenCopied ? <Check size={14} /> : <Copy size={14} />}
96
- {tokenCopied ? s.copiedToken : s.copyToken}
97
- </button>
98
- <button onClick={() => onGenerate()}
99
- className="flex items-center gap-1 px-3 py-2 text-xs rounded-lg border border-border hover:bg-muted transition-colors shrink-0"
100
- style={{ color: 'var(--foreground)' }}>
101
- <RefreshCw size={14} />
102
- </button>
103
- </div>
104
- </Field>
105
- <div className="space-y-1.5">
106
- <button onClick={() => setShowUsage(!showUsage)} className="text-xs underline"
107
- style={{ color: 'var(--muted-foreground)' }}>
108
- {s.authTokenUsageWhat}
109
- </button>
110
- {showUsage && (
111
- <p className="text-xs leading-relaxed px-3 py-2 rounded-lg"
112
- style={{ background: 'var(--muted)', color: 'var(--muted-foreground)' }}>
113
- {s.authTokenUsage}
114
- </p>
115
- )}
116
- </div>
117
- <div>
118
- <button onClick={() => setShowSeed(!showSeed)} className="text-xs underline"
119
- style={{ color: 'var(--muted-foreground)' }}>
120
- {s.authTokenSeed}
121
- </button>
122
- {showSeed && (
123
- <div className="mt-2 flex gap-2">
124
- <Input value={seed} onChange={e => setSeed(e.target.value)} placeholder={s.authTokenSeedHint} />
125
- <button onClick={() => { if (seed.trim()) onGenerate(seed); }}
126
- className="px-3 py-2 text-xs rounded-lg border border-border hover:bg-muted transition-colors shrink-0"
127
- style={{ color: 'var(--foreground)' }}>
128
- {s.generateToken}
129
- </button>
130
- </div>
131
- )}
132
- </div>
133
- <Field label={s.webPassword} hint={s.webPasswordHint}>
134
- <Input type="password" value={webPassword} onChange={e => onPasswordChange(e.target.value)} placeholder="(optional)" />
135
- </Field>
136
- </div>
137
- );
138
- }
139
-
140
- // ─── PortField ────────────────────────────────────────────────────────────────
141
- function PortField({
142
- label, hint, value, onChange, status, onCheckPort, s,
143
- }: {
144
- label: string; hint: string; value: number;
145
- onChange: (v: number) => void;
146
- status: PortStatus;
147
- onCheckPort: (port: number) => void;
148
- s: { portChecking: string; portInUse: (p: number) => string; portSuggest: (p: number) => string; portAvailable: string; portSelf: string };
149
- }) {
150
- // Debounce auto-check on input change (500ms)
151
- const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
152
- const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
153
- const v = parseInt(e.target.value, 10) || value;
154
- onChange(v);
155
- clearTimeout(timerRef.current);
156
- if (v >= 1024 && v <= 65535) {
157
- timerRef.current = setTimeout(() => onCheckPort(v), 500);
158
- }
159
- };
160
- const handleBlur = () => {
161
- // Cancel pending debounce — onBlur fires the check immediately
162
- clearTimeout(timerRef.current);
163
- onCheckPort(value);
164
- };
165
- useEffect(() => () => clearTimeout(timerRef.current), []);
166
-
167
- return (
168
- <Field label={label} hint={hint}>
169
- <div className="space-y-1.5">
170
- <Input
171
- type="number" min={1024} max={65535} value={value}
172
- onChange={handleChange}
173
- onBlur={handleBlur}
174
- />
175
- {status.checking && (
176
- <p className="text-xs flex items-center gap-1" style={{ color: 'var(--muted-foreground)' }}>
177
- <Loader2 size={11} className="animate-spin" /> {s.portChecking}
178
- </p>
179
- )}
180
- {!status.checking && status.available === false && (
181
- <div className="flex items-center gap-2">
182
- <p className="text-xs flex items-center gap-1" style={{ color: 'var(--amber)' }}>
183
- <AlertTriangle size={11} /> {s.portInUse(value)}
184
- </p>
185
- {status.suggestion !== null && (
186
- <button type="button"
187
- onClick={() => {
188
- onChange(status.suggestion!);
189
- setTimeout(() => onCheckPort(status.suggestion!), 0);
190
- }}
191
- className="text-xs px-2 py-0.5 rounded border transition-colors"
192
- style={{ borderColor: 'var(--amber)', color: 'var(--amber)' }}>
193
- {s.portSuggest(status.suggestion)}
194
- </button>
195
- )}
196
- </div>
197
- )}
198
- {!status.checking && status.available === true && (
199
- <p className="text-xs flex items-center gap-1" style={{ color: '#22c55e' }}>
200
- <CheckCircle2 size={11} /> {status.isSelf ? s.portSelf : s.portAvailable}
201
- </p>
202
- )}
203
- </div>
204
- </Field>
205
- );
206
- }
207
-
208
- // Derive parent dir from current input for ls — supports both / and \ separators
209
- function getParentDir(p: string): string {
210
- if (!p.trim()) return '';
211
- const trimmed = p.trim();
212
- // Already a directory (ends with separator)
213
- if (trimmed.endsWith('/') || trimmed.endsWith('\\')) return trimmed;
214
- // Find last separator (/ or \)
215
- const lastSlash = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
216
- return lastSlash >= 0 ? trimmed.slice(0, lastSlash + 1) : '';
217
- }
218
-
219
- // ─── Step 1: Knowledge Base ───────────────────────────────────────────────────
220
- function Step1({
221
- state, update, t, homeDir,
222
- }: {
223
- state: SetupState;
224
- update: <K extends keyof SetupState>(key: K, val: SetupState[K]) => void;
225
- t: ReturnType<typeof useLocale>['t'];
226
- homeDir: string;
227
- }) {
228
- const s = t.setup;
229
- // Build platform-aware placeholder, e.g. /Users/alice/MindOS/mind or C:\Users\alice\MindOS\mind
230
- // Windows homedir always contains \, e.g. C:\Users\Alice — safe to detect by separator
231
- const sep = homeDir.includes('\\') ? '\\' : '/';
232
- const placeholder = homeDir !== '~' ? [homeDir, 'MindOS', 'mind'].join(sep) : s.kbPathDefault;
233
- const [pathInfo, setPathInfo] = useState<{ exists: boolean; empty: boolean; count: number } | null>(null);
234
- const [suggestions, setSuggestions] = useState<string[]>([]);
235
- const [showSuggestions, setShowSuggestions] = useState(false);
236
- const [activeSuggestion, setActiveSuggestion] = useState(-1);
237
- const [showTemplatePickerAnyway, setShowTemplatePickerAnyway] = useState(false);
238
- const inputRef = useRef<HTMLInputElement>(null);
239
-
240
- // Debounced autocomplete
241
- useEffect(() => {
242
- if (!state.mindRoot.trim()) { setSuggestions([]); return; }
243
- const timer = setTimeout(() => {
244
- const parent = getParentDir(state.mindRoot) || homeDir;
245
- fetch('/api/setup/ls', {
246
- method: 'POST',
247
- headers: { 'Content-Type': 'application/json' },
248
- body: JSON.stringify({ path: parent }),
249
- })
250
- .then(r => r.json())
251
- .then(d => {
252
- if (!d.dirs?.length) { setSuggestions([]); return; }
253
- // Normalize parent to end with a separator (preserve existing / or \)
254
- const endsWithSep = parent.endsWith('/') || parent.endsWith('\\');
255
- const localSep = parent.includes('\\') ? '\\' : '/';
256
- const parentNorm = endsWithSep ? parent : parent + localSep;
257
- const typed = state.mindRoot.trim();
258
- const full: string[] = (d.dirs as string[]).map((dir: string) => parentNorm + dir);
259
- const endsWithAnySep = typed.endsWith('/') || typed.endsWith('\\');
260
- const filtered = endsWithAnySep ? full : full.filter(f => f.startsWith(typed));
261
- setSuggestions(filtered.slice(0, 8));
262
- setShowSuggestions(filtered.length > 0);
263
- setActiveSuggestion(-1);
264
- })
265
- .catch(() => setSuggestions([]));
266
- }, 300);
267
- return () => clearTimeout(timer);
268
- }, [state.mindRoot, homeDir]);
269
-
270
- // Debounced path check
271
- useEffect(() => {
272
- if (!state.mindRoot.trim()) { setPathInfo(null); return; }
273
- const timer = setTimeout(() => {
274
- fetch('/api/setup/check-path', {
275
- method: 'POST',
276
- headers: { 'Content-Type': 'application/json' },
277
- body: JSON.stringify({ path: state.mindRoot }),
278
- })
279
- .then(r => r.json())
280
- .then(d => {
281
- setPathInfo(d);
282
- setShowTemplatePickerAnyway(false);
283
- // Non-empty directory: default to skip template (user can opt-in to merge)
284
- if (d?.exists && !d.empty) update('template', '');
285
- })
286
- .catch(() => setPathInfo(null));
287
- }, 600);
288
- return () => clearTimeout(timer);
289
- }, [state.mindRoot]);
290
-
291
- const hideSuggestions = () => {
292
- setSuggestions([]);
293
- setShowSuggestions(false);
294
- setActiveSuggestion(-1);
295
- };
296
-
297
- const selectSuggestion = (val: string) => {
298
- update('mindRoot', val);
299
- hideSuggestions();
300
- inputRef.current?.focus();
301
- };
302
-
303
- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
304
- if (!showSuggestions || suggestions.length === 0) return;
305
- if (e.key === 'ArrowDown') {
306
- e.preventDefault();
307
- setActiveSuggestion(i => Math.min(i + 1, suggestions.length - 1));
308
- } else if (e.key === 'ArrowUp') {
309
- e.preventDefault();
310
- setActiveSuggestion(i => Math.max(i - 1, -1));
311
- } else if (e.key === 'Enter' && activeSuggestion >= 0) {
312
- e.preventDefault();
313
- selectSuggestion(suggestions[activeSuggestion]);
314
- } else if (e.key === 'Escape') {
315
- setShowSuggestions(false);
316
- }
317
- };
318
-
319
- return (
320
- <div className="space-y-6">
321
- <Field label={s.kbPath} hint={s.kbPathHint}>
322
- <div className="relative">
323
- <input
324
- ref={inputRef}
325
- value={state.mindRoot}
326
- onChange={e => { update('mindRoot', e.target.value); setShowSuggestions(true); }}
327
- onKeyDown={handleKeyDown}
328
- onBlur={() => setTimeout(() => hideSuggestions(), 150)}
329
- onFocus={() => suggestions.length > 0 && setShowSuggestions(true)}
330
- placeholder={placeholder}
331
- className="w-full px-3 py-2 text-sm rounded-lg border outline-none transition-colors"
332
- style={{
333
- background: 'var(--input, var(--card))',
334
- borderColor: 'var(--border)',
335
- color: 'var(--foreground)',
336
- }}
337
- />
338
- {showSuggestions && suggestions.length > 0 && (
339
- <div
340
- className="absolute z-50 left-0 right-0 top-full mt-1 rounded-lg border overflow-auto"
341
- style={{
342
- background: 'var(--card)',
343
- borderColor: 'var(--border)',
344
- boxShadow: '0 4px 16px rgba(0,0,0,0.12)',
345
- maxHeight: '220px',
346
- }}>
347
- {suggestions.map((suggestion, i) => (
348
- <button
349
- key={suggestion}
350
- type="button"
351
- onMouseDown={() => selectSuggestion(suggestion)}
352
- className="w-full text-left px-3 py-2 text-sm font-mono transition-colors"
353
- style={{
354
- background: i === activeSuggestion ? 'var(--muted)' : 'transparent',
355
- color: 'var(--foreground)',
356
- borderTop: i > 0 ? '1px solid var(--border)' : undefined,
357
- }}>
358
- {suggestion}
359
- </button>
360
- ))}
361
- </div>
362
- )}
363
- </div>
364
- {/* Recommended default — one-click accept */}
365
- {state.mindRoot !== placeholder && placeholder !== s.kbPathDefault && (
366
- <button type="button"
367
- onClick={() => update('mindRoot', placeholder)}
368
- className="mt-1.5 px-2.5 py-1 text-xs rounded-md border transition-colors hover:bg-muted/50"
369
- style={{ borderColor: 'var(--amber)', color: 'var(--amber)' }}>
370
- {s.kbPathUseDefault(placeholder)}
371
- </button>
372
- )}
373
- </Field>
374
- {/* Template selection — conditional on directory state */}
375
- {pathInfo && pathInfo.exists && !pathInfo.empty && !showTemplatePickerAnyway ? (
376
- <div>
377
- <label className="text-sm text-foreground font-medium mb-3 block">{s.template}</label>
378
- <div className="rounded-lg border p-3 text-sm" style={{ borderColor: 'var(--amber)', background: 'rgba(245,158,11,0.06)' }}>
379
- <p style={{ color: 'var(--amber)' }}>
380
- {s.kbPathHasFiles(pathInfo.count)}
381
- </p>
382
- <div className="flex gap-2 mt-2">
383
- <button type="button"
384
- onClick={() => update('template', '')}
385
- className="px-2.5 py-1 text-xs rounded-md border transition-colors"
386
- style={{
387
- borderColor: 'var(--amber)',
388
- color: state.template === '' ? 'var(--background)' : 'var(--amber)',
389
- background: state.template === '' ? 'var(--amber)' : 'transparent',
390
- }}>
391
- {state.template === '' ? <>{s.kbTemplateSkip} ✓</> : s.kbTemplateSkip}
392
- </button>
393
- <button type="button"
394
- onClick={() => setShowTemplatePickerAnyway(true)}
395
- className="px-2.5 py-1 text-xs rounded-md border transition-colors hover:bg-muted/50"
396
- style={{ borderColor: 'var(--border)', color: 'var(--muted-foreground)' }}>
397
- {s.kbTemplateMerge}
398
- </button>
399
- </div>
400
- </div>
401
- </div>
402
- ) : (
403
- <div>
404
- <label className="text-sm text-foreground font-medium mb-3 block">{s.template}</label>
405
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
406
- {TEMPLATES.map(tpl => (
407
- <button key={tpl.id} onClick={() => update('template', tpl.id)}
408
- className="flex flex-col items-start gap-2 p-4 rounded-xl border text-left transition-all duration-150"
409
- style={{
410
- background: state.template === tpl.id ? 'var(--amber-subtle, rgba(200,135,30,0.08))' : 'var(--card)',
411
- borderColor: state.template === tpl.id ? 'var(--amber)' : 'var(--border)',
412
- }}>
413
- <div className="flex items-center gap-2">
414
- <span style={{ color: 'var(--amber)' }}>{tpl.icon}</span>
415
- <span className="text-sm font-medium" style={{ color: 'var(--foreground)' }}>
416
- {t.onboarding.templates[tpl.id as 'en' | 'zh' | 'empty'].title}
417
- </span>
418
- </div>
419
- <div className="w-full rounded-lg px-2.5 py-1.5 text-[11px] leading-relaxed font-display"
420
- style={{ background: 'var(--muted)', color: 'var(--muted-foreground)' }}>
421
- {tpl.dirs.map(d => <div key={d}>{d}</div>)}
422
- </div>
423
- </button>
424
- ))}
425
- </div>
426
- </div>
427
- )}
428
- </div>
429
- );
430
- }
431
-
432
- // ─── Step 2: AI Provider ──────────────────────────────────────────────────────
433
- function Step2({
434
- state, update, s,
435
- }: {
436
- state: SetupState;
437
- update: <K extends keyof SetupState>(key: K, val: SetupState[K]) => void;
438
- s: ReturnType<typeof useLocale>['t']['setup'];
439
- }) {
440
- const providers = [
441
- { id: 'anthropic' as const, icon: <Brain size={18} />, label: 'Anthropic', desc: 'Claude — claude-sonnet-4-6' },
442
- { id: 'openai' as const, icon: <Zap size={18} />, label: 'OpenAI', desc: 'GPT or any OpenAI-compatible API' },
443
- { id: 'skip' as const, icon: <SkipForward size={18} />, label: s.aiSkipTitle, desc: s.aiSkipDesc },
444
- ];
445
- return (
446
- <div className="space-y-5">
447
- <div className="grid grid-cols-1 gap-3">
448
- {providers.map(p => (
449
- <button key={p.id} onClick={() => update('provider', p.id)}
450
- className="flex items-start gap-3 p-4 rounded-xl border text-left transition-all duration-150"
451
- style={{
452
- background: state.provider === p.id ? 'var(--amber-subtle, rgba(200,135,30,0.08))' : 'var(--card)',
453
- borderColor: state.provider === p.id ? 'var(--amber)' : 'var(--border)',
454
- }}>
455
- <span className="mt-0.5" style={{ color: state.provider === p.id ? 'var(--amber)' : 'var(--muted-foreground)' }}>
456
- {p.icon}
457
- </span>
458
- <div>
459
- <p className="text-sm font-medium" style={{ color: 'var(--foreground)' }}>{p.label}</p>
460
- <p className="text-xs mt-0.5" style={{ color: 'var(--muted-foreground)' }}>{p.desc}</p>
461
- </div>
462
- {state.provider === p.id && (
463
- <CheckCircle2 size={16} className="ml-auto mt-0.5 shrink-0" style={{ color: 'var(--amber)' }} />
464
- )}
465
- </button>
466
- ))}
467
- </div>
468
- {state.provider !== 'skip' && (
469
- <div className="space-y-4 pt-2">
470
- <Field label={s.apiKey}>
471
- <ApiKeyInput
472
- value={state.provider === 'anthropic' ? state.anthropicKey : state.openaiKey}
473
- onChange={v => update(state.provider === 'anthropic' ? 'anthropicKey' : 'openaiKey', v)}
474
- placeholder={state.provider === 'anthropic' ? 'sk-ant-...' : 'sk-...'}
475
- />
476
- </Field>
477
- <Field label={s.model}>
478
- <Input
479
- value={state.provider === 'anthropic' ? state.anthropicModel : state.openaiModel}
480
- onChange={e => update(state.provider === 'anthropic' ? 'anthropicModel' : 'openaiModel', e.target.value)}
481
- />
482
- </Field>
483
- {state.provider === 'openai' && (
484
- <Field label={s.baseUrl} hint={s.baseUrlHint}>
485
- <Input value={state.openaiBaseUrl} onChange={e => update('openaiBaseUrl', e.target.value)}
486
- placeholder="https://api.openai.com/v1" />
487
- </Field>
488
- )}
489
- </div>
490
- )}
491
- </div>
492
- );
493
- }
494
-
495
- // ─── Step 3: Ports ────────────────────────────────────────────────────────────
496
- function Step3({
497
- state, update, webPortStatus, mcpPortStatus, setWebPortStatus, setMcpPortStatus, checkPort, portConflict, s,
498
- }: {
499
- state: SetupState;
500
- update: <K extends keyof SetupState>(key: K, val: SetupState[K]) => void;
501
- webPortStatus: PortStatus;
502
- mcpPortStatus: PortStatus;
503
- setWebPortStatus: (s: PortStatus) => void;
504
- setMcpPortStatus: (s: PortStatus) => void;
505
- checkPort: (port: number, which: 'web' | 'mcp') => void;
506
- portConflict: boolean;
507
- s: ReturnType<typeof useLocale>['t']['setup'];
508
- }) {
509
- return (
510
- <div className="space-y-5">
511
- <PortField
512
- label={s.webPort} hint={s.portHint} value={state.webPort}
513
- onChange={v => { update('webPort', v); setWebPortStatus({ checking: false, available: null, isSelf: false, suggestion: null }); }}
514
- status={webPortStatus}
515
- onCheckPort={port => checkPort(port, 'web')}
516
- s={s}
517
- />
518
- <PortField
519
- label={s.mcpPort} hint={s.portHint} value={state.mcpPort}
520
- onChange={v => { update('mcpPort', v); setMcpPortStatus({ checking: false, available: null, isSelf: false, suggestion: null }); }}
521
- status={mcpPortStatus}
522
- onCheckPort={port => checkPort(port, 'mcp')}
523
- s={s}
524
- />
525
- {portConflict && (
526
- <p className="text-xs flex items-center gap-1.5" style={{ color: 'var(--amber)' }}>
527
- <AlertTriangle size={12} /> {s.portConflict}
528
- </p>
529
- )}
530
- {!portConflict && (webPortStatus.available === null || mcpPortStatus.available === null) && !webPortStatus.checking && !mcpPortStatus.checking && (
531
- <p className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{s.portVerifyHint}</p>
532
- )}
533
- <p className="text-xs flex items-center gap-1.5" style={{ color: 'var(--muted-foreground)' }}>
534
- <Info size={12} /> {s.portRestartWarning}
535
- </p>
536
- </div>
537
- );
538
- }
539
-
540
- // ─── Step 5: Agent Tools ──────────────────────────────────────────────────────
541
- function Step5({
542
- agents, agentsLoading, selectedAgents, setSelectedAgents,
543
- agentTransport, setAgentTransport, agentScope, setAgentScope,
544
- agentStatuses, s, settingsMcp, template,
545
- }: {
546
- agents: AgentEntry[];
547
- agentsLoading: boolean;
548
- selectedAgents: Set<string>;
549
- setSelectedAgents: React.Dispatch<React.SetStateAction<Set<string>>>;
550
- agentTransport: 'auto' | 'stdio' | 'http';
551
- setAgentTransport: (v: 'auto' | 'stdio' | 'http') => void;
552
- agentScope: 'global' | 'project';
553
- setAgentScope: (v: 'global' | 'project') => void;
554
- agentStatuses: Record<string, AgentInstallStatus>;
555
- s: ReturnType<typeof useLocale>['t']['setup'];
556
- settingsMcp: ReturnType<typeof useLocale>['t']['settings']['mcp'];
557
- template: Template;
558
- }) {
559
- const toggleAgent = (key: string) => {
560
- setSelectedAgents(prev => {
561
- const next = new Set(prev);
562
- if (next.has(key)) next.delete(key); else next.add(key);
563
- return next;
564
- });
565
- };
566
-
567
- const [showOtherAgents, setShowOtherAgents] = useState(false);
568
- const [showAdvanced, setShowAdvanced] = useState(false);
569
-
570
- const getEffectiveTransport = (agent: AgentEntry) => {
571
- if (agentTransport === 'auto') return agent.preferredTransport;
572
- return agentTransport;
573
- };
574
-
575
- const getStatusBadge = (key: string, agent: AgentEntry) => {
576
- const st = agentStatuses[key];
577
- if (st) {
578
- if (st.state === 'installing') return (
579
- <span className="flex items-center gap-1 text-[11px]" style={{ color: 'var(--muted-foreground)' }}>
580
- <Loader2 size={10} className="animate-spin" /> {s.agentInstalling}
581
- </span>
582
- );
583
- if (st.state === 'ok') return (
584
- <span className="flex items-center gap-1 text-[11px] px-1.5 py-0.5 rounded"
585
- style={{ background: 'rgba(34,197,94,0.12)', color: '#22c55e' }}>
586
- <CheckCircle2 size={10} /> {s.agentStatusOk}
587
- </span>
588
- );
589
- if (st.state === 'error') return (
590
- <span className="flex items-center gap-1 text-[11px] px-1.5 py-0.5 rounded"
591
- style={{ background: 'rgba(200,80,80,0.1)', color: 'var(--error)' }}>
592
- <XCircle size={10} /> {s.agentStatusError}
593
- {st.message && <span className="ml-1 text-[10px]">({st.message})</span>}
594
- </span>
595
- );
596
- }
597
- if (agent.installed) return (
598
- <span className="text-[11px] px-1.5 py-0.5 rounded"
599
- style={{ background: 'rgba(34,197,94,0.12)', color: '#22c55e' }}>
600
- {settingsMcp.installed}
601
- </span>
602
- );
603
- if (agent.present) return (
604
- <span className="text-[11px] px-1.5 py-0.5 rounded"
605
- style={{ background: 'rgba(245,158,11,0.12)', color: '#f59e0b' }}>
606
- {s.agentDetected}
607
- </span>
608
- );
609
- return (
610
- <span className="text-[11px] px-1.5 py-0.5 rounded"
611
- style={{ background: 'rgba(100,100,120,0.1)', color: 'var(--muted-foreground)' }}>
612
- {s.agentNotFound}
613
- </span>
614
- );
615
- };
616
-
617
- const { detected, other } = useMemo(() => ({
618
- detected: agents.filter(a => a.installed || a.present),
619
- other: agents.filter(a => !a.installed && !a.present),
620
- }), [agents]);
621
-
622
- const renderAgentRow = (agent: AgentEntry, i: number) => (
623
- <label key={agent.key}
624
- className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-muted/50 transition-colors"
625
- style={{
626
- background: i % 2 === 0 ? 'var(--card)' : 'transparent',
627
- borderTop: i > 0 ? '1px solid var(--border)' : undefined,
628
- }}>
629
- <input
630
- type="checkbox"
631
- checked={selectedAgents.has(agent.key)}
632
- onChange={() => toggleAgent(agent.key)}
633
- className="accent-amber-500"
634
- disabled={agentStatuses[agent.key]?.state === 'installing'}
635
- />
636
- <span className="text-sm flex-1" style={{ color: 'var(--foreground)' }}>{agent.name}</span>
637
- <span className="text-[10px] px-1.5 py-0.5 rounded font-mono"
638
- style={{ background: 'rgba(100,100,120,0.08)', color: 'var(--muted-foreground)' }}>
639
- {getEffectiveTransport(agent)}
640
- </span>
641
- {getStatusBadge(agent.key, agent)}
642
- </label>
643
- );
644
-
645
- return (
646
- <div className="space-y-5">
647
- <p className="text-sm" style={{ color: 'var(--muted-foreground)' }}>{s.agentToolsHint}</p>
648
- {agentsLoading ? (
649
- <div className="flex items-center gap-2 py-4" style={{ color: 'var(--muted-foreground)' }}>
650
- <Loader2 size={14} className="animate-spin" />
651
- <span className="text-sm">{s.agentToolsLoading}</span>
652
- </div>
653
- ) : agents.length === 0 ? (
654
- <p className="text-sm py-4 text-center" style={{ color: 'var(--muted-foreground)' }}>
655
- {s.agentToolsEmpty}
656
- </p>
657
- ) : (
658
- <>
659
- {/* Badge legend */}
660
- <div className="flex items-center gap-4 text-[10px]" style={{ color: 'var(--muted-foreground)' }}>
661
- <span className="flex items-center gap-1">
662
- <span className="inline-block w-1.5 h-1.5 rounded-full" style={{ background: '#22c55e' }} />
663
- {s.badgeInstalled}
664
- </span>
665
- <span className="flex items-center gap-1">
666
- <span className="inline-block w-1.5 h-1.5 rounded-full" style={{ background: '#f59e0b' }} />
667
- {s.badgeDetected}
668
- </span>
669
- <span className="flex items-center gap-1">
670
- <span className="inline-block w-1.5 h-1.5 rounded-full" style={{ background: 'var(--muted-foreground)' }} />
671
- {s.badgeNotFound}
672
- </span>
673
- </div>
674
-
675
- {/* Detected agents — always visible */}
676
- {detected.length > 0 ? (
677
- <div className="rounded-xl border overflow-hidden" style={{ borderColor: 'var(--border)' }}>
678
- {detected.map((agent, i) => renderAgentRow(agent, i))}
679
- </div>
680
- ) : (
681
- <p className="text-xs py-2" style={{ color: 'var(--muted-foreground)' }}>
682
- {s.agentNoneDetected}
683
- </p>
684
- )}
685
- {/* Other agents — collapsed by default */}
686
- {other.length > 0 && (
687
- <div>
688
- <button
689
- type="button"
690
- onClick={() => setShowOtherAgents(!showOtherAgents)}
691
- className="flex items-center gap-1.5 text-xs py-1.5 transition-colors"
692
- style={{ color: 'var(--muted-foreground)' }}>
693
- <ChevronDown size={12} className={`transition-transform ${showOtherAgents ? 'rotate-180' : ''}`} />
694
- {s.agentShowMore(other.length)}
695
- </button>
696
- {showOtherAgents && (
697
- <div className="rounded-xl border overflow-hidden mt-1" style={{ borderColor: 'var(--border)' }}>
698
- {other.map((agent, i) => renderAgentRow(agent, i))}
699
- </div>
700
- )}
701
- </div>
702
- )}
703
- {/* Skill context + auto-install hint */}
704
- <div className="space-y-1.5">
705
- <p className="text-xs" style={{ color: 'var(--muted-foreground)' }}>
706
- {s.skillWhat}
707
- </p>
708
- <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-xs"
709
- style={{ background: 'rgba(100,100,120,0.06)', color: 'var(--muted-foreground)' }}>
710
- <Brain size={13} className="shrink-0" />
711
- <span>{s.skillAutoHint(template === 'zh' ? 'mindos-zh' : 'mindos')}</span>
712
- </div>
713
- </div>
714
- {/* Advanced options — collapsed by default */}
715
- <div>
716
- <button
717
- type="button"
718
- onClick={() => setShowAdvanced(!showAdvanced)}
719
- className="flex items-center gap-1.5 text-xs py-1.5 transition-colors"
720
- style={{ color: 'var(--muted-foreground)' }}>
721
- <ChevronDown size={12} className={`transition-transform ${showAdvanced ? 'rotate-180' : ''}`} />
722
- {s.agentAdvanced}
723
- </button>
724
- {showAdvanced && (
725
- <div className="grid grid-cols-2 gap-4 mt-2">
726
- <Field label={s.agentTransport}>
727
- <Select value={agentTransport} onChange={e => setAgentTransport(e.target.value as 'auto' | 'stdio' | 'http')}>
728
- <option value="auto">{s.agentTransportAuto}</option>
729
- <option value="stdio">{settingsMcp.transportStdio}</option>
730
- <option value="http">{settingsMcp.transportHttp}</option>
731
- </Select>
732
- </Field>
733
- <Field label={s.agentScope}>
734
- <Select value={agentScope} onChange={e => setAgentScope(e.target.value as 'global' | 'project')}>
735
- <option value="global">{s.agentScopeGlobal}</option>
736
- <option value="project">{s.agentScopeProject}</option>
737
- </Select>
738
- </Field>
739
- </div>
740
- )}
741
- </div>
742
- <div className="flex gap-2 mt-1">
743
- <button
744
- type="button"
745
- onClick={() => setSelectedAgents(new Set(
746
- agents.filter(a => a.installed || a.present).map(a => a.key)
747
- ))}
748
- className="text-xs px-2.5 py-1 rounded-md border transition-colors hover:bg-muted/50"
749
- style={{ borderColor: 'var(--amber)', color: 'var(--amber)' }}>
750
- {s.agentSelectDetected}
751
- </button>
752
- <button
753
- type="button"
754
- onClick={() => setSelectedAgents(new Set())}
755
- className="text-xs px-2.5 py-1 rounded-md border transition-colors hover:bg-muted/50"
756
- style={{ borderColor: 'var(--border)', color: 'var(--muted-foreground)' }}>
757
- {s.agentSkipLater}
758
- </button>
759
- </div>
760
- </>
761
- )}
762
- </div>
763
- );
764
- }
765
-
766
- // ─── Restart Block ────────────────────────────────────────────────────────────
767
- function RestartBlock({ s, newPort }: { s: ReturnType<typeof useLocale>['t']['setup']; newPort: number }) {
768
- const [restarting, setRestarting] = useState(false);
769
- const [done, setDone] = useState(false);
770
-
771
- const handleRestart = async () => {
772
- setRestarting(true);
773
- try {
774
- await fetch('/api/restart', { method: 'POST' });
775
- setDone(true);
776
- const redirect = () => { window.location.href = `http://localhost:${newPort}/?welcome=1`; };
777
- // Poll the new port until ready, then redirect
778
- let attempts = 0;
779
- const poll = setInterval(async () => {
780
- attempts++;
781
- try {
782
- const r = await fetch(`http://localhost:${newPort}/api/health`);
783
- if (r.status < 500) { clearInterval(poll); redirect(); return; }
784
- } catch { /* not ready yet */ }
785
- if (attempts >= 10) { clearInterval(poll); redirect(); }
786
- }, 800);
787
- } catch {
788
- setRestarting(false);
789
- }
790
- };
791
-
792
- if (done) {
793
- return (
794
- <div className="p-3 rounded-lg text-sm flex items-center gap-2"
795
- style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e' }}>
796
- <CheckCircle2 size={14} /> {s.restartDone}
797
- </div>
798
- );
799
- }
800
-
801
- return (
802
- <div className="space-y-3">
803
- <div className="p-3 rounded-lg text-sm flex items-center gap-2"
804
- style={{ background: 'rgba(200,135,30,0.1)', color: 'var(--amber)' }}>
805
- <AlertTriangle size={14} /> {s.restartRequired}
806
- </div>
807
- <div className="flex items-center gap-3">
808
- <button
809
- type="button"
810
- onClick={handleRestart}
811
- disabled={restarting}
812
- className="flex items-center gap-1.5 px-4 py-2 text-sm rounded-lg transition-colors disabled:opacity-50"
813
- style={{ background: 'var(--amber)', color: 'white' }}>
814
- {restarting ? <Loader2 size={13} className="animate-spin" /> : null}
815
- {restarting ? s.restarting : s.restartNow}
816
- </button>
817
- <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>
818
- {s.restartManual} <code className="font-mono">mindos start</code>
819
- </span>
820
- </div>
821
- </div>
822
- );
823
- }
824
-
825
- // ─── Step 6: Review ───────────────────────────────────────────────────────────
826
- function Step6({
827
- state, selectedAgents, agentStatuses, onRetryAgent, error, needsRestart, s,
828
- skillInstallResult, setupPhase,
829
- }: {
830
- state: SetupState;
831
- selectedAgents: Set<string>;
832
- agentStatuses: Record<string, AgentInstallStatus>;
833
- onRetryAgent: (key: string) => void;
834
- error: string;
835
- needsRestart: boolean;
836
- s: ReturnType<typeof useLocale>['t']['setup'];
837
- skillInstallResult: { ok?: boolean; skill?: string; error?: string } | null;
838
- setupPhase: 'review' | 'saving' | 'agents' | 'skill' | 'done';
839
- }) {
840
- const failedAgents = Object.entries(agentStatuses).filter(([, v]) => v.state === 'error');
841
-
842
- // Compact config summary (only key info)
843
- const summaryRows: [string, string][] = [
844
- [s.kbPath, state.mindRoot],
845
- [s.webPort, `${state.webPort} / ${state.mcpPort}`],
846
- [s.agentToolsTitle, selectedAgents.size > 0 ? s.agentCountSummary(selectedAgents.size) : '—'],
847
- ];
848
-
849
- // Progress stepper phases
850
- type Phase = typeof setupPhase;
851
- const phases: { key: Phase; label: string }[] = [
852
- { key: 'saving', label: s.phaseSaving },
853
- { key: 'agents', label: s.phaseAgents },
854
- { key: 'skill', label: s.phaseSkill },
855
- { key: 'done', label: s.phaseDone },
856
- ];
857
- const phaseOrder: Phase[] = ['saving', 'agents', 'skill', 'done'];
858
- const currentIdx = phaseOrder.indexOf(setupPhase);
859
-
860
- return (
861
- <div className="space-y-5">
862
- {/* Compact config summary */}
863
- <div className="rounded-xl border overflow-hidden" style={{ borderColor: 'var(--border)' }}>
864
- {summaryRows.map(([label, value], i) => (
865
- <div key={i} className="flex items-center justify-between px-4 py-2.5 text-sm"
866
- style={{
867
- background: i % 2 === 0 ? 'var(--card)' : 'transparent',
868
- borderTop: i > 0 ? '1px solid var(--border)' : undefined,
869
- }}>
870
- <span style={{ color: 'var(--muted-foreground)' }}>{label}</span>
871
- <span className="font-mono text-xs truncate ml-4" style={{ color: 'var(--foreground)' }}>{value}</span>
872
- </div>
873
- ))}
874
- </div>
875
-
876
- {/* Before submit: review hint */}
877
- {setupPhase === 'review' && (
878
- <p className="text-sm" style={{ color: 'var(--muted-foreground)' }}>{s.reviewHint}</p>
879
- )}
880
-
881
- {/* Progress stepper — visible during/after setup */}
882
- {setupPhase !== 'review' && (
883
- <div className="space-y-2 py-2">
884
- {phases.map(({ key, label }, i) => {
885
- const idx = phaseOrder.indexOf(key);
886
- const isDone = currentIdx > idx || (key === 'done' && setupPhase === 'done');
887
- const isActive = setupPhase === key && key !== 'done';
888
- const isPending = currentIdx < idx;
889
- return (
890
- <div key={key} className="flex items-center gap-3">
891
- <div className="w-5 h-5 rounded-full flex items-center justify-center shrink-0 text-[10px]"
892
- style={{
893
- background: isDone ? 'rgba(34,197,94,0.15)' : isActive ? 'rgba(200,135,30,0.15)' : 'var(--muted)',
894
- color: isDone ? '#22c55e' : isActive ? 'var(--amber)' : 'var(--muted-foreground)',
895
- }}>
896
- {isDone ? <CheckCircle2 size={12} /> : isActive ? <Loader2 size={12} className="animate-spin" /> : (i + 1)}
897
- </div>
898
- <span className="text-sm" style={{
899
- color: isDone ? '#22c55e' : isActive ? 'var(--foreground)' : 'var(--muted-foreground)',
900
- fontWeight: isActive ? 500 : 400,
901
- opacity: isPending ? 0.5 : 1,
902
- }}>
903
- {label}
904
- </span>
905
- </div>
906
- );
907
- })}
908
- </div>
909
- )}
910
-
911
- {/* Agent failures — expandable */}
912
- {failedAgents.length > 0 && setupPhase === 'done' && (
913
- <div className="p-3 rounded-lg space-y-2" style={{ background: 'rgba(200,80,80,0.08)' }}>
914
- <p className="text-xs font-medium" style={{ color: 'var(--error)' }}>
915
- {s.agentFailedCount(failedAgents.length)}
916
- </p>
917
- {failedAgents.map(([key, st]) => (
918
- <div key={key} className="flex items-center justify-between gap-2">
919
- <span className="text-xs flex items-center gap-1" style={{ color: 'var(--error)' }}>
920
- <XCircle size={11} /> {key}{st.message ? ` — ${st.message}` : ''}
921
- </span>
922
- <button
923
- type="button"
924
- onClick={() => onRetryAgent(key)}
925
- disabled={st.state === 'installing'}
926
- className="text-xs px-2 py-0.5 rounded border transition-colors disabled:opacity-40"
927
- style={{ borderColor: 'var(--error)', color: 'var(--error)' }}>
928
- {st.state === 'installing' ? <Loader2 size={10} className="animate-spin inline" /> : s.retryAgent}
929
- </button>
930
- </div>
931
- ))}
932
- <p className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{s.agentFailureNote}</p>
933
- </div>
934
- )}
935
-
936
- {/* Skill result — compact */}
937
- {skillInstallResult && setupPhase === 'done' && (
938
- <div className="flex items-center gap-2 text-xs px-3 py-2 rounded-lg" style={{
939
- background: skillInstallResult.ok ? 'rgba(34,197,94,0.06)' : 'rgba(200,80,80,0.06)',
940
- }}>
941
- {skillInstallResult.ok ? (
942
- <><CheckCircle2 size={11} className="text-green-500 shrink-0" />
943
- <span style={{ color: 'var(--foreground)' }}>{s.skillInstalled} — {skillInstallResult.skill}</span></>
944
- ) : (
945
- <><XCircle size={11} className="text-error shrink-0" />
946
- <span style={{ color: 'var(--error)' }}>{s.skillFailed}{skillInstallResult.error ? `: ${skillInstallResult.error}` : ''}</span></>
947
- )}
948
- </div>
949
- )}
950
-
951
- {error && (
952
- <div className="p-3 rounded-lg text-sm text-error" style={{ background: 'rgba(200,80,80,0.1)' }}>
953
- {s.completeFailed}: {error}
954
- </div>
955
- )}
956
- {needsRestart && setupPhase === 'done' && <RestartBlock s={s} newPort={state.webPort} />}
957
- </div>
958
- );
959
- }
960
-
961
- // ─── Step dots ────────────────────────────────────────────────────────────────
962
- function StepDots({ step, setStep, stepTitles, disabled }: {
963
- step: number;
964
- setStep: (s: number) => void;
965
- stepTitles: readonly string[];
966
- disabled?: boolean;
967
- }) {
968
- return (
969
- <div className="flex items-center gap-2 mb-8">
970
- {stepTitles.map((title: string, i: number) => (
971
- <div key={i} className="flex items-center gap-2">
972
- {i > 0 && <div className="w-8 h-px" style={{ background: i <= step ? 'var(--amber)' : 'var(--border)' }} />}
973
- <button onClick={() => !disabled && i < step && setStep(i)} className="flex items-center gap-1.5 disabled:cursor-not-allowed disabled:opacity-60" disabled={disabled || i > step}>
974
- <div
975
- className="w-6 h-6 rounded-full text-xs font-medium flex items-center justify-center transition-colors"
976
- style={{
977
- background: i <= step ? 'var(--amber)' : 'var(--muted)',
978
- color: i <= step ? 'white' : 'var(--muted-foreground)',
979
- opacity: i <= step ? 1 : 0.5,
980
- }}>
981
- {i + 1}
982
- </div>
983
- <span className="text-xs hidden sm:inline"
984
- style={{ color: i === step ? 'var(--foreground)' : 'var(--muted-foreground)', opacity: i <= step ? 1 : 0.5 }}>
985
- {title}
986
- </span>
987
- </button>
988
- </div>
989
- ))}
990
- </div>
991
- );
992
- }
993
-
994
- // ─── Main component ───────────────────────────────────────────────────────────
995
- export default function SetupWizard() {
996
- const { t } = useLocale();
997
- const s = t.setup;
998
-
999
- const [step, setStep] = useState(0);
1000
- const [state, setState] = useState<SetupState>({
1001
- mindRoot: '~/MindOS/mind',
1002
- template: 'en',
1003
- provider: 'anthropic',
1004
- anthropicKey: '',
1005
- anthropicModel: 'claude-sonnet-4-6',
1006
- openaiKey: '',
1007
- openaiModel: 'gpt-5.4',
1008
- openaiBaseUrl: '',
1009
- webPort: 3000,
1010
- mcpPort: 8787,
1011
- authToken: '',
1012
- webPassword: '',
1013
- });
1014
- const [homeDir, setHomeDir] = useState('~');
1015
- const [tokenCopied, setTokenCopied] = useState(false);
1016
- const [submitting, setSubmitting] = useState(false);
1017
- const [completed, setCompleted] = useState(false);
1018
- const [error, setError] = useState('');
1019
- const [needsRestart, setNeedsRestart] = useState(false);
1020
-
1021
- const [webPortStatus, setWebPortStatus] = useState<PortStatus>({ checking: false, available: null, isSelf: false, suggestion: null });
1022
- const [mcpPortStatus, setMcpPortStatus] = useState<PortStatus>({ checking: false, available: null, isSelf: false, suggestion: null });
1023
-
1024
- const [agents, setAgents] = useState<AgentEntry[]>([]);
1025
- const [agentsLoading, setAgentsLoading] = useState(false);
1026
- const [selectedAgents, setSelectedAgents] = useState<Set<string>>(new Set());
1027
- const [agentTransport, setAgentTransport] = useState<'auto' | 'stdio' | 'http'>('auto');
1028
- const [agentScope, setAgentScope] = useState<'global' | 'project'>('global');
1029
- const [agentStatuses, setAgentStatuses] = useState<Record<string, AgentInstallStatus>>({});
1030
- const [skillInstallResult, setSkillInstallResult] = useState<{ ok?: boolean; skill?: string; error?: string } | null>(null);
1031
- const [setupPhase, setSetupPhase] = useState<'review' | 'saving' | 'agents' | 'skill' | 'done'>('review');
1032
-
1033
- // Load existing config as defaults on mount, generate token if none exists
1034
- useEffect(() => {
1035
- fetch('/api/setup')
1036
- .then(r => r.json())
1037
- .then(data => {
1038
- if (data.homeDir) setHomeDir(data.homeDir);
1039
- setState(prev => ({
1040
- ...prev,
1041
- mindRoot: data.mindRoot || prev.mindRoot,
1042
- webPort: typeof data.port === 'number' ? data.port : prev.webPort,
1043
- mcpPort: typeof data.mcpPort === 'number' ? data.mcpPort : prev.mcpPort,
1044
- authToken: data.authToken || prev.authToken,
1045
- webPassword: data.webPassword || prev.webPassword,
1046
- provider: (data.provider === 'anthropic' || data.provider === 'openai') ? data.provider : prev.provider,
1047
- anthropicModel: data.anthropicModel || prev.anthropicModel,
1048
- openaiModel: data.openaiModel || prev.openaiModel,
1049
- openaiBaseUrl: data.openaiBaseUrl ?? prev.openaiBaseUrl,
1050
- }));
1051
- // Generate a new token only if none exists yet
1052
- if (!data.authToken) {
1053
- fetch('/api/setup/generate-token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })
1054
- .then(r => r.json())
1055
- .then(tokenData => { if (tokenData.token) setState(p => ({ ...p, authToken: tokenData.token })); })
1056
- .catch(() => {});
1057
- }
1058
- })
1059
- .catch(() => {
1060
- // Fallback: generate token on failure
1061
- fetch('/api/setup/generate-token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })
1062
- .then(r => r.json())
1063
- .then(data => { if (data.token) setState(prev => ({ ...prev, authToken: data.token })); })
1064
- .catch(() => {});
1065
- });
1066
- }, []);
1067
-
1068
- // Auto-check ports when entering Step 3
1069
- useEffect(() => {
1070
- if (step === STEP_PORTS) {
1071
- checkPort(state.webPort, 'web');
1072
- checkPort(state.mcpPort, 'mcp');
1073
- }
1074
- // eslint-disable-next-line react-hooks/exhaustive-deps
1075
- }, [step]);
1076
-
1077
- // Load agents when entering Step 5
1078
- useEffect(() => {
1079
- if (step === STEP_AGENTS && agents.length === 0 && !agentsLoading) {
1080
- setAgentsLoading(true);
1081
- fetch('/api/mcp/agents')
1082
- .then(r => r.json())
1083
- .then(data => {
1084
- if (data.agents) {
1085
- setAgents(data.agents);
1086
- setSelectedAgents(new Set(
1087
- (data.agents as AgentEntry[]).filter(a => a.installed || a.present).map(a => a.key)
1088
- ));
1089
- }
1090
- })
1091
- .catch(() => {})
1092
- .finally(() => setAgentsLoading(false));
1093
- }
1094
- }, [step, agents.length, agentsLoading]);
1095
-
1096
- const update = useCallback(<K extends keyof SetupState>(key: K, val: SetupState[K]) => {
1097
- setState(prev => ({ ...prev, [key]: val }));
1098
- }, []);
1099
-
1100
- const generateToken = useCallback(async (seed?: string) => {
1101
- try {
1102
- const res = await fetch('/api/setup/generate-token', {
1103
- method: 'POST',
1104
- headers: { 'Content-Type': 'application/json' },
1105
- body: JSON.stringify({ seed: seed || undefined }),
1106
- });
1107
- const data = await res.json();
1108
- if (data.token) setState(prev => ({ ...prev, authToken: data.token }));
1109
- } catch { /* ignore */ }
1110
- }, []);
1111
-
1112
- const copyToken = useCallback(() => {
1113
- setState(prev => { navigator.clipboard.writeText(prev.authToken); return prev; });
1114
- setTokenCopied(true);
1115
- setTimeout(() => setTokenCopied(false), 2000);
1116
- }, []);
1117
-
1118
- const checkPort = useCallback(async (port: number, which: 'web' | 'mcp') => {
1119
- if (port < 1024 || port > 65535) return;
1120
- const setStatus = which === 'web' ? setWebPortStatus : setMcpPortStatus;
1121
- setStatus({ checking: true, available: null, isSelf: false, suggestion: null });
1122
- try {
1123
- const res = await fetch('/api/setup/check-port', {
1124
- method: 'POST',
1125
- headers: { 'Content-Type': 'application/json' },
1126
- body: JSON.stringify({ port }),
1127
- });
1128
- const data = await res.json();
1129
- setStatus({ checking: false, available: data.available ?? null, isSelf: !!data.isSelf, suggestion: data.suggestion ?? null });
1130
- } catch {
1131
- setStatus({ checking: false, available: null, isSelf: false, suggestion: null });
1132
- }
1133
- }, []);
1134
-
1135
-
1136
- const portConflict = state.webPort === state.mcpPort;
1137
-
1138
- const canNext = () => {
1139
- if (step === STEP_KB) return state.mindRoot.trim().length > 0;
1140
- if (step === STEP_PORTS) {
1141
- if (portConflict) return false;
1142
- if (webPortStatus.checking || mcpPortStatus.checking) return false;
1143
- if (webPortStatus.available !== true || mcpPortStatus.available !== true) return false;
1144
- return (
1145
- state.webPort >= 1024 && state.webPort <= 65535 &&
1146
- state.mcpPort >= 1024 && state.mcpPort <= 65535
1147
- );
1148
- }
1149
- return true;
1150
- };
1151
-
1152
- const handleComplete = async () => {
1153
- setSubmitting(true);
1154
- setError('');
1155
- setSetupPhase('saving');
1156
- let restartNeeded = false;
1157
-
1158
- // 1. Save setup config
1159
- try {
1160
- const payload = {
1161
- mindRoot: state.mindRoot,
1162
- template: state.template || undefined,
1163
- port: state.webPort,
1164
- mcpPort: state.mcpPort,
1165
- authToken: state.authToken,
1166
- webPassword: state.webPassword,
1167
- ai: state.provider === 'skip' ? undefined : {
1168
- provider: state.provider,
1169
- providers: {
1170
- anthropic: { apiKey: state.anthropicKey, model: state.anthropicModel },
1171
- openai: { apiKey: state.openaiKey, model: state.openaiModel, baseUrl: state.openaiBaseUrl },
1172
- },
1173
- },
1174
- };
1175
- const res = await fetch('/api/setup', {
1176
- method: 'POST',
1177
- headers: { 'Content-Type': 'application/json' },
1178
- body: JSON.stringify(payload),
1179
- });
1180
- const data = await res.json();
1181
- if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
1182
- restartNeeded = !!data.needsRestart;
1183
- if (restartNeeded) setNeedsRestart(true);
1184
- } catch (e) {
1185
- setError(e instanceof Error ? e.message : String(e));
1186
- setSetupPhase('review');
1187
- setSubmitting(false);
1188
- return;
1189
- }
1190
-
1191
- // 2. Install agents after config saved
1192
- setSetupPhase('agents');
1193
- if (selectedAgents.size > 0) {
1194
- const initialStatuses: Record<string, AgentInstallStatus> = {};
1195
- for (const key of selectedAgents) initialStatuses[key] = { state: 'installing' };
1196
- setAgentStatuses(initialStatuses);
1197
-
1198
- try {
1199
- const agentsPayload = Array.from(selectedAgents).map(key => {
1200
- const agent = agents.find(a => a.key === key);
1201
- const effectiveTransport = agentTransport === 'auto'
1202
- ? (agent?.preferredTransport || 'stdio')
1203
- : agentTransport;
1204
- return { key, scope: agentScope, transport: effectiveTransport };
1205
- });
1206
- const res = await fetch('/api/mcp/install', {
1207
- method: 'POST',
1208
- headers: { 'Content-Type': 'application/json' },
1209
- body: JSON.stringify({
1210
- agents: agentsPayload,
1211
- transport: agentTransport,
1212
- url: `http://localhost:${state.mcpPort}/mcp`,
1213
- token: state.authToken || undefined,
1214
- }),
1215
- });
1216
- const data = await res.json();
1217
- if (data.results) {
1218
- const updated: Record<string, AgentInstallStatus> = {};
1219
- for (const r of data.results as Array<{ agent: string; status: string; message?: string; transport?: string; verified?: boolean; verifyError?: string }>) {
1220
- updated[r.agent] = {
1221
- state: r.status === 'ok' ? 'ok' : 'error',
1222
- message: r.message,
1223
- transport: r.transport,
1224
- verified: r.verified,
1225
- verifyError: r.verifyError,
1226
- };
1227
- }
1228
- setAgentStatuses(updated);
1229
- }
1230
- } catch {
1231
- const errStatuses: Record<string, AgentInstallStatus> = {};
1232
- for (const key of selectedAgents) errStatuses[key] = { state: 'error' };
1233
- setAgentStatuses(errStatuses);
1234
- }
1235
- }
1236
-
1237
- // 3. Install skill to agents
1238
- setSetupPhase('skill');
1239
- const skillName = state.template === 'zh' ? 'mindos-zh' : 'mindos';
1240
- try {
1241
- const skillRes = await fetch('/api/mcp/install-skill', {
1242
- method: 'POST',
1243
- headers: { 'Content-Type': 'application/json' },
1244
- body: JSON.stringify({ skill: skillName, agents: Array.from(selectedAgents) }),
1245
- });
1246
- const skillData = await skillRes.json();
1247
- setSkillInstallResult(skillData);
1248
- } catch {
1249
- setSkillInstallResult({ error: 'Failed to install skill' });
1250
- }
1251
-
1252
- setSubmitting(false);
1253
- setCompleted(true);
1254
- setSetupPhase('done');
1255
-
1256
- if (restartNeeded) {
1257
- // Config changed requiring restart — stay on page, show restart block
1258
- return;
1259
- }
1260
- window.location.href = '/?welcome=1';
1261
- };
1262
-
1263
- const retryAgent = useCallback(async (key: string) => {
1264
- setAgentStatuses(prev => ({ ...prev, [key]: { state: 'installing' } }));
1265
- try {
1266
- const agent = agents.find(a => a.key === key);
1267
- const effectiveTransport = agentTransport === 'auto'
1268
- ? (agent?.preferredTransport || 'stdio')
1269
- : agentTransport;
1270
- const res = await fetch('/api/mcp/install', {
1271
- method: 'POST',
1272
- headers: { 'Content-Type': 'application/json' },
1273
- body: JSON.stringify({
1274
- agents: [{ key, scope: agentScope, transport: effectiveTransport }],
1275
- transport: agentTransport,
1276
- url: `http://localhost:${state.mcpPort}/mcp`,
1277
- token: state.authToken || undefined,
1278
- }),
1279
- });
1280
- const data = await res.json();
1281
- if (data.results?.[0]) {
1282
- const r = data.results[0] as { agent: string; status: string; message?: string; transport?: string; verified?: boolean; verifyError?: string };
1283
- setAgentStatuses(prev => ({
1284
- ...prev,
1285
- [key]: {
1286
- state: r.status === 'ok' ? 'ok' : 'error',
1287
- message: r.message,
1288
- transport: r.transport,
1289
- verified: r.verified,
1290
- verifyError: r.verifyError,
1291
- },
1292
- }));
1293
- }
1294
- } catch {
1295
- setAgentStatuses(prev => ({ ...prev, [key]: { state: 'error' } }));
1296
- }
1297
- }, [agents, agentScope, agentTransport, state.mcpPort, state.authToken]);
1298
-
1299
- return (
1300
- <div className="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto"
1301
- style={{ background: 'var(--background)' }}>
1302
- <div className="w-full max-w-xl mx-auto px-6 py-12">
1303
- <div className="text-center mb-8">
1304
- <div className="inline-flex items-center gap-2 mb-2">
1305
- <Sparkles size={18} style={{ color: 'var(--amber)' }} />
1306
- <h1 className="text-2xl font-semibold tracking-tight font-display" style={{ color: 'var(--foreground)' }}>
1307
- MindOS
1308
- </h1>
1309
- </div>
1310
- </div>
1311
-
1312
- <div className="flex justify-center">
1313
- <StepDots step={step} setStep={setStep} stepTitles={s.stepTitles} disabled={submitting || completed} />
1314
- </div>
1315
-
1316
- <h2 className="text-lg font-semibold mb-5" style={{ color: 'var(--foreground)' }}>
1317
- {s.stepTitles[step]}
1318
- </h2>
1319
-
1320
- {step === 0 && <Step1 state={state} update={update} t={t} homeDir={homeDir} />}
1321
- {step === 1 && <Step2 state={state} update={update} s={s} />}
1322
- {step === 2 && (
1323
- <Step3
1324
- state={state} update={update}
1325
- webPortStatus={webPortStatus} mcpPortStatus={mcpPortStatus}
1326
- setWebPortStatus={setWebPortStatus} setMcpPortStatus={setMcpPortStatus}
1327
- checkPort={checkPort} portConflict={portConflict} s={s}
1328
- />
1329
- )}
1330
- {step === 3 && (
1331
- <Step4Inner
1332
- authToken={state.authToken} tokenCopied={tokenCopied}
1333
- onCopy={copyToken} onGenerate={generateToken}
1334
- webPassword={state.webPassword} onPasswordChange={v => update('webPassword', v)}
1335
- s={s}
1336
- />
1337
- )}
1338
- {step === 4 && (
1339
- <Step5
1340
- agents={agents} agentsLoading={agentsLoading}
1341
- selectedAgents={selectedAgents} setSelectedAgents={setSelectedAgents}
1342
- agentTransport={agentTransport} setAgentTransport={setAgentTransport}
1343
- agentScope={agentScope} setAgentScope={setAgentScope}
1344
- agentStatuses={agentStatuses} s={s} settingsMcp={t.settings.mcp}
1345
- template={state.template}
1346
- />
1347
- )}
1348
- {step === 5 && (
1349
- <Step6
1350
- state={state} selectedAgents={selectedAgents}
1351
- agentStatuses={agentStatuses} onRetryAgent={retryAgent}
1352
- error={error} needsRestart={needsRestart}
1353
- s={s}
1354
- skillInstallResult={skillInstallResult}
1355
- setupPhase={setupPhase}
1356
- />
1357
- )}
1358
-
1359
- {/* Navigation */}
1360
- <div className="flex items-center justify-between mt-8 pt-6" style={{ borderTop: '1px solid var(--border)' }}>
1361
- <button
1362
- onClick={() => setStep(step - 1)}
1363
- disabled={step === 0 || submitting || completed}
1364
- className="flex items-center gap-1 px-4 py-2 text-sm rounded-lg border border-border hover:bg-muted transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
1365
- style={{ color: 'var(--foreground)' }}>
1366
- <ChevronLeft size={14} /> {s.back}
1367
- </button>
1368
-
1369
- {step < TOTAL_STEPS - 1 ? (
1370
- <button
1371
- onClick={() => setStep(step + 1)}
1372
- disabled={!canNext()}
1373
- className="flex items-center gap-1 px-4 py-2 text-sm rounded-lg transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
1374
- style={{ background: 'var(--amber)', color: 'white' }}>
1375
- {s.next} <ChevronRight size={14} />
1376
- </button>
1377
- ) : completed ? (
1378
- // After completing: show Done link (no restart needed) or nothing (RestartBlock handles it)
1379
- !needsRestart ? (
1380
- <a href="/?welcome=1"
1381
- className="flex items-center gap-1 px-5 py-2 text-sm font-medium rounded-lg transition-colors"
1382
- style={{ background: 'var(--amber)', color: 'white' }}>
1383
- {s.completeDone} &rarr;
1384
- </a>
1385
- ) : null
1386
- ) : (
1387
- <button
1388
- onClick={handleComplete}
1389
- disabled={submitting}
1390
- className="flex items-center gap-1 px-5 py-2 text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
1391
- style={{ background: 'var(--amber)', color: 'white' }}>
1392
- {submitting && <Loader2 size={14} className="animate-spin" />}
1393
- {submitting ? s.completing : s.complete}
1394
- </button>
1395
- )}
1396
- </div>
1397
- </div>
1398
- </div>
1399
- );
1400
- }
1
+ export { default } from './setup';