From f9eeb4040c0fcb8f88c7294e7b029b415f72714d Mon Sep 17 00:00:00 2001 From: Matthias Platzer Date: Wed, 25 Nov 2026 00:46:15 +0100 Subject: [PATCH 1/3] feat(model-setup): the setup's page as React parts, and the studio's setup on them --- apps/web/package.json | 1 + apps/web/src/lib/i18n.ts | 129 +-- apps/web/src/studio/Harness.tsx | 269 ++----- apps/web/src/studio/LocalRuntime.tsx | 223 +---- apps/web/src/studio/SetupPage.tsx | 761 +++++------------- apps/web/src/styles/app.css | 1 + packages/model-setup/README.md | 9 + packages/model-setup/package.json | 53 +- packages/model-setup/src/react/client.test.ts | 24 + packages/model-setup/src/react/client.tsx | 281 +++++++ packages/model-setup/src/react/columns.tsx | 406 ++++++++++ packages/model-setup/src/react/css.d.ts | 1 + packages/model-setup/src/react/host.tsx | 66 ++ packages/model-setup/src/react/index.ts | 25 + packages/model-setup/src/react/keys.tsx | 259 ++++++ .../model-setup/src/react/terminal.tsx | 52 +- packages/model-setup/src/react/tone.ts | 71 ++ .../model-setup/src/server/routes.test.ts | 7 + packages/model-setup/src/server/routes.ts | 1 + packages/model-setup/src/texts.ts | 157 ++++ packages/model-setup/tsconfig.build.json | 2 +- packages/model-setup/tsconfig.json | 10 +- packages/model-setup/vitest.config.ts | 2 +- pnpm-lock.yaml | 30 + scripts/copy-check.mjs | 1 + 25 files changed, 1711 insertions(+), 1130 deletions(-) create mode 100644 packages/model-setup/src/react/client.test.ts create mode 100644 packages/model-setup/src/react/client.tsx create mode 100644 packages/model-setup/src/react/columns.tsx create mode 100644 packages/model-setup/src/react/css.d.ts create mode 100644 packages/model-setup/src/react/host.tsx create mode 100644 packages/model-setup/src/react/index.ts create mode 100644 packages/model-setup/src/react/keys.tsx rename apps/web/src/studio/Terminal.tsx => packages/model-setup/src/react/terminal.tsx (56%) create mode 100644 packages/model-setup/src/react/tone.ts create mode 100644 packages/model-setup/src/texts.ts diff --git a/apps/web/package.json b/apps/web/package.json index bffd3a07f..f50f1aadb 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -28,6 +28,7 @@ "@codemirror/view": "6.43.15", "@dagrejs/dagre": "^3.1.3", "@engenty/chatviews": "workspace:*", + "@engenty/model-setup": "workspace:*", "@engenty/wizards": "workspace:*", "@engenty/wizards-runner": "workspace:*", "@engenty/wizards-shared": "workspace:*", diff --git a/apps/web/src/lib/i18n.ts b/apps/web/src/lib/i18n.ts index 23cc297e6..aa78f04d7 100644 --- a/apps/web/src/lib/i18n.ts +++ b/apps/web/src/lib/i18n.ts @@ -1,3 +1,4 @@ +import { SETUP_TEXTS } from "@engenty/model-setup/texts"; import { RUNNER_TEXTS, type RunnerTable, @@ -21,6 +22,7 @@ import { useSyncExternalStore } from "react"; // own sentence, not a word-for-word copy of the other. Check with `pnpm copy:check`. const de: Record = { ...RUNNER_TEXTS.de, + ...SETUP_TEXTS.de, "brand.tagline": "Wünsch dir was. Hol dir deinen Wizard.", "brand.sub": "Er führt dich Schritt für Schritt. Die KI erledigt die Arbeit.", "auth.dev": "Dev-Login (lokal)", @@ -261,58 +263,6 @@ const de: Record = { "local.accountExpired": "Die Anmeldung ist abgelaufen. Melde dich neu an.", "local.sourceNeedsAccount": "Dafür brauchst du ein Konto.", "local.toAccount": "Zu Einstellungen → Konto", - "local.sourceOwn": "Eigene API-Keys", - "local.keys": "API-Keys", - "local.keysHint": - "Ein API-Key reicht. Testen prüft ihn beim Anbieter. Die Keys liegen im Schlüsselbund dieses Geräts, nie in der Datenbank.", - "local.keySet": "hinterlegt", - "local.keyRemove": "Entfernen", - "local.keyGet": "Key holen", - "local.keyWorks": "Funktioniert. Deine Wizards schreiben mit {model}.", - "local.keyWorksOther": "Funktioniert. Deine Wizards schreiben weiter mit {model}.", - "local.keyWorksPlain": "Funktioniert.", - "local.ollamaWhere": "auf diesem Computer", - "local.modelsLater": - "Welches Modell was übernimmt, lässt sich später unter Einstellungen → Modelle ändern.", - "harness.hint": - "Texte schreibt {name} auf diesem Computer, mit deinem {sub}. Kein API-Key nötig. Bilder, Videos und Audio brauchen weiter einen API-Key.", - "harness.hintImages": - "Texte und Bilder erzeugt {name} auf diesem Computer, mit deinem {sub}. Kein API-Key nötig. Videos und Audio brauchen weiter einen API-Key.", - "harness.found": "{name} {version} gefunden", - "harness.missing": "{name} ist auf diesem Computer nicht installiert.", - "harness.install": "Oder in deinem eigenen Terminal:", - "harness.installButton": "{name} installieren", - "harness.installing": - "{name} wird im Terminal unten installiert – das dauert etwa eine Minute. Danach meldest du es an.", - "harness.installEnded": - "Die Installation ist fertig, aber {name} ist nicht da. Warum, steht oben.", - "harness.appHere": - "Die {app}-App ist auf diesem Computer: {name} meldet sich mit demselben {sub} an.", - "harness.notInstalled": "nicht installiert", - "harness.authSubscription": "Angemeldet mit deinem {sub}.", - "harness.authKey": - "Angemeldet mit einem API-Key aus deiner Shell, nicht mit dem Abo. Melde dich hier an, damit es über dein {sub} läuft.", - "harness.authNone": "Noch nicht angemeldet.", - "harness.signIn": "Hier anmelden", - "harness.signingIn": - "Die Anmeldung läuft im Terminal unten – dein Browser öffnet sich dafür. Das Terminal schließt sich, sobald die Anmeldung da ist.", - "harness.signInInteractive": - "Unten startet {name}. Wähle dort die Anmeldung mit deinem {sub} und melde dich im Browser an. Das Terminal schließt sich, sobald die Anmeldung da ist.", - "harness.loginEnded": "Die Anmeldung wurde beendet, ohne dass {name} angemeldet ist.", - "harness.sub.claude": "Claude-Abo", - "harness.sub.codex": "ChatGPT-Abo", - "harness.sub.antigravity": "Google-AI-Abo", - "harness.sub.cursor": "Cursor-Abo", - "harness.desc.claude": "Mit deinem Claude-Abo – kein API-Key nötig.", - "harness.desc.codex": "Mit deinem ChatGPT-Abo – kein API-Key nötig.", - "harness.desc.antigravity": "Mit deinem Google-AI-Abo – kein API-Key nötig.", - "harness.desc.cursor": "Mit deinem Cursor-Abo – kein API-Key nötig.", - "harness.ready": "angemeldet", - "local.recheck": "Erneut prüfen", - "local.test": "Testen", - "local.testHint": "Ein kurzer Aufruf prüft, ob das Modell erreichbar ist.", - "local.testOk": "Antwort in {s} s über {ref}: „{reply}“", - "local.testFailed": "Der Test hat nicht geklappt: {error}", "models.groupStudio": "Im Studio", "models.groupRuns": "Agents & Wizards", "models.cap.chat": "Studio-Chat (Goose)", @@ -876,24 +826,12 @@ const de: Record = { "onboard.sectorHint": "Danach wählt das Studio deine Vorlagen:", "onboard.catalog": "Wizards für {sector}", "onboard.step": "Schritt {n} von {total}", - "setup.stage.connect": "Verbinden", - "setup.stage.test": "Testen", - "setup.stage.done": "Fertig", - "setup.h.install": "{name} installieren", - "setup.h.signIn": "{name} anmelden", - "setup.h.keys": "API-Key eintragen", - "setup.h.test": "Ein kurzer Test", - "setup.h.done": "Verbunden", - "setup.ready": "Alles bereit.", - "setup.noHarness": - "Noch kein KI-Client installiert. Wähle einen aus – er wird dann hier installiert. Oder trage eigene API-Keys ein.", "setup.ownDesc": "OpenAI, Anthropic, Google, AI Gateway oder Ollama.", "setup.appleDesc": "Das Modell auf diesem Mac – ohne Konto, ohne Internet.", "setup.appleHint": "Kurze Texte und Entscheidungen übernimmt Apple Intelligence auf diesem Mac. Nichts verlässt ihn. Für Recherche, lange Dokumente und Code richtest du später unter Einstellungen → Modelle einen weiteren Zugang ein.", "setup.appleHintKeeps": "Kurze Texte und Entscheidungen übernimmt Apple Intelligence auf diesem Mac. Nichts verlässt ihn. Recherche, lange Dokumente und Code (Standard, High) bleiben, wie sie waren: {way}.", - "setup.recommended": "Empfohlen", "setup.done": "Zum Studio", "setup.untilWorks": "Das Studio öffnet sich, sobald der Test klappt.", "cloud.notSent": "Diese Version ist noch nicht in der Cloud.", @@ -5156,6 +5094,7 @@ export type Key = keyof typeof en; const en = { ...RUNNER_TEXTS.en, + ...SETUP_TEXTS.en, "brand.tagline": "Make a wish. Get your wizard.", "brand.sub": "It guides you step by step. Let AI do the work.", "auth.dev": "Developer sign-in (local)", @@ -5390,56 +5329,6 @@ const en = { "local.accountExpired": "Your sign-in has expired. Sign in again.", "local.sourceNeedsAccount": "This needs an account.", "local.toAccount": "Go to Settings → Account", - "local.sourceOwn": "Your own keys", - "local.keys": "Keys", - "local.keysHint": - "One key is enough. Test checks it with the provider. Keys stay in this computer’s keychain, never in the database.", - "local.keySet": "stored", - "local.keyRemove": "Delete", - "local.keyGet": "Get a key", - "local.keyWorks": "Works. Your wizards write with {model}.", - "local.keyWorksOther": "Works. Your wizards keep writing with {model}.", - "local.keyWorksPlain": "Works.", - "local.ollamaWhere": "on this computer", - "local.modelsLater": "Which model does which job can be changed later under Settings → Models.", - "harness.hint": - "Text runs on {name} on this computer, using your {sub}. No key needed. Images, video and audio still need a key.", - "harness.hintImages": - "Text and images run on {name} on this computer, using your {sub}. No key needed. Video and audio still need a key.", - "harness.found": "{name} {version} found", - "harness.missing": "{name} isn’t installed on this computer.", - "harness.install": "Or in your own terminal:", - "harness.installButton": "Install {name}", - "harness.installing": - "{name} is installing in the terminal below – it takes about a minute. Then you sign in.", - "harness.installEnded": - "The installation ended, but {name} isn’t there. The output above says why.", - "harness.appHere": "The {app} app is on this computer: {name} signs in with the same {sub}.", - "harness.notInstalled": "not installed", - "harness.authSubscription": "Signed in with your {sub}.", - "harness.authKey": - "Signed in with an API key from your shell, not the subscription. Sign in here so it runs on your {sub}.", - "harness.authNone": "Not signed in yet.", - "harness.signIn": "Sign in here", - "harness.signingIn": - "The sign-in runs in the terminal below – your browser opens for it. The terminal closes once you’re signed in.", - "harness.signInInteractive": - "{name} starts below. Choose to sign in with your {sub} there, then finish in the browser. The terminal closes once you’re signed in.", - "harness.loginEnded": "The sign-in ended, but {name} isn’t signed in. Try again.", - "harness.sub.claude": "Claude subscription", - "harness.sub.codex": "ChatGPT subscription", - "harness.sub.antigravity": "Google AI subscription", - "harness.sub.cursor": "Cursor subscription", - "harness.desc.claude": "On your Claude subscription – no key needed.", - "harness.desc.codex": "On your ChatGPT subscription – no key needed.", - "harness.desc.antigravity": "On your Google AI subscription – no key needed.", - "harness.desc.cursor": "On your Cursor subscription – no key needed.", - "harness.ready": "signed in", - "local.recheck": "Check again", - "local.test": "Test", - "local.testHint": "One short call checks that the model can be reached.", - "local.testOk": "Answered in {s} s on {ref}: “{reply}”", - "local.testFailed": "The test didn’t work: {error}", "models.groupStudio": "In the studio", "models.groupRuns": "Agents & wizards", "models.cap.chat": "Studio chat (Goose)", @@ -5988,24 +5877,12 @@ const en = { "onboard.sectorHint": "The studio picks your templates by it:", "onboard.catalog": "Wizards for {sector}", "onboard.step": "Step {n} of {total}", - "setup.stage.connect": "Connect", - "setup.stage.test": "Test", - "setup.stage.done": "Done", - "setup.h.install": "Install {name}", - "setup.h.signIn": "Sign in to {name}", - "setup.h.keys": "Enter a key", - "setup.h.test": "One short test", - "setup.h.done": "Connected.", - "setup.ready": "All set.", - "setup.noHarness": - "No AI client is installed yet. Choose one and it installs right here, or enter your own keys.", "setup.ownDesc": "OpenAI, Anthropic, Google, AI Gateway or Ollama.", "setup.appleDesc": "The model on this Mac – no account, no internet.", "setup.appleHint": "Apple Intelligence handles short texts and decisions on this Mac; nothing leaves it. For research, long documents and code, add another option later under Settings → Models.", "setup.appleHintKeeps": "Apple Intelligence handles short texts and decisions on this Mac; nothing leaves it. Research, long documents and code (Standard, High) stay as they were: {way}.", - "setup.recommended": "Recommended", "setup.done": "Open the studio", "setup.untilWorks": "The studio opens once the test works.", "cloud.notSent": "This version hasn’t arrived in the cloud yet.", diff --git a/apps/web/src/studio/Harness.tsx b/apps/web/src/studio/Harness.tsx index 4ba3b54e3..19a35503c 100644 --- a/apps/web/src/studio/Harness.tsx +++ b/apps/web/src/studio/Harness.tsx @@ -1,78 +1,60 @@ -import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { Check, RefreshCw } from "lucide-react"; -import { useEffect, useRef, useState } from "react"; +import { + ClientPanel, + type SetupHostApi, + ModelTest as SetupModelTest, + SetupProvider, +} from "@engenty/model-setup/react"; +import { useQueryClient } from "@tanstack/react-query"; +import { type ReactNode, useMemo } from "react"; +import { withBase } from "@/lib/base"; import { api } from "../lib/api"; -import { t } from "../lib/i18n"; +import { useLang } from "../lib/i18n"; import type { HarnessId, Me } from "../lib/session"; -import { Button, cn } from "../ui"; -import { Terminal } from "./Terminal"; +import { openExternal } from "./LocalRuntime"; -interface TestResult { - ok: boolean; - ref?: string; - reply?: string; - error?: string; - ms: number; +/** The setup's routes of a runtime that runs alone. */ +const LOCAL = "/api/studio/local"; + +/** The studio around the setup's parts (@engenty/model-setup): its calls, its language. */ +export function StudioSetup({ children }: { children: ReactNode }) { + const qc = useQueryClient(); + const lang = useLang(); + const host = useMemo( + () => ({ + lang, + post: (path, body) => api.post(`${LOCAL}${path}`, body), + put: (path, body) => api.put(`${LOCAL}${path}`, body), + del: (path) => api.del(`${LOCAL}${path}`), + follow(terminal, on) { + const source = new EventSource(withBase(`${LOCAL}/terminal/${terminal}/stream`), { + withCredentials: true, + }); + source.addEventListener("data", (e) => on(JSON.parse((e as MessageEvent).data))); + source.addEventListener("done", () => on({ type: "done" })); + source.addEventListener("exit", (e) => { + source.close(); + on(JSON.parse((e as MessageEvent).data)); + }); + return () => source.close(); + }, + open: openExternal, + changed: () => qc.invalidateQueries({ queryKey: ["me"] }), + }), + [qc, lang], + ); + return {children}; } -/** - * One short call on the classifier class, as a run would make it; the answer shows the way is - * open. `auto`: the call is made right away — the setup tests by itself once a source is ready. - */ +/** The short call that shows the way to a model is open. */ export function ModelTest({ auto = false }: { auto?: boolean }) { - const qc = useQueryClient(); - const test = useMutation({ - mutationFn: () => api.post("/api/studio/local/models/test", { cls: "classifier" }), - // A working call ends the setup: the studio learns it from `me`. - onSuccess: (r) => (r.ok ? qc.invalidateQueries({ queryKey: ["me"] }) : undefined), - }); - const { mutate } = test; - const started = useRef(false); - useEffect(() => { - if (auto && !started.current) { - started.current = true; - mutate(); - } - }, [auto, mutate]); - const r = test.data; return ( -
-

{t("local.testHint")}

-
- -
- {r?.ok ? ( -

- - - {t("local.testOk", { - s: (r.ms / 1000).toFixed(1), - ref: r.ref ?? "", - reply: r.reply ?? "", - })} - -

- ) : null} - {r && !r.ok ? ( -

- {t("local.testFailed", { error: r.error ?? "" })} -

- ) : null} - {test.isError ? ( -

- {t("local.testFailed", { error: (test.error as Error).message })} -

- ) : null} -
+ + + ); } -/** - * One AI client on this machine: found with its version, how it is signed in, the sign-in - * itself in an inline terminal, and the test call. The setup and the settings both show it. - */ +/** One AI client on this machine; the setup and the settings both show it. */ export function HarnessPanel({ me, id, @@ -83,157 +65,10 @@ export function HarnessPanel({ /** Make the test call without a click as soon as the client is signed in. */ autoTest?: boolean; }) { - const qc = useQueryClient(); const client = me.harnesses.find((h) => h.id === id); - // The inline terminal runs the install or the sign-in; one of them at a time. - const [terminal, setTerminal] = useState<{ id: string; job: "install" | "login" } | null>(null); - const [ended, setEnded] = useState(null); - const recheck = useMutation({ - mutationFn: () => api.post(`/api/studio/local/harness/${id}/detect`), - onSuccess: () => qc.invalidateQueries({ queryKey: ["me"] }), - }); - const open = (job: "install" | "login") => ({ - mutationFn: () => - api.post<{ terminal: string }>(`/api/studio/local/harness/${id}/${job}`, { - cols: 100, - rows: 24, - }), - onSuccess: ({ terminal: started }: { terminal: string }) => { - setTerminal({ id: started, job }); - setEnded(null); - }, - }); - const install = useMutation(open("install")); - const login = useMutation(open("login")); - const signedIn = client?.auth === "subscription"; - const installed = client ? client.version !== null : false; - // What the terminal was for is there and its command is over: it has done its job. - useEffect(() => { - if (ended !== null && (terminal?.job === "install" ? installed : signedIn)) { - setTerminal(null); - } - }, [signedIn, installed, ended, terminal?.job]); - if (!client) { - return null; - } - const sub = t(`harness.sub.${id}`); - const again = ( - - ); - return ( -
-

- {t(client.images ? "harness.hintImages" : "harness.hint", { name: client.name, sub })} -

- {installed ? ( -
-

- - {t("harness.found", { name: client.name, version: client.version ?? "" })} -

-

- {signedIn - ? t("harness.authSubscription", { sub }) - : client.auth === "api_key" - ? t("harness.authKey", { sub }) - : t("harness.authNone")} -

- {signedIn || terminal ? null : ( -
- - {again} -
- )} - {login.isError ? ( -

{(login.error as Error).message}

- ) : null} -
- ) : ( -
-

{t("harness.missing", { name: client.name })}

- {client.app ? ( -

- {t("harness.appHere", { app: client.app, name: client.name, sub })} -

- ) : null} - {terminal ? null : ( -
- - {again} -
- )} - {install.isError ? ( -

{(install.error as Error).message}

- ) : null} -

- {t("harness.install")}{" "} - - {client.install} - -

-
- )} - {terminal ? ( -
-

- {terminal.job === "install" - ? t("harness.installing", { name: client.name }) - : client.interactiveLogin - ? t("harness.signInInteractive", { name: client.name, sub }) - : t("harness.signingIn")} -

- recheck.mutate()} - onExit={(code) => { - setEnded(code); - recheck.mutate(); - }} - /> -
- {ended === null ? ( - - ) : ( - <> - - {terminal.job === "install" ? ( - installed ? null : ( - - {t("harness.installEnded", { name: client.name })} - - ) - ) : signedIn ? null : ( - - {t("harness.loginEnded", { name: client.name })} - - )} - - )} -
-
- ) : null} - {/* A new sign-in is a new start: the test of the old one is put away. */} - {installed ? ( - - ) : null} -
- ); + return client ? ( + + + + ) : null; } diff --git a/apps/web/src/studio/LocalRuntime.tsx b/apps/web/src/studio/LocalRuntime.tsx index 0ebaba647..0a873d1cc 100644 --- a/apps/web/src/studio/LocalRuntime.tsx +++ b/apps/web/src/studio/LocalRuntime.tsx @@ -1,16 +1,8 @@ -import { - modelLabel, - PROVIDERS, - type ProviderInfo, - providerOfRef, -} from "@engenty/wizards-shared/providers"; -import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { Check, ExternalLink } from "lucide-react"; -import { type ReactNode, useState } from "react"; +import { OllamaAddress, OwnKeys } from "@engenty/model-setup/react"; +import { modelLabel, PROVIDERS, providerOfRef } from "@engenty/wizards-shared/providers"; import { api } from "../lib/api"; import { t } from "../lib/i18n"; import type { LocalModels } from "../lib/session"; -import { Button, cn, Input, Label } from "../ui"; /** Opens a page in the person's own browser — also from inside the desktop app's window. */ export function openExternal(url: string) { @@ -22,205 +14,26 @@ export function openExternal(url: string) { } } -/** What the setup's test of a key or of Ollama answered. */ -interface SetupOutcome { - ok: boolean; - message: string | null; - /** The model the wizards now write with; null where none runs without credits. */ - text: string | null; -} - /** The providers that can write: a key from one of them is enough for the setup. */ const WRITERS = PROVIDERS.filter((p) => p.text); -/** - * The keys of the setup, each tested on its own: a key that works is stored and put to use, and - * the first one ends the setup. Which model does which job is for Settings → Models. - */ +/** The keys of the setup and Ollama. Which model does which job is for Settings → Models. */ export function OwnModels({ models }: { models: LocalModels }) { return ( -
-
- -

{t("local.keysHint")}

-
-
- {WRITERS.map((p) => ( - - ))} - -
-

{t("local.modelsLater")}

-
- ); -} - -function useSetupTest(path: string) { - const qc = useQueryClient(); - return useMutation({ - mutationFn: (body: Record) => api.post(path, body), - // A working key ends the setup: the studio learns it from `me`. - onSuccess: () => qc.invalidateQueries({ queryKey: ["me"] }), - }); -} - -function KeyRow({ provider, stored }: { provider: ProviderInfo; stored: boolean }) { - const qc = useQueryClient(); - const [value, setValue] = useState(""); - const test = useSetupTest(`/api/studio/local/keys/${provider.id}`); - // A stored key is tested again with an empty field; a working new one leaves the field. - const run = () => - test.mutate(value.trim() ? { key: value.trim() } : {}, { - onSuccess: (r) => (r.ok ? setValue("") : undefined), - }); - const remove = useMutation({ - mutationFn: () => api.put("/api/studio/local/models", { keys: { [provider.id]: "" } }), - onSuccess: async () => { - test.reset(); - await qc.invalidateQueries({ queryKey: ["me"] }); - }, - }); - return ( - openExternal(provider.keyUrl)} - className="inline-flex items-center gap-1 text-left hover:text-ink-2 hover:underline" - > - {t("local.keyGet")} - - } - input={ - setValue(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter" && value.trim()) { - run(); - } - }} - /> - } - actions={ - <> - - {stored ? ( - - ) : null} - - } - said={said(test, (ref) => providerOfRef(ref) === provider.id)} - /> - ); -} - -function OllamaRow({ url: saved }: { url: string }) { - const [url, setUrl] = useState(saved); - const test = useSetupTest("/api/studio/local/ollama"); - return ( - setUrl(e.target.value)} - /> - } - actions={ - - } - said={said(test, (ref) => ref.startsWith("ollama:"))} - /> - ); -} - -/** The line under a row once its test answered; `mine`: the model is this row's. */ -function said( - test: ReturnType, - mine: (ref: string) => boolean, -): { ok: boolean; text: string } | null { - if (test.isError) { - return { ok: false, text: (test.error as Error).message }; - } - const r = test.data; - if (!r) { - return null; - } - if (!r.ok) { - return { ok: false, text: r.message ?? t("models.keyBad") }; - } - if (!r.text) { - return { ok: true, text: t("local.keyWorksPlain") }; - } - const model = modelLabel(r.text); - return { ok: true, text: t(mine(r.text) ? "local.keyWorks" : "local.keyWorksOther", { model }) }; -} - -function Row({ - label, - sub, - input, - actions, - said, -}: { - label: string; - sub: ReactNode; - input: ReactNode; - actions: ReactNode; - said: { ok: boolean; text: string } | null; -}) { - return ( -
-
-
{label}
-
{sub}
-
-
-
- {input} - {actions} -
- {said ? ( -

- {said.ok ? : null} - {said.text} -

- ) : null} -
-
+ ({ + id, + name, + keyUrl, + keyPlaceholder, + stored: Boolean(models.keys[id]), + }))} + isOf={(ref, provider) => providerOfRef(ref) === provider} + modelName={modelLabel} + onRemove={(provider) => api.put("/api/studio/local/models", { keys: { [provider]: "" } })} + later={t("local.modelsLater")} + > + + ); } diff --git a/apps/web/src/studio/SetupPage.tsx b/apps/web/src/studio/SetupPage.tsx index 29bcf96ef..1310436ca 100644 --- a/apps/web/src/studio/SetupPage.tsx +++ b/apps/web/src/studio/SetupPage.tsx @@ -1,6 +1,20 @@ +import { + Choice, + ClientPanel, + ModelTest, + SETUP_GROUND, + SETUP_GROUND_INK, + SETUP_ON_GROUND, + SETUP_ON_PAPER, + type SetupChoice, + SetupColumns, + SetupReady, + useClientChoices, + useClientStage, +} from "@engenty/model-setup/react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { ArrowLeft, ArrowRight, Check, Cloud, RefreshCw } from "lucide-react"; -import { type CSSProperties, useEffect, useState } from "react"; +import { ArrowRight, Check, Cloud } from "lucide-react"; +import { useEffect, useState } from "react"; import { useNavigate } from "react-router"; import { Mascot } from "../brand"; import { EngentyLogoMark } from "../engenty/logo"; @@ -9,8 +23,8 @@ import { useConfig, useFeature } from "../lib/features"; import { lang, t } from "../lib/i18n"; import { type AppleStatus, - type HarnessStatus, type LocalModels, + type Me, useCurrentSpace, useMe, withoutApple, @@ -18,7 +32,7 @@ import { import { useGround, usePreferredTheme } from "../lib/theme"; import { Button, cn } from "../ui"; import { LinkStatus, useAccountLink } from "./Account"; -import { HarnessPanel, ModelTest } from "./Harness"; +import { StudioSetup } from "./Harness"; import { LangSwitch } from "./LangSwitch"; import { OwnModels, openExternal } from "./LocalRuntime"; import { ThemeSwitch } from "./ThemeSwitch"; @@ -27,58 +41,8 @@ type Source = LocalModels["source"]; /** What the setup offers: a source, or Apple Intelligence — the short classes bound on this Mac. */ type Pick = Source | "apple"; -/** The ground the setup stands on and the text on white, as on the landing page. */ -const GROUND = "oklch(50% 0.2 262)"; -const GROUND_INK = "oklch(32% 0.15 262)"; -const CREAM = "oklch(90% 0.1 80)"; - -/** A step of the setup by its state: reached, the one to do now, still ahead. */ +/** The colour of a step reached. */ const STEP_DONE = "var(--step-done)"; -const STEP_NOW = "var(--step-now)"; -const STEP_LATER = "color-mix(in oklab, var(--on) 38%, transparent)"; - -/** - * The page's own colours. Dark: on the vivid ground, white on it, and secondary text, checks and - * errors a step brighter than the dark theme's. Light: on the theme's paper, the ground's blue - * marks the pick. - */ -const ON_GROUND = { - "--on": "white", - "--tile": "rgb(255 255 255 / 0.1)", - "--tile-hover": "rgb(255 255 255 / 0.15)", - "--tile-ring": "rgb(255 255 255 / 0.15)", - "--panel": "rgb(255 255 255 / 0.07)", - "--panel-ring": "rgb(255 255 255 / 0.12)", - "--pick": "white", - "--pick-ink": GROUND_INK, - "--pick-mark": GROUND_INK, - "--dot": CREAM, - "--step-done": "oklch(88% 0.17 150)", - "--step-now": "oklch(88% 0.14 80)", - "--ready-ink": "oklch(27% 0.09 150)", - "--ink-2": "oklch(96% 0.02 262)", - "--ink-3": "oklch(90% 0.035 262)", - "--ink-4": "oklch(82% 0.05 262)", - "--moss": "oklch(90% 0.14 150)", - "--rose": "oklch(89% 0.09 45)", -} as CSSProperties; -const ON_PAPER = { - "--on": "var(--ink)", - "--tile": "var(--card)", - "--tile-hover": "var(--paper-2)", - "--tile-ring": "var(--border-soft)", - "--panel": "var(--card)", - "--panel-ring": "var(--border-soft)", - "--pick": GROUND, - "--pick-ink": "white", - "--pick-mark": "white", - "--dot": GROUND, - "--step-done": "oklch(52% 0.15 150)", - "--step-now": "oklch(60% 0.15 65)", - "--ready-ink": "white", -} as CSSProperties; - -const EASE = "ease-[cubic-bezier(0.3,0.7,0.2,1)]"; /** The host of the start, beside the choices; on a narrow page it is scaled down. */ const HOST = 220; @@ -109,24 +73,6 @@ function appleNote(apple: AppleStatus): string { } } -/** - * A line of the list's heading: as wide as its text and shifted, not laid out, to the middle — - * so it keeps the column's full width and can travel to the left edge. - */ -const LINE = - "relative w-fit max-w-full transition-[left,translate] duration-700 ease-[cubic-bezier(0.3,0.7,0.2,1)] motion-reduce:transition-none"; -const LINE_MIDDLE = "left-1/2 -translate-x-1/2 text-center"; -/** Beside an opened choice the lines stand at the left edge; on a narrow page the list is alone again and they stay in the middle. */ -const LINE_LEFT = - "max-lg:left-1/2 max-lg:-translate-x-1/2 max-lg:text-center lg:left-0 lg:translate-x-0 lg:text-left"; - -/** On a narrow page the choices and the opened choice take turns; each starts at the top. */ -function toTop() { - if (window.matchMedia("(max-width: 1023px)").matches) { - window.scrollTo({ top: 0 }); - } -} - /** "Own keys" has no trace on the server until a key is saved; the tab remembers the pick. */ const OWN_PICKED = "wizards.setup.own"; @@ -163,132 +109,6 @@ function Wordmark() { ); } -function Choice({ - selected, - title, - description, - badge, - note, - onPick, -}: { - selected: boolean; - title: string; - description: string; - /** Set on the row's edge: the choice the setup recommends. */ - badge?: string; - /** How the choice stands right now, at the row's end. */ - note?: string; - onPick: () => void; -}) { - return ( - - ); -} - -/** - * Where the setup stands: what is chosen, its steps by name, then one dash per step. A step - * reached is green and checked, the one to do now amber, the ones ahead dim. The dashes fill - * like a strength meter: as many as the step the setup is on, amber on the way, all green once - * it works. - */ -function Stages({ name, at, done }: { name: string; at: number; done: boolean }) { - const stages = [t("setup.stage.connect"), t("setup.stage.test"), t("setup.stage.done")]; - const level = done ? stages.length : at + 1; - return ( -
- {name} -
    - {stages.map((stage, i) => { - const reached = done || i < at; - return ( -
  1. - {reached ? : null} - {stage} -
  2. - ); - })} -
-
- ); -} - function FooterLink({ href, children }: { href: string; children: string }) { return ( + + + ) : null; +} + +function Setup({ me, models }: { me: Me; models: LocalModels }) { const siteOn = useFeature("site"); // Dark stands on the vivid ground, light on the theme's paper. const onGround = usePreferredTheme() !== "light"; - useGround(onGround ? GROUND : null); - const me = useMe(); + useGround(onGround ? SETUP_GROUND : null); const qc = useQueryClient(); const navigate = useNavigate(); const config = useConfig(); const accountOn = useFeature("account"); const { space } = useCurrentSpace(); // The account: signed in during the install, or here; its credits are a way to think too. - const linking = useAccountLink(Boolean(me.data?.account?.signedIn)); + const signedIn = Boolean(me.account?.signedIn); + const linking = useAccountLink(signedIn); const [picked, setPicked] = useState(ownPicked); - // A narrow page shows the opened choice alone; the person goes back to the choices from there. - const [listOpen, setListOpen] = useState(false); // Without an account, the way to the studio asks once whether to sign in first. const [asking, setAsking] = useState(false); const choose = useMutation({ @@ -426,77 +252,44 @@ export function SetupPage() { ? { bindings: { classifier: "apple:default", low: "apple:default" } } : pick === "own" ? { source: "own", bindings: { classifier: "", low: "" } } - : { source: pick, bindings: withoutApple(me.data?.models?.bindings ?? {}) }, + : { source: pick, bindings: withoutApple(models.bindings) }, ), onSuccess: async (_saved, source) => { // First what the server now says, then the move: the choice opens on its own state, // never for a moment on the source it replaced. await qc.invalidateQueries({ queryKey: ["me"] }); setPicked(true); - setListOpen(false); - toTop(); rememberOwn(source === "own"); }, }); const rescan = useMutation({ mutationFn: () => - Promise.all( - (me.data?.harnesses ?? []).map((h) => api.post(`/api/studio/local/harness/${h.id}/detect`)), - ), + Promise.all(me.harnesses.map((h) => api.post(`/api/studio/local/harness/${h.id}/detect`))), onSuccess: () => qc.invalidateQueries({ queryKey: ["me"] }), }); - if (!me.data?.models) { - return null; - } - const models = me.data.models; - // Installed clients first, and among each, the one whose app is on this computer: its - // subscription is most likely already paid for. A missing one installs right here. - const rank = (h: HarnessStatus) => (h.version === null ? 2 : 0) + (h.app ? 0 : 1); - const clients = [...me.data.harnesses].sort((a, b) => rank(a) - rank(b)); - const installed = clients.filter((h) => h.version !== null); + const clients = useClientChoices(me.harnesses); + const installed = me.harnesses.some((h) => h.version !== null); // A first start has nothing chosen yet; a source picked earlier (here or in the settings) stays picked. - const apple = me.data.apple; + const apple = me.apple; const appleChosen = models.bindings.low?.startsWith("apple:"); const selected: Pick | null = appleChosen ? "apple" - : picked || me.data.setupDone || models.source !== "own" + : picked || me.setupDone || models.source !== "own" ? models.source : null; - const client = me.data.harnesses.find((h) => h.id === selected); + const client = me.harnesses.find((h) => h.id === selected); // Beside Apple the source stays: Standard and High think on the client or the credits picked before. const keeps = models.source === "account" ? t("models.creditsName") - : (me.data.harnesses.find((h) => h.id === models.source)?.name ?? null); - const works = me.data.setupDone; + : (me.harnesses.find((h) => h.id === models.source)?.name ?? null); + const works = me.setupDone; const hasKey = Object.values(models.keys).some(Boolean); // Connect, test, done: where the chosen source stands. Apple has nothing to connect. - const stage = works - ? 2 - : client - ? client.auth === "none" - ? 0 - : 1 - : selected === "apple" || selected === "account" || hasKey - ? 1 - : 0; - const heading = works - ? t("setup.h.done") - : client - ? client.version === null - ? t("setup.h.install", { name: client.name }) - : client.auth === "none" - ? t("setup.h.signIn", { name: client.name }) - : t("setup.h.test") - : selected === "apple" || selected === "account" || hasKey - ? t("setup.h.test") - : t("setup.h.keys"); + const standing = useClientStage(client, works); + const { stage, heading } = + selected === "own" && !works && !hasKey ? { stage: 0, heading: t("setup.h.keys") } : standing; const site = siteOn ? config.data?.site : null; - /** On a narrow page: the opened choice is all there is to see. */ - const panelOnly = selected !== null && !listOpen; - /** The row that is lit: the one just clicked, at once; else the one in effect. */ - const marked = choose.isPending ? (choose.variables ?? selected) : selected; - const signedIn = Boolean(me.data.account?.signedIn); const sourceName = client?.name ?? (selected === "apple" @@ -505,258 +298,139 @@ export function SetupPage() { ? t("setup.creditsChoice") : t("local.sourceOwn")); const toStudio = () => navigate("/", { replace: true }); + const credits = me.account?.credits ?? null; + const choices: SetupChoice[] = [ + ...clients, + ...(apple?.supported + ? [ + { + id: "apple", + title: t("models.optApple"), + description: t("setup.appleDesc"), + note: appleNote(apple), + }, + ] + : []), + { id: "own", title: t("local.sourceOwn"), description: t("setup.ownDesc") }, + ]; + /** The row that is lit: the one just clicked, at once; else the one in effect. */ + const marked = choose.isPending ? (choose.variables ?? selected) : selected; + const account = (pick: (id: string) => void) => ( + <> + {accountOn ? ( +
+ + {me.account?.signedIn ? ( + (me.account.name || me.account.email).slice(0, 1).toUpperCase() + ) : ( + + )} + +
+ {me.account?.signedIn ? ( + <> +

+ {t("setup.accountLinked", { name: me.account.name || me.account.email })} +

+

+ {[ + me.account.organization, + credits === null + ? null + : t("setup.accountCredits", { credits: credits.toLocaleString(lang) }), + ] + .filter(Boolean) + .join(" · ")} +

+ + ) : ( + <> +

{t("setup.account")}

+

+ {t("setup.accountText")} +

+ + + )} +
+ {signedIn ? null : ( + + )} +
+ ) : null} + {signedIn ? ( +
+ pick("account")} + /> +
+ ) : null} + + ); return (
- +
{/* While it asks about the account, the choices step out; the start's host is already gone. */} {asking ? : null} - {/* The host of the start takes no row of its own on a wide page: it stands large beside - the choices. On a narrow page there is no room beside anything, so it stands small - above them. A choice brings a host of its own, and this one steps out. */} - -
{/* One quiet line at the foot: whose app this is and where it runs. Its other end holds a place, marked with the wordmark's dot at its own size, for what belongs there later. */}