ltcai 6.0.0 → 6.2.0

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 (54) hide show
  1. package/README.md +33 -35
  2. package/docs/CHANGELOG.md +68 -0
  3. package/docs/V4_1_FRONTEND_MIGRATION_REPORT.md +1 -1
  4. package/docs/V4_6_1_RELEASE_REFRESH_REPORT.md +1 -1
  5. package/docs/V4_7_0_ADMIN_SEPARATION_REPORT.md +1 -1
  6. package/docs/V4_7_1_ADMIN_OPERATIONS_REPORT.md +1 -1
  7. package/frontend/src/App.tsx +3 -1281
  8. package/frontend/src/components/LanguageSwitcher.tsx +23 -0
  9. package/frontend/src/components/ProductFlow.tsx +32 -662
  10. package/frontend/src/components/onboarding/ProductFlowScreens.tsx +688 -0
  11. package/frontend/src/features/admin/AdminConsole.tsx +294 -0
  12. package/frontend/src/features/brain/BrainHome.tsx +999 -0
  13. package/frontend/src/features/brain/brainData.ts +98 -0
  14. package/frontend/src/features/brain/graphLayout.ts +26 -0
  15. package/frontend/src/features/brain/types.ts +44 -0
  16. package/frontend/src/features/review/ReviewCard.tsx +15 -10
  17. package/frontend/src/i18n.ts +208 -0
  18. package/frontend/src/styles.css +240 -0
  19. package/lattice_brain/__init__.py +1 -1
  20. package/lattice_brain/runtime/multi_agent.py +1 -1
  21. package/latticeai/__init__.py +1 -1
  22. package/latticeai/api/chat.py +52 -33
  23. package/latticeai/api/tools.py +50 -23
  24. package/latticeai/app_factory.py +65 -47
  25. package/latticeai/cli/__init__.py +1 -0
  26. package/latticeai/cli/entrypoint.py +283 -0
  27. package/latticeai/cli/runtime.py +37 -0
  28. package/latticeai/core/marketplace.py +1 -1
  29. package/latticeai/core/workspace_os.py +1 -1
  30. package/latticeai/integrations/__init__.py +0 -0
  31. package/latticeai/integrations/telegram_bot.py +1009 -0
  32. package/latticeai/runtime/lifespan_runtime.py +1 -1
  33. package/latticeai/runtime/platform_runtime_wiring.py +87 -0
  34. package/latticeai/runtime/router_registration.py +49 -30
  35. package/latticeai/services/app_context.py +1 -0
  36. package/latticeai/services/p_reinforce.py +258 -0
  37. package/latticeai/services/router_context.py +52 -0
  38. package/latticeai/services/tool_dispatch.py +82 -25
  39. package/ltcai_cli.py +7 -305
  40. package/p_reinforce.py +4 -255
  41. package/package.json +2 -1
  42. package/scripts/release_smoke.py +133 -0
  43. package/scripts/wheel_smoke.py +4 -0
  44. package/src-tauri/Cargo.lock +1 -1
  45. package/src-tauri/Cargo.toml +1 -1
  46. package/src-tauri/tauri.conf.json +1 -1
  47. package/static/app/asset-manifest.json +5 -5
  48. package/static/app/assets/{index-xRn29gI8.css → index-B2-1Gm0q.css} +1 -1
  49. package/static/app/assets/index-D91Rz5--.js +16 -0
  50. package/static/app/assets/index-D91Rz5--.js.map +1 -0
  51. package/static/app/index.html +2 -2
  52. package/telegram_bot.py +9 -1008
  53. package/static/app/assets/index-D2zafMYb.js +0 -16
  54. package/static/app/assets/index-D2zafMYb.js.map +0 -1
@@ -1,42 +1,22 @@
1
1
  import * as React from "react";
2
- import { CheckCircle2, ChevronRight, Cpu, Download, LockKeyhole, MonitorCog, Sparkles } from "lucide-react";
3
2
  import { latticeApi } from "@/api/client";
4
- import { LivingBrain } from "@/components/LivingBrain";
5
- import { Badge } from "@/components/ui/badge";
6
- import { Button } from "@/components/ui/button";
7
- import { Input } from "@/components/ui/input";
8
- import { cn, asArray } from "@/lib/utils";
9
- import { LANGUAGE_LABELS, t, type Language } from "@/i18n";
3
+ import { type BrainState, LivingBrain } from "@/components/LivingBrain";
4
+ import { t } from "@/i18n";
10
5
  import { useAppStore } from "@/store/appStore";
6
+ import {
7
+ AnalysisScreen,
8
+ InstallScreen,
9
+ LanguageChooser,
10
+ LoginScreen,
11
+ RecommendationScreen,
12
+ buildRecommendations,
13
+ fallbackModel,
14
+ type FlowAnalysis,
15
+ type FlowStep,
16
+ type RecommendedModel,
17
+ } from "@/components/onboarding/ProductFlowScreens";
11
18
 
12
19
  const FLOW_COMPLETE_KEY = "lattice.productFlow.complete";
13
- const FLOW_USER_KEY = "lattice.productFlow.user";
14
-
15
- type FlowStep = "login" | "analysis" | "recommend" | "install";
16
- type ApiData = Record<string, unknown>;
17
-
18
- type FlowAnalysis = {
19
- setup?: ApiData | null;
20
- models?: ApiData | null;
21
- recommendations?: ApiData | null;
22
- sysinfo?: ApiData | null;
23
- };
24
-
25
- type RecommendedModel = {
26
- id: string;
27
- loadId: string;
28
- engine: string;
29
- name: string;
30
- shortName: string;
31
- family: string;
32
- size: string;
33
- role: "best" | "faster" | "advanced";
34
- reason: string;
35
- supported: boolean;
36
- downloadRequired: boolean;
37
- };
38
-
39
- type InstallStage = "idle" | "install" | "download" | "validate" | "load" | "done" | "error";
40
20
 
41
21
  export function readProductFlowComplete() {
42
22
  try {
@@ -45,14 +25,6 @@ export function readProductFlowComplete() {
45
25
  return false;
46
26
  }
47
27
 
48
- function readSavedFlowUser(): { email?: string; name?: string } | null {
49
- try {
50
- const raw = localStorage.getItem(FLOW_USER_KEY);
51
- return raw ? JSON.parse(raw) : null;
52
- } catch {}
53
- return null;
54
- }
55
-
56
28
  export function ProductFlow({ onComplete }: { onComplete: () => void }) {
57
29
  const language = useAppStore((state) => state.language);
58
30
  const [step, setStep] = React.useState<FlowStep>("login");
@@ -75,10 +47,10 @@ export function ProductFlow({ onComplete }: { onComplete: () => void }) {
75
47
  ]);
76
48
  if (cancelled) return;
77
49
  setAnalysis({
78
- setup: setup.ok ? setup.data as ApiData : null,
79
- recommendations: recommendationsResult.ok ? recommendationsResult.data as ApiData : null,
80
- models: models.ok ? models.data as ApiData : null,
81
- sysinfo: sysinfo.ok ? sysinfo.data as ApiData : null,
50
+ setup: setup.ok ? setup.data as Record<string, unknown> : null,
51
+ recommendations: recommendationsResult.ok ? recommendationsResult.data as Record<string, unknown> : null,
52
+ models: models.ok ? models.data as Record<string, unknown> : null,
53
+ sysinfo: sysinfo.ok ? sysinfo.data as Record<string, unknown> : null,
82
54
  });
83
55
  if (!setup.ok && !recommendationsResult.ok && !models.ok) {
84
56
  setAnalysisError(t(language, "flow.analysis.error"));
@@ -92,37 +64,21 @@ export function ProductFlow({ onComplete }: { onComplete: () => void }) {
92
64
  <div className="ritual-shell" aria-label={t(language, "flow.shell")}>
93
65
  <div className="ritual-container">
94
66
  <LanguageChooser />
95
- {/* The living presence participates in the ritual at every step */}
96
67
  <div className="ritual-brain">
97
- <LivingBrain
98
- state={
99
- step === "login" ? "idle" :
100
- step === "analysis" ? "listening" :
101
- step === "recommend" ? "recalling" :
102
- "thinking"
103
- }
104
- intensity={step === "install" ? 0.92 : 0.7}
105
- size="large"
106
- showLabel={false}
107
- />
68
+ <LivingBrain state={brainStateForStep(step)} intensity={step === "install" ? 0.92 : 0.7} size="large" showLabel={false} />
108
69
  </div>
109
70
 
110
- {step === "login" && (
111
- <LoginScreen onSuccess={() => setStep("analysis")} />
112
- )}
71
+ {step === "login" && <LoginScreen onSuccess={() => setStep("analysis")} />}
113
72
 
114
73
  {step === "analysis" && (
115
- <AnalysisScreen
116
- analysis={analysis}
117
- error={analysisError}
118
- onContinue={() => setStep("recommend")}
119
- />
74
+ <AnalysisScreen analysis={analysis} error={analysisError} onContinue={() => setStep("recommend")} />
120
75
  )}
121
76
 
122
77
  {step === "recommend" && (
123
78
  <RecommendationScreen
124
79
  recommendations={recommendations}
125
80
  onBack={() => setStep("analysis")}
81
+ onSkipModel={() => completeFlow(onComplete)}
126
82
  onSelect={(model) => {
127
83
  setSelected(model);
128
84
  setStep("install");
@@ -134,10 +90,8 @@ export function ProductFlow({ onComplete }: { onComplete: () => void }) {
134
90
  <InstallScreen
135
91
  model={selected || recommendations[0] || fallbackModel()}
136
92
  onBack={() => setStep("recommend")}
137
- onComplete={() => {
138
- try { localStorage.setItem(FLOW_COMPLETE_KEY, "true"); } catch {}
139
- onComplete();
140
- }}
93
+ onComplete={() => completeFlow(onComplete)}
94
+ onLater={() => completeFlow(onComplete)}
141
95
  />
142
96
  )}
143
97
  </div>
@@ -145,598 +99,14 @@ export function ProductFlow({ onComplete }: { onComplete: () => void }) {
145
99
  );
146
100
  }
147
101
 
148
- function LanguageChooser() {
149
- const language = useAppStore((state) => state.language);
150
- const setLanguage = useAppStore((state) => state.setLanguage);
151
-
152
- return (
153
- <div className="language-switcher ritual-language" aria-label={t(language, "language.label")}>
154
- {(["ko", "en"] as Language[]).map((item) => (
155
- <button
156
- key={item}
157
- type="button"
158
- className={language === item ? "is-active" : ""}
159
- onClick={() => setLanguage(item)}
160
- aria-pressed={language === item}
161
- >
162
- {LANGUAGE_LABELS[item]}
163
- </button>
164
- ))}
165
- </div>
166
- );
167
- }
168
-
169
- function LoginScreen({ onSuccess }: { onSuccess: () => void }) {
170
- const language = useAppStore((state) => state.language);
171
- const [email, setEmail] = React.useState(() => {
172
- return readSavedFlowUser()?.email || "you@local";
173
- });
174
- const [password, setPassword] = React.useState("");
175
- const [name, setName] = React.useState(() => readSavedFlowUser()?.name || "You");
176
- const [busy, setBusy] = React.useState(false);
177
- const [error, setError] = React.useState<string | null>(null);
178
-
179
- async function submit(event: React.FormEvent) {
180
- event.preventDefault();
181
- const cleanEmail = email.trim();
182
- const cleanPassword = password.trim();
183
- const cleanName = name.trim() || cleanEmail.split("@")[0] || "You";
184
- if (!cleanEmail || !cleanPassword) {
185
- setError(t(language, "flow.login.missing"));
186
- return;
187
- }
188
- setBusy(true);
189
- setError(null);
190
- const savedUser = readSavedFlowUser();
191
- let result = await latticeApi.login(cleanEmail, cleanPassword);
192
- if (!result.ok) {
193
- const profile = await latticeApi.profile();
194
- if (profile.ok && (!savedUser?.email || savedUser.email === cleanEmail)) {
195
- try { localStorage.setItem(FLOW_USER_KEY, JSON.stringify({ email: cleanEmail, name: cleanName })); } catch {}
196
- setBusy(false);
197
- onSuccess();
198
- return;
199
- }
200
- if (savedUser?.email && savedUser.email !== cleanEmail) {
201
- setBusy(false);
202
- setError(t(language, "flow.login.otherEmail"));
203
- return;
204
- }
205
- if (savedUser?.email === cleanEmail) {
206
- setBusy(false);
207
- setError(t(language, "flow.login.wrongPassword"));
208
- return;
209
- }
210
- const registered = await latticeApi.register({
211
- email: cleanEmail,
212
- password: cleanPassword,
213
- name: cleanName,
214
- nickname: cleanName,
215
- });
216
- if (registered.ok) result = await latticeApi.login(cleanEmail, cleanPassword);
217
- }
218
- if (!result.ok) {
219
- setBusy(false);
220
- setError(t(language, "flow.login.unavailable"));
221
- return;
222
- }
223
- try { localStorage.setItem(FLOW_USER_KEY, JSON.stringify({ email: cleanEmail, name: cleanName })); } catch {}
224
- setBusy(false);
225
- onSuccess();
226
- }
227
-
228
- return (
229
- <div>
230
- <div className="ritual-title">{t(language, "flow.login.title")}</div>
231
- <div className="ritual-subtitle">{t(language, "flow.login.body")}</div>
232
-
233
- <ProductPromise />
234
-
235
- <form onSubmit={submit} className="ritual-card" style={{ maxWidth: 420, margin: "0 auto" }}>
236
- <div style={{ display: "grid", gap: "0.85rem" }}>
237
- <div>
238
- <div style={{ fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "1px", color: "hsl(var(--fg-muted))", marginBottom: 4 }}>{t(language, "flow.name")}</div>
239
- <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="You" />
240
- </div>
241
- <div>
242
- <div style={{ fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "1px", color: "hsl(var(--fg-muted))", marginBottom: 4 }}>{t(language, "flow.email")}</div>
243
- <Input value={email} onChange={(e) => setEmail(e.target.value)} type="email" placeholder="you@local" />
244
- </div>
245
- <div>
246
- <div style={{ fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "1px", color: "hsl(var(--fg-muted))", marginBottom: 4 }}>{t(language, "flow.password")}</div>
247
- <Input value={password} onChange={(e) => setPassword(e.target.value)} type="password" placeholder={t(language, "flow.password.placeholder")} />
248
- </div>
249
- </div>
250
-
251
- {error && <div style={{ marginTop: "0.85rem", padding: "0.6rem 0.85rem", background: "hsl(var(--destructive)/0.12)", border: "1px solid hsl(var(--destructive)/0.4)", borderRadius: 10, fontSize: "0.9rem" }}>{error}</div>}
252
-
253
- <Button type="submit" disabled={busy || !email.trim() || !password.trim()} style={{ width: "100%", marginTop: "1rem" }}>
254
- {busy ? t(language, "flow.login.busy") : t(language, "flow.login.submit")}
255
- </Button>
256
- <div style={{ fontSize: "0.75rem", color: "hsl(var(--fg-muted))", marginTop: "0.6rem" }}>
257
- {t(language, "flow.login.note")}
258
- </div>
259
- </form>
260
- </div>
261
- );
262
- }
263
-
264
- function ProductPromise() {
265
- const language = useAppStore((state) => state.language);
266
- return (
267
- <div className="ritual-promise" aria-label="Lattice AI product promise">
268
- <div>
269
- <span>{t(language, "flow.promise.memory.k")}</span>
270
- <strong>{t(language, "flow.promise.memory.v")}</strong>
271
- </div>
272
- <div>
273
- <span>{t(language, "flow.promise.model.k")}</span>
274
- <strong>{t(language, "flow.promise.model.v")}</strong>
275
- </div>
276
- <div>
277
- <span>{t(language, "flow.promise.ownership.k")}</span>
278
- <strong>{t(language, "flow.promise.ownership.v")}</strong>
279
- </div>
280
- </div>
281
- );
282
- }
283
-
284
- function AnalysisScreen({
285
- analysis,
286
- error,
287
- onContinue,
288
- }: {
289
- analysis: FlowAnalysis | null;
290
- error: string | null;
291
- onContinue: () => void;
292
- }) {
293
- const language = useAppStore((state) => state.language);
294
- const detected = buildDetectedFacts(analysis);
295
- return (
296
- <div>
297
- <div className="ritual-title">{t(language, "flow.analysis.title")}</div>
298
- <div className="ritual-subtitle">{t(language, "flow.analysis.body")}</div>
299
-
300
- <div className="ritual-fact-grid">
301
- {detected.map((item, idx) => (
302
- <div key={idx} className="ritual-fact">
303
- <div className="ritual-fact-label">{item.label}</div>
304
- <div className="ritual-fact-value">{item.value}</div>
305
- <div style={{ fontSize: "0.8rem", color: "hsl(var(--fg-muted))", marginTop: 3 }}>{item.detail}</div>
306
- </div>
307
- ))}
308
- </div>
309
-
310
- <div className="ritual-card" style={{ marginTop: "1rem" }}>
311
- <div style={{ display: "flex", alignItems: "center", gap: "0.6rem" }}>
312
- <Sparkles style={{ color: "hsl(var(--brain-core))" }} />
313
- <div>
314
- <div style={{ fontWeight: 620 }}>{analysis ? recommendedSummary(analysis, language) : t(language, "flow.analysis.finding")}</div>
315
- <div style={{ fontSize: "0.9rem", color: "hsl(var(--fg-muted))" }}>
316
- {analysis ? t(language, "flow.analysis.ready") : t(language, "flow.analysis.wait")}
317
- </div>
318
- </div>
319
- </div>
320
- </div>
321
-
322
- {error && <div className="ritual-card" style={{ borderColor: "hsl(var(--destructive)/0.4)", background: "hsl(var(--destructive)/0.06)" }}>{error}</div>}
323
-
324
- <div style={{ marginTop: "1.25rem" }}>
325
- <Button onClick={onContinue} disabled={!analysis && !error} style={{ minWidth: 260 }}>
326
- {t(language, "flow.analysis.continue")}
327
- </Button>
328
- </div>
329
- </div>
330
- );
331
- }
332
-
333
- function RecommendationScreen({
334
- recommendations,
335
- onBack,
336
- onSelect,
337
- }: {
338
- recommendations: RecommendedModel[];
339
- onBack: () => void;
340
- onSelect: (model: RecommendedModel) => void;
341
- }) {
342
- const language = useAppStore((state) => state.language);
343
- const items = recommendations.length ? recommendations : [fallbackModel()];
344
- return (
345
- <div>
346
- <div className="ritual-title">{t(language, "flow.recommend.title")}</div>
347
- <div className="ritual-subtitle">{t(language, "flow.recommend.body")}</div>
348
-
349
- <div style={{ maxWidth: 560, margin: "0 auto" }}>
350
- {items[0]?.supported ? (
351
- <Button onClick={() => onSelect(items[0])} style={{ width: "100%", marginBottom: "0.85rem" }}>
352
- {t(language, "flow.recommend.primary")}
353
- </Button>
354
- ) : null}
355
- {items.slice(0, 3).map((model, index) => (
356
- <button
357
- key={`${model.role}-${model.id}`}
358
- className="ritual-model-card"
359
- onClick={() => model.supported && onSelect(model)}
360
- disabled={!model.supported}
361
- style={{ width: "100%" }}
362
- >
363
- <div className="role">{rankLabel(model.role, index, language)}</div>
364
- <div className="name">{model.shortName}</div>
365
- <div className="reason">{model.reason} · {model.size || "ready"}</div>
366
- {!model.supported && <div style={{ color: "hsl(var(--destructive))", marginTop: 6, fontSize: "0.85rem" }}>{t(language, "flow.recommend.unsupported")}</div>}
367
- </button>
368
- ))}
369
- </div>
370
-
371
- <div style={{ marginTop: "1.1rem", display: "flex", justifyContent: "center", gap: "1rem", alignItems: "center" }}>
372
- <Button variant="ghost" onClick={onBack}>{t(language, "flow.recommend.back")}</Button>
373
- <div style={{ fontSize: "0.82rem", color: "hsl(var(--fg-muted))" }}>{t(language, "flow.recommend.hint")}</div>
374
- </div>
375
- </div>
376
- );
377
- }
378
-
379
- function InstallScreen({
380
- model,
381
- onBack,
382
- onComplete,
383
- }: {
384
- model: RecommendedModel;
385
- onBack: () => void;
386
- onComplete: () => void;
387
- }) {
388
- const language = useAppStore((state) => state.language);
389
- const [busy, setBusy] = React.useState(false);
390
- const [stage, setStage] = React.useState<InstallStage>("idle");
391
- const [percent, setPercent] = React.useState(0);
392
- const [message, setMessage] = React.useState(t(language, "flow.install.wait"));
393
- const [error, setError] = React.useState<string | null>(null);
394
-
395
- async function start() {
396
- setBusy(true);
397
- setError(null);
398
- setStage("install");
399
- setPercent(8);
400
- setMessage(t(language, "flow.install.prepare"));
401
- const result = await latticeApi.streamModelPrepare(
402
- { model: model.loadId, engine: model.engine || "local_mlx", allow_download: true },
403
- {
404
- onProgress: (event) => {
405
- const nextStage = friendlyInstallStage(String(event.stage || ""));
406
- setStage(nextStage);
407
- setPercent(Number(event.percent || percentForStage(nextStage)));
408
- setMessage(friendlyInstallMessage(event, nextStage, language));
409
- },
410
- onDone: () => {
411
- setStage("done");
412
- setPercent(100);
413
- setMessage(t(language, "flow.install.done"));
414
- },
415
- onError: (event) => {
416
- setStage("error");
417
- setError(consumerError(event));
418
- },
419
- },
420
- );
421
- setBusy(false);
422
- if (result.ok) {
423
- setStage("done");
424
- setPercent(100);
425
- setMessage(t(language, "flow.install.done"));
426
- window.setTimeout(onComplete, 700);
427
- } else {
428
- setStage("error");
429
- setError(consumerError(result.data as ApiData));
430
- }
431
- }
432
-
433
- const brainStateForStage: any =
434
- stage === "download" ? "thinking" :
435
- stage === "validate" ? "recalling" :
436
- stage === "load" ? "synthesizing" :
437
- stage === "done" ? "idle" : "listening";
438
-
439
- return (
440
- <div>
441
- <div className="ritual-title">{t(language, "flow.install.title")}</div>
442
- <div className="ritual-subtitle">
443
- <strong>{model.shortName}</strong> — {model.reason}.<br />
444
- {t(language, "flow.install.body")}
445
- </div>
446
-
447
- {/* Living Brain reacts to the ceremony of installation */}
448
- <div style={{ margin: "0.6rem auto 1rem" }}>
449
- <LivingBrain
450
- state={brainStateForStage}
451
- intensity={stage === "download" || stage === "load" ? 0.96 : 0.82}
452
- size="normal"
453
- />
454
- </div>
455
-
456
- <div className="ritual-progress">
457
- <div className="ritual-stage-list">
458
- {(["install", "download", "validate", "load"] as const).map((item) => (
459
- <div key={item} className={`ritual-stage ${installStepState(stage, item)}`}>
460
- <CheckCircle2 style={{ width: 15, height: 15 }} />
461
- <span>{installLabel(item, language)}</span>
462
- </div>
463
- ))}
464
- </div>
465
-
466
- <div className="ritual-bar">
467
- <span style={{ width: `${Math.max(4, Math.min(100, percent))}%` }} />
468
- </div>
469
- </div>
470
-
471
- <div className="ritual-status">{message}</div>
472
- <div className="ritual-card" style={{ margin: "0.8rem auto 0", maxWidth: 540, fontSize: "0.86rem", color: "hsl(var(--fg-muted))" }}>
473
- {t(language, "flow.install.note")}
474
- </div>
475
-
476
- {error && (
477
- <div className="ritual-card" style={{ borderColor: "hsl(var(--destructive)/0.45)", background: "hsl(var(--destructive)/0.07)", marginBottom: "1rem" }}>
478
- {error}
479
- <div style={{ marginTop: "0.5rem", fontSize: "0.85rem" }}>{t(language, "flow.install.retry")}</div>
480
- </div>
481
- )}
482
-
483
- <div style={{ display: "flex", gap: "0.75rem", justifyContent: "center", marginTop: "1rem" }}>
484
- <Button variant="ghost" onClick={onBack} disabled={busy}>{t(language, "flow.install.back")}</Button>
485
-
486
- {stage !== "done" ? (
487
- <Button
488
- onClick={start}
489
- disabled={busy || !model.supported}
490
- >
491
- {busy ? t(language, "flow.install.busy") : t(language, "flow.install.start")}
492
- </Button>
493
- ) : (
494
- <Button onClick={onComplete}>{t(language, "flow.install.enter")}</Button>
495
- )}
496
- </div>
497
-
498
- <div style={{ fontSize: "0.72rem", color: "hsl(var(--fg-muted))", marginTop: "0.9rem" }}>
499
- {t(language, "flow.install.local")}
500
- </div>
501
- </div>
502
- );
503
- }
504
-
505
- function buildDetectedFacts(analysis: FlowAnalysis | null) {
506
- if (!analysis) {
507
- return [
508
- { label: "Computer", value: "Checking", detail: "Operating system and chip" },
509
- { label: "Memory", value: "Checking", detail: "Available room for local thinking" },
510
- { label: "Graphics", value: "Checking", detail: "Local acceleration support" },
511
- { label: "Local Support", value: "Checking", detail: "Installed model helpers" },
512
- { label: "Models", value: "Checking", detail: "Installed local Brains" },
513
- ];
514
- }
515
- const setupEnv = asRecord(analysis.setup?.environment);
516
- const recProfile = asRecord(analysis.recommendations?.profile);
517
- const recs = asRecord(analysis.recommendations?.recommendations);
518
- const models = asRecord(analysis.models);
519
- const sysinfo = asRecord(analysis.sysinfo);
520
- const profile = { ...setupEnv, ...recProfile };
521
- const ramGb = Number(recs.ram_gb || Number(profile.ram_mb || 0) / 1024 || 0);
522
- const appleSilicon = Boolean(recs.apple_silicon || String(profile.arch || "").includes("arm"));
523
- const loadedModels = asArray(models.loaded);
524
- const gpu = asRecord(profile.gpu);
525
- const installedRuntimes = [
526
- ...asArray(setupEnv.installed_runtimes),
527
- ...asArray(profile.installed_runtimes),
528
- ...asArray(recs.installed_runtimes),
529
- ];
530
- return [
531
- {
532
- label: "Computer",
533
- value: appleSilicon ? "Apple Silicon Mac" : friendlyOs(profile.os),
534
- detail: "Ready for local Digital Brain use",
535
- },
536
- {
537
- label: "Memory",
538
- value: ramGb ? `${Math.round(ramGb)} GB` : "Detected",
539
- detail: "Enough context for the recommended model",
540
- },
541
- {
542
- label: "Graphics",
543
- value: gpu.vendor || sysinfo.gpu_mem_gb ? "Local acceleration ready" : "Standard local mode",
544
- detail: "Lattice will choose the best available path",
545
- },
546
- {
547
- label: "Local Support",
548
- value: installedRuntimes.length ? "Ready" : "Will be prepared",
549
- detail: installedRuntimes.length ? "Installed model helpers detected" : "Lattice will add what is needed",
550
- },
551
- {
552
- label: "Models",
553
- value: loadedModels.length ? `${loadedModels.length} already installed` : "None installed yet",
554
- detail: loadedModels.length ? "One can be loaded immediately" : "Lattice will guide the first install",
555
- },
556
- ];
557
- }
558
-
559
- function buildRecommendations(analysis: FlowAnalysis | null): RecommendedModel[] {
560
- const models = asRecord(analysis?.models);
561
- const modelRows = [
562
- ...asArray<ApiData>(models.recommended),
563
- ...asArray<ApiData>(models.catalog),
564
- ];
565
- const recommendationRoot = asRecord(analysis?.recommendations?.recommendations);
566
- const recRows = asArray<ApiData>(recommendationRoot.models);
567
- const topPick = asRecord(recommendationRoot.top_pick);
568
- const merged = new Map<string, ApiData>();
569
- for (const row of [...recRows, ...modelRows]) {
570
- const id = String(row.id || row.model_id || row.recommended_load_id || "");
571
- if (!id) continue;
572
- merged.set(id, { ...(merged.get(id) || {}), ...row });
573
- }
574
- if (topPick.id && !merged.has(String(topPick.id))) merged.set(String(topPick.id), topPick);
575
- const all = Array.from(merged.values()).map(toRecommendedModel).filter((item) => item.id);
576
- const supported = all.filter((item) => item.supported);
577
- const pool = supported.length ? supported : all;
578
- const byName = (pattern: RegExp) => pool.find((item) => pattern.test(`${item.name} ${item.id}`));
579
- const byId = (id?: unknown) => pool.find((item) => item.id === String(id));
580
- const best = byId(topPick.id) || byName(/gemma.*12|12b/i) || pool[0];
581
- const faster = pool.find((item) => item.id !== best?.id && /qwen|8b|7b/i.test(`${item.name} ${item.id}`)) || pool.find((item) => item.id !== best?.id);
582
- const advanced = pool.find((item) => item.id !== best?.id && item.id !== faster?.id && /26b|32b|70b|advanced/i.test(`${item.name} ${item.id}`))
583
- || pool.find((item) => item.id !== best?.id && item.id !== faster?.id);
584
- return [
585
- best ? { ...best, role: "best" as const, reason: "Best Experience" } : null,
586
- faster ? { ...faster, role: "faster" as const, reason: "Faster" } : null,
587
- advanced ? { ...advanced, role: "advanced" as const, reason: "Advanced" } : null,
588
- ].filter(Boolean) as RecommendedModel[];
589
- }
590
-
591
- function toRecommendedModel(row: ApiData): RecommendedModel {
592
- const compatibility = asRecord(row.runtime_compatibility);
593
- const id = String(row.id || row.model_id || row.recommended_load_id || "");
594
- const loadId = String(row.recommended_load_id || row.load_id || id);
595
- const name = String(row.display_name || row.name || id || "Recommended Brain");
596
- const supported = row.load_status !== "unsupported"
597
- && row.load_status !== "runtime_update_needed"
598
- && row.status !== "not_recommended"
599
- && compatibility.supported !== false;
600
- return {
601
- id,
602
- loadId,
603
- engine: String(row.recommended_engine || row.engine || "local_mlx"),
604
- name,
605
- shortName: friendlyModelName(name || id),
606
- family: friendlyModelName(String(row.family || name || "Local Brain")),
607
- size: String(row.size || ""),
608
- role: "best",
609
- reason: String(row.reason || "Recommended"),
610
- supported,
611
- downloadRequired: Boolean(row.download_required),
612
- };
613
- }
614
-
615
- function fallbackModel(): RecommendedModel {
616
- return {
617
- id: "mlx-community/Qwen3-VL-8B-Instruct-4bit",
618
- loadId: "mlx-community/Qwen3-VL-8B-Instruct-4bit",
619
- engine: "local_mlx",
620
- name: "Qwen3-VL 8B",
621
- shortName: "Qwen 3",
622
- family: "Qwen 3",
623
- size: "ready",
624
- role: "best",
625
- reason: "Best Experience",
626
- supported: true,
627
- downloadRequired: false,
628
- };
629
- }
630
-
631
- function rankLabel(role: RecommendedModel["role"], index: number, language: Language) {
632
- if (role === "best") return language === "ko" ? "추천" : "Best Experience";
633
- if (role === "faster") return language === "ko" ? "빠른 선택" : "Faster";
634
- if (role === "advanced") return language === "ko" ? "고급 선택" : "Advanced";
635
- return `Choice ${index + 1}`;
636
- }
637
-
638
- function recommendedSummary(analysis: FlowAnalysis, language: Language) {
639
- const recs = asRecord(analysis.recommendations?.recommendations);
640
- const topPick = asRecord(recs.top_pick);
641
- if (topPick.name || topPick.id) {
642
- const model = friendlyModelName(String(topPick.name || topPick.id));
643
- return language === "ko" ? `${model}이 이 컴퓨터에 가장 잘 맞습니다.` : `${model} looks like the best fit.`;
644
- }
645
- return language === "ko" ? "이 컴퓨터에는 개인 로컬 Brain을 추천합니다." : "A private local Brain is recommended for this computer.";
646
- }
647
-
648
- function friendlyModelName(value: string) {
649
- return String(value || "Recommended Brain")
650
- .replace(/^mlx-community\//i, "")
651
- .replace(/[-_]?Instruct/gi, "")
652
- .replace(/[-_]?4bit/gi, "")
653
- .replace(/Qwen3[-_ ]?VL/gi, "Qwen 3")
654
- .replace(/Qwen3/gi, "Qwen 3")
655
- .replace(/Gemma[-_ ]?4/gi, "Gemma 4")
656
- .replace(/A4B/gi, "")
657
- .replace(/[-_]+/g, " ")
658
- .replace(/\s+/g, " ")
659
- .trim();
660
- }
661
-
662
- function friendlyOs(value: unknown) {
663
- const text = String(value || "Computer");
664
- if (/darwin|mac/i.test(text)) return "Mac";
665
- if (/win/i.test(text)) return "Windows PC";
666
- if (/linux/i.test(text)) return "Linux computer";
667
- return "Computer";
668
- }
669
-
670
- function friendlyInstallStage(stage: string): InstallStage {
671
- if (/download|pull|weights/i.test(stage)) return "download";
672
- if (/smoke|validate|verify|test/i.test(stage)) return "validate";
673
- if (/load|ready/i.test(stage)) return "load";
674
- if (/done|complete/i.test(stage)) return "done";
675
- return "install";
676
- }
677
-
678
- function percentForStage(stage: InstallStage) {
679
- if (stage === "install") return 20;
680
- if (stage === "download") return 55;
681
- if (stage === "validate") return 82;
682
- if (stage === "load") return 94;
683
- if (stage === "done") return 100;
684
- return 8;
685
- }
686
-
687
- function friendlyInstallMessage(event: ApiData, stage: InstallStage, language: Language) {
688
- const fallback = {
689
- install: t(language, "flow.install.prepare"),
690
- download: language === "ko" ? "모델 파일을 받는 중입니다." : "Getting the model files.",
691
- validate: language === "ko" ? "Brain이 응답할 수 있는지 확인 중입니다." : "Checking that the Brain can answer.",
692
- load: language === "ko" ? "Brain을 불러오는 중입니다." : "Loading the Brain.",
693
- done: t(language, "flow.install.done"),
694
- idle: t(language, "flow.install.wait"),
695
- error: language === "ko" ? "확인이 필요한 일이 있습니다." : "Something needs attention.",
696
- }[stage];
697
- return cleanConsumerText(String(event.user_message || event.message || fallback));
698
- }
699
-
700
- function installLabel(stage: "install" | "download" | "validate" | "load", language: Language) {
701
- if (language === "ko") {
702
- if (stage === "install") return "준비";
703
- if (stage === "download") return "다운로드";
704
- if (stage === "validate") return "확인";
705
- return "로드";
706
- }
707
- if (stage === "install") return "Install";
708
- if (stage === "download") return "Download";
709
- if (stage === "validate") return "Validate";
710
- return "Load";
711
- }
712
-
713
- function installStepState(current: InstallStage, item: "install" | "download" | "validate" | "load") {
714
- const order: InstallStage[] = ["idle", "install", "download", "validate", "load", "done"];
715
- const currentIndex = order.indexOf(current);
716
- const itemIndex = order.indexOf(item);
717
- if (current === "error") return "is-error";
718
- if (current === "done" || currentIndex > itemIndex) return "is-done";
719
- if (current === item) return "is-active";
720
- return "";
721
- }
722
-
723
- function consumerError(data: ApiData | unknown) {
724
- const record = asRecord(data);
725
- const guidance = asArray<string>(record.recovery_guidance).map(cleanConsumerText).filter(Boolean);
726
- const message = cleanConsumerText(String(record.user_message || record.reason || record.error || "The selected model could not be loaded."));
727
- return [message, ...guidance.slice(0, 2)].join(" ");
728
- }
729
-
730
- function cleanConsumerText(value: string) {
731
- return String(value || "")
732
- .replace(/gemma4_unified/gi, "this model format")
733
- .replace(/mlx[-_ ]?vlm|mlx[-_ ]?lm|local_mlx|\bmlx\b|\bgguf\b|\bollama\b|huggingface|hugging face/gi, "local model support")
734
- .replace(/runtime/gi, "model support")
735
- .replace(/No module named ['\"][^'\"]+['\"]/gi, "A local support component is missing")
736
- .replace(/\s+/g, " ")
737
- .trim();
102
+ function completeFlow(onComplete: () => void) {
103
+ try { localStorage.setItem(FLOW_COMPLETE_KEY, "true"); } catch {}
104
+ onComplete();
738
105
  }
739
106
 
740
- function asRecord(value: unknown): ApiData {
741
- return value && typeof value === "object" && !Array.isArray(value) ? value as ApiData : {};
107
+ function brainStateForStep(step: FlowStep): BrainState {
108
+ if (step === "analysis") return "listening";
109
+ if (step === "recommend") return "recalling";
110
+ if (step === "install") return "thinking";
111
+ return "idle";
742
112
  }