Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TextGeneratorsSettings.tsx

816 lines29.5 KB

1import {
2 type EnvironmentId,
3 isSecretReference,
4 type ProviderInstanceId,
5 type SecretReference,
6 type ServerProvider,
7 TextGeneratorConfig,
8 type TextGeneratorModel,
9} from "@t3tools/contracts";
10import { pickModelSelection } from "@t3tools/shared/model";
11import { AsyncResult } from "effect/reactivity";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14import { CheckIcon, MoreVertical, PlusIcon, ServerIcon } from "lucide-react";
15import { useId, useState } from "react";
16import { msg, T, useGT, useMessages, Var } from "gt-react";
17​
18import { useEnvironmentSettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
19import {
20 checkTextGeneratorConfig,
21 rereadTextGeneratorModels,
22 nextTextGeneratorId,
23 refreshTextGeneratorModels,
24 testTextGeneratorModel,
25 useTextGenerationTargets,
26 useTextGeneratorModels,
27 TEXT_GENERATOR_PRESETS,
28 type TextGeneratorPreset,
29 textGeneratorBrand,
30 textGeneratorDisplayName,
31} from "../../textGenerators";
32import { getTextGenerationModelOptionsByInstance } from "../../modelSelection";
33import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
34import { ProviderModelPicker } from "../chat/ProviderModelPicker";
35import {
36 AlertDialog,
37 AlertDialogClose,
38 AlertDialogDescription,
39 AlertDialogFooter,
40 AlertDialogHeader,
41 AlertDialogPopup,
42 AlertDialogTitle,
43} from "../ui/alert-dialog";
44import { Button } from "../ui/button";
45import { RefreshIcon } from "../ui/refresh-icon";
46import { toastManager } from "../ui/toast";
47import {
48 Dialog,
49 DialogDescription,
50 DialogFooter,
51 DialogHeader,
52 DialogPanel,
53 DialogPopup,
54 DialogTitle,
55} from "../ui/dialog";
56import { Input } from "../ui/input";
57import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
58import { Label } from "../ui/label";
59import { Spinner } from "../ui/spinner";
60import { Switch } from "../ui/switch";
61import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
62import { SecretSourceInput, useSecretSources } from "./SecretSourceInput";
63import { useSearchableSetting } from "./settingsSearch";
64import { SETTINGS_PICKER_TRIGGER_CLASSNAME, SettingsRow, SettingsSection } from "./settingsLayout";
65​
66const decodeTextGenerator = Schema.decodeUnknownOption(TextGeneratorConfig);
67​
68type Saved = { readonly id: ProviderInstanceId; readonly config: TextGeneratorConfig };
69type Editing = Saved | "new";
70​
71/** Rows that list, add, edit, and remove one environment's text generators. */
72export function TextGeneratorsSettings({
73 environmentId,
74 environmentLabel,
75 providers,
76 readOnly,
77}: {
78 readonly environmentId: EnvironmentId;
79 readonly environmentLabel: string;
80 readonly providers: ReadonlyArray<ServerProvider>;
81 readonly readOnly: boolean;
82}) {
83 const setting = useSearchableSetting();
84 const gt = useGT();
85 const messages = useMessages();
86 const settings = useEnvironmentSettings(environmentId);
87 const updateSettings = useUpdateEnvironmentSettings(environmentId);
88 const [editing, setEditing] = useState<Editing | null>(null);
89 const [removing, setRemoving] = useState<ProviderInstanceId | null>(null);
90 const [viewing, setViewing] = useState<Saved | null>(null);
91 const generators = Object.entries(settings.textGenerators) as Array<
92 [ProviderInstanceId, TextGeneratorConfig]
93 >;
94 const removingConfig = removing === null ? undefined : settings.textGenerators[removing];
95​
96 return (
97 <>
98 <SettingsSection
99 {...setting("text-generators")}
100 headerAction={
101 !readOnly ? (
102 <Button size="xs" variant="outline" onClick={() => setEditing("new")}>
103 <PlusIcon className="size-3" aria-hidden />
104 <T>Add generator</T>
105 </Button>
106 ) : null
107 }
108 >
109 {generators.length === 0 ? (
110 <SettingsRow
111 title={gt("No text generators yet")}
112 description={gt(
113 "Add a model API to write thread titles, commit messages, and other short text without starting a coding agent.",
114 )}
115 />
116 ) : null}
117 {generators.map(([id, config]) => {
118 const name = textGeneratorDisplayName(config, messages);
119 return (
120 <SettingsRow
121 key={id}
122 title={
123 <span className="inline-flex items-center gap-2.5">
124 <ProviderInstanceIcon
125 driverKind={textGeneratorBrand(config)}
126 displayName={name}
127 badgeContent="none"
128 />
129 {name}
130 </span>
131 }
132 description={
133 // Indented past the icon so it lines up with the name.
134 <span className="block truncate ps-7.5">
135 {config.enabled ? "" : gt("Off · ")}
136 {config.baseUrl.replace(/^https?:\/\//, "")}
137 </span>
138 }
139 control={
140 readOnly ? null : (
141 <div className="flex items-center gap-2">
142 <Menu>
143 <MenuTrigger
144 render={
145 <Button
146 size="icon-sm"
147 variant="ghost-muted"
148 aria-label={gt("More actions for {name}", { name })}
149 />
150 }
151 >
152 <MoreVertical />
153 </MenuTrigger>
154 <MenuPopup align="end">
155 <MenuItem onClick={() => setEditing({ id, config })}>
156 <T>Edit</T>
157 </MenuItem>
158 <MenuItem
159 disabled={!config.enabled}
160 onClick={() => setViewing({ id, config })}
161 >
162 <T>Show models</T>
163 </MenuItem>
164 <MenuItem variant="destructive" onClick={() => setRemoving(id)}>
165 <T>Remove</T>
166 </MenuItem>
167 </MenuPopup>
168 </Menu>
169 <Switch
170 checked={config.enabled}
171 onCheckedChange={(enabled) =>
172 updateSettings({ textGenerators: { [id]: { ...config, enabled } } })
173 }
174 aria-label={gt("Enable {name}", { name })}
175 />
176 </div>
177 )
178 }
179 />
180 );
181 })}
182 </SettingsSection>
183 {editing !== null ? (
184 <TextGeneratorWizard
185 environmentId={environmentId}
186 editing={editing}
187 providers={providers}
188 onClose={() => setEditing(null)}
189 onSave={(id, config) =>
190 updateSettings(
191 { textGenerators: { [id]: config } },
192 { onSaved: () => rereadTextGeneratorModels(environmentId, id) },
193 )
194 }
195 newId={(preset) => nextTextGeneratorId(preset.id, settings, providers)}
196 />
197 ) : null}
198 {viewing !== null ? (
199 <TextGeneratorModelsDialog
200 environmentId={environmentId}
201 saved={viewing}
202 onClose={() => setViewing(null)}
203 />
204 ) : null}
205 <AlertDialog
206 open={removingConfig !== undefined}
207 onOpenChange={(open) => {
208 if (!open) setRemoving(null);
209 }}
210 >
211 <AlertDialogPopup>
212 <AlertDialogHeader>
213 <AlertDialogTitle>
214 <T>
215 Remove{" "}
216 <Var>
217 {removingConfig ? textGeneratorDisplayName(removingConfig, messages) : ""}
218 </Var>
219 ?
220 </T>
221 </AlertDialogTitle>
222 <AlertDialogDescription>
223 <T>
224 This deletes the API key stored on <Var>{environmentLabel}</Var>. Anything set to
225 use this generator falls back to the text generation model.
226 </T>
227 </AlertDialogDescription>
228 </AlertDialogHeader>
229 <AlertDialogFooter>
230 <AlertDialogClose render={<Button variant="outline" />}>
231 <T>Cancel</T>
232 </AlertDialogClose>
233 <Button
234 variant="destructive"
235 onClick={() => {
236 if (removing !== null) updateSettings({ textGenerators: { [removing]: null } });
237 setRemoving(null);
238 }}
239 >
240 <T>Remove</T>
241 </Button>
242 </AlertDialogFooter>
243 </AlertDialogPopup>
244 </AlertDialog>
245 </>
246 );
248​
249const STEPS = [msg("Connect", { $context: "wizard step" }), msg("Use it")] as const;
250​
251/** Text tasks a generator can write, in the order the settings pages show them. */
252const TASKS = [
253 { key: "textGenerationModelSelection", label: msg("Thread titles and other generated text") },
254 {
255 key: "sourceControlWriterModelSelection",
256 label: msg("Commit messages, pull requests, and branch names"),
257 },
258 { key: "speechPostProcessingModelSelection", label: msg("Voice transcript cleanup") },
259] as const;
260​
261/**
262 * Connect checks the settings by listing the service's models and saves the generator; Use it then
263 * shows each text task's model picker, so any of them can switch to it. The key goes once to the
264 * environment's secret storage; settings keep only a redaction marker.
265 */
266function TextGeneratorWizard({
267 environmentId,
268 editing,
269 providers,
270 onClose,
271 onSave,
272 newId,
273}: {
274 readonly environmentId: EnvironmentId;
275 readonly editing: Editing;
276 readonly providers: ReadonlyArray<ServerProvider>;
277 readonly onClose: () => void;
278 readonly onSave: (id: ProviderInstanceId, config: TextGeneratorConfig) => void;
279 readonly newId: (preset: TextGeneratorPreset) => ProviderInstanceId;
280}) {
281 const messages = useMessages();
282 const gt = useGT();
283 const formId = useId();
284 const existing = editing === "new" ? null : editing.config;
285 const [step, setStep] = useState(0);
286 const [preset, setPreset] = useState(TEXT_GENERATOR_PRESETS[0]!);
287 const [baseUrl, setBaseUrl] = useState(existing?.baseUrl ?? preset.baseUrl);
288 const [label, setLabel] = useState(existing?.label ?? "");
289 const secretSources = useSecretSources(environmentId);
290 const [keyDraft, setKeyDraft] = useState<string | SecretReference>(
291 isSecretReference(existing?.apiKey) ? existing.apiKey : "",
292 );
293 const [keyValid, setKeyValid] = useState(true);
294 const [checking, setChecking] = useState(false);
295 const [checkError, setCheckError] = useState<string | null>(null);
296 const [modelCount, setModelCount] = useState(0);
297 // Fixed once saved, so editing the form again after Back updates the same generator.
298 const [savedId, setSavedId] = useState<ProviderInstanceId | null>(
299 editing === "new" ? null : editing.id,
300 );
301​
302 // A saved literal key arrives redacted; sending the marker back keeps it.
303 const storedKey = typeof existing?.apiKey === "string" ? existing.apiKey : "";
304 const apiKey = typeof keyDraft === "string" ? keyDraft.trim() || storedKey : keyDraft;
305 const kind = existing?.kind ?? preset.kind;
306 const config = decodeTextGenerator({
307 kind,
308 ...(label.trim() ? { label: label.trim() } : {}),
309 baseUrl: baseUrl.trim(),
310 apiKey,
311 enabled: existing?.enabled ?? true,
312 });
313 const keyRequired = existing === null && preset.id !== "custom";
314 // Presets know their URL; only a custom endpoint, or one already saved as such, asks for it.
315 const showBaseUrl =
316 existing === null
317 ? preset.id === "custom"
318 : !["openai", "anthropic", "openrouter"].includes(textGeneratorBrand(existing));
319 const canConnect = keyValid && Option.isSome(config) && (!keyRequired || apiKey !== "");
320 const name = Option.isSome(config)
321 ? textGeneratorDisplayName(config.value, messages)
322 : messages(preset.label);
323​
324 const connect = async () => {
325 if (!canConnect || checking) return;
326 const id = savedId ?? newId(preset);
327 setChecking(true);
328 setCheckError(null);
329 // The form is disabled while this runs, so the checked config is the one saved below.
330 const result = await checkTextGeneratorConfig(environmentId, id, config.value);
331 setChecking(false);
332 if ("error" in result) {
333 setCheckError(result.error);
334 return;
335 }
336 onSave(id, config.value);
337 setSavedId(id);
338 setModelCount(result.models.length);
339 setStep(1);
340 };
341​
342 return (
343 <Dialog
344 open
345 onOpenChange={(open) => {
346 if (!open) onClose();
347 }}
348 >
349 <WizardPopup>
350 <WizardHeader
351 title={
352 existing
353 ? gt("Edit {name}", { name: textGeneratorDisplayName(existing, messages) })
354 : gt("Add a text generator")
355 }
356 description={gt(
357 "Writes thread titles, commit messages, and other short text without starting a coding agent. Your API key is stored on this environment.",
358 )}
359 >
360 <WizardSteps
361 steps={STEPS.map((step) => messages(step))}
362 currentStep={step}
363 isStepDisabled={(index) => index > step}
364 onStepChange={setStep}
365 />
366 </WizardHeader>
367 <WizardPanel>
368 {step === 0 ? (
369 <form
370 id={formId}
371 className="grid gap-4"
372 onSubmit={(event) => {
373 event.preventDefault();
374 void connect();
375 }}
376 >
377 <fieldset disabled={checking} className="contents">
378 {existing === null ? (
379 <div className="grid gap-1.5">
380 <span className="text-sm font-medium">
381 <T>Service</T>
382 </span>
383 <div
384 role="radiogroup"
385 aria-label={gt("Service")}
386 className="grid grid-cols-2 gap-2 sm:grid-cols-4"
387 >
388 {TEXT_GENERATOR_PRESETS.map((candidate) => {
389 const selected = candidate.id === preset.id;
390 return (
391 <button
392 key={candidate.id}
393 type="button"
394 role="radio"
395 aria-checked={selected}
396 className={
397 selected
398 ? "flex flex-col items-center gap-2 rounded-lg border border-primary bg-primary/5 px-2 py-3 text-sm font-medium text-foreground ring-1 ring-primary ring-inset outline-none focus-visible:ring-2 focus-visible:ring-inset"
399 : "flex flex-col items-center gap-2 rounded-lg border bg-background px-2 py-3 text-sm text-muted-foreground outline-none hover:bg-accent/50 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
400 }
401 onClick={() => {
402 setPreset(candidate);
403 setBaseUrl(candidate.baseUrl);
404 setCheckError(null);
405 }}
406 >
407 {candidate.id === "custom" ? (
408 <ServerIcon className="size-5" aria-hidden />
409 ) : (
410 <ProviderInstanceIcon
411 driverKind={textGeneratorBrand(candidate)}
412 displayName={candidate.label}
413 badgeContent="none"
414 />
415 )}
416 {candidate.id === "custom" ? gt("Custom") : candidate.label}
417 </button>
418 );
419 })}
420 </div>
421 </div>
422 ) : null}
423 {showBaseUrl ? (
424 <div className="grid gap-1.5">
425 <Label htmlFor="text-generator-url">
426 <T>Base URL</T>
427 </Label>
428 <Input
429 id="text-generator-url"
430 placeholder="http://localhost:11434/v1"
431 value={baseUrl}
432 onChange={(event) => {
433 setBaseUrl(event.target.value);
434 setCheckError(null);
435 }}
436 spellCheck={false}
437 autoFocus={existing === null && preset.id === "custom"}
438 />
439 </div>
440 ) : null}
441 <div className="grid gap-1.5">
442 <Label htmlFor="text-generator-key">
443 {keyRequired ? gt("API key") : gt("API key (optional)")}
444 </Label>
445 <SecretSourceInput
446 id="text-generator-key"
447 aria-label={gt("API key")}
448 value={keyDraft}
449 configured={storedKey !== ""}
450 sources={secretSources}
451 onChange={(event) => {
452 setKeyDraft(event.target.value);
453 setCheckError(null);
454 }}
455 onSecretChange={(secret) => setKeyDraft(secret ?? "")}
456 autoFocus={existing === null && preset.id !== "custom"}
457 onValidityChange={setKeyValid}
458 />
459 </div>
460 <div className="grid gap-1.5">
461 <Label htmlFor="text-generator-label">
462 <T>Name (optional)</T>
463 </Label>
464 <Input
465 id="text-generator-label"
466 placeholder={
467 existing !== null
468 ? textGeneratorDisplayName(existing, messages)
469 : preset.id === "custom"
470 ? gt("e.g. My local model")
471 : messages(preset.label)
472 }
473 value={label}
474 onChange={(event) => setLabel(event.target.value)}
475 />
476 </div>
477 {checkError ? (
478 <p role="alert" className="text-sm text-destructive">
479 {checkError}
480 </p>
481 ) : null}
482 </fieldset>
483 </form>
484 ) : (
485 <div className="grid gap-4">
486 <p className="text-sm text-muted-foreground">
487 {gt(
488 "{count, plural, one {{name} is connected and lists {count} model. Switch any of these to it, or keep what they use now.} other {{name} is connected and lists {count} models. Switch any of these to it, or keep what they use now.}}",
489 { name, count: modelCount },
490 )}
491 </p>
492 {/* One grid for all rows, so pickers and Test buttons line up in columns. */}
493 <div className="grid grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-x-2 gap-y-4">
494 {TASKS.map((task) => (
495 <TextGenerationTaskPicker
496 key={task.key}
497 environmentId={environmentId}
498 providers={providers}
499 settingKey={task.key}
500 label={messages(task.label)}
501 />
502 ))}
503 </div>
504 </div>
505 )}
506 </WizardPanel>
507 <WizardFooter
508 leading={
509 step > 0 ? (
510 <Button variant="ghost" onClick={() => setStep(0)}>
511 <T>Back</T>
512 </Button>
513 ) : null
514 }
515 >
516 {step === 0 ? (
517 <>
518 <Button variant="outline" onClick={onClose}>
519 <T>Cancel</T>
520 </Button>
521 <Button type="submit" form={formId} disabled={!canConnect || checking}>
522 {checking ? <Spinner /> : null}
523 {checking ? gt("Connecting") : existing ? gt("Save and continue") : gt("Connect")}
524 </Button>
525 </>
526 ) : (
527 // Connect's button unmounts here; without this, focus lands on the step list.
528 <Button autoFocus onClick={onClose}>
529 <T>Done</T>
530 </Button>
531 )}
532 </WizardFooter>
533 </WizardPopup>
534 </Dialog>
535 );
537​
538/** One text task's model, saved as it changes, with every text generation target to pick from. */
539function TextGenerationTaskPicker({
540 environmentId,
541 providers,
542 settingKey,
543 label,
544}: {
545 readonly environmentId: EnvironmentId;
546 readonly providers: ReadonlyArray<ServerProvider>;
547 readonly settingKey: (typeof TASKS)[number]["key"];
548 readonly label: string;
549}) {
550 const settings = useEnvironmentSettings(environmentId);
551 const updateSettings = useUpdateEnvironmentSettings(environmentId);
552 const own = settings[settingKey];
553 // Source control and voice follow the text generation model until they get their own.
554 const selection = own ?? settings.textGenerationModelSelection;
555 const targets = useTextGenerationTargets({
556 environmentId,
557 settings,
558 providers: providers.filter((provider) => provider.supportsTextGeneration !== false),
559 projectId: null,
560 selections: [selection],
561 });
562 // Only a text generator's model can be tried cheaply; agents start a whole session.
563 const testable = Object.hasOwn(settings.textGenerators, selection.instanceId);
564 const testKey = `${selection.instanceId}:${selection.model}`;
565 const [testing, setTesting] = useState(false);
566 const [result, setResult] = useState<{
567 readonly key: string;
568 readonly error: string | null;
569 } | null>(null);
570 const shown = result?.key === testKey ? result : null;
571 const test = async () => {
572 setTesting(true);
573 const error = await testTextGeneratorModel(
574 environmentId,
575 selection.instanceId,
576 selection.model,
577 );
578 setTesting(false);
579 setResult({ key: testKey, error });
580 };
581 return (
582 <>
583 <div className="grid min-w-0 gap-0.5 pe-2">
584 <span className="text-sm">{label}</span>
585 {shown?.error ? (
586 <span role="alert" className="text-xs text-destructive">
587 {shown.error}
588 </span>
589 ) : shown ? (
590 <span role="status" className="text-xs text-muted-foreground">
591 <T>
592 <Var>{selection.model}</Var> answered. It works.
593 </T>
594 </span>
595 ) : own === null ? (
596 <span className="text-xs text-muted-foreground">
597 <T>Follows the text generation model</T>
598 </span>
599 ) : null}
600 </div>
601 <div className="justify-self-end">
602 <ProviderModelPicker
603 environmentId={environmentId}
604 activeInstanceId={selection.instanceId}
605 model={selection.model}
606 lockedProvider={null}
607 instanceEntries={targets.entries}
608 modelOptionsByInstance={getTextGenerationModelOptionsByInstance(
609 settings,
610 targets.providers,
611 selection.instanceId,
612 selection.model,
613 )}
614 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
615 onInstanceModelChange={(instanceId, model) =>
616 updateSettings({ [settingKey]: pickModelSelection(selection, instanceId, model) })
617 }
618 />
619 </div>
620 <div className="justify-self-end">
621 {testable ? (
622 <Button
623 size="xs"
624 variant="outline"
625 aria-busy={testing}
626 disabled={testing}
627 onClick={() => void test()}
628 >
629 {/* Keeps the label's width while testing, so the row never reflows. */}
630 <span className="relative">
631 <span className={testing ? "invisible" : undefined}>
632 <T>Test</T>
633 </span>
634 {testing ? (
635 <span className="absolute inset-0 flex items-center justify-center">
636 <Spinner />
637 </span>
638 ) : null}
639 </span>
640 </Button>
641 ) : null}
642 </div>
643 </>
644 );
646​
647/** Searchable models; selectable when `onSelect` is given. */
648function TextGeneratorModelList({
649 models,
650 selected,
651 onSelect,
652}: {
653 readonly models: ReadonlyArray<TextGeneratorModel>;
654 readonly selected?: string | null;
655 readonly onSelect?: (id: string) => void;
656}) {
657 const gt = useGT();
658 const [query, setQuery] = useState("");
659 const needle = query.trim().toLowerCase();
660 const shown = needle
661 ? models.filter(
662 (model) =>
663 model.id.toLowerCase().includes(needle) || model.name.toLowerCase().includes(needle),
664 )
665 : models;
666 return (
667 <div className="grid gap-2">
668 {models.length > 8 ? (
669 // Native search inputs clear on Escape even during IME composition.
670 <Input
671 type="text"
672 role="searchbox"
673 enterKeyHint="search"
674 placeholder={gt("Search models")}
675 aria-label={gt("Search models")}
676 autoFocus
677 value={query}
678 onChange={(event) => setQuery(event.target.value)}
679 onKeyDown={(event) => {
680 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
681 if (event.key === "Escape" && (query || event.repeat)) {
682 event.preventDefault();
683 event.stopPropagation();
684 setQuery("");
685 }
686 }}
687 />
688 ) : null}
689 <div className="max-h-80 overflow-y-auto rounded-lg border divide-y divide-border/60">
690 {shown.length === 0 ? (
691 <p className="px-3 py-2 text-sm text-muted-foreground">
692 <T>No models match.</T>
693 </p>
694 ) : (
695 <ul role={onSelect ? "listbox" : "list"} aria-label={gt("Models")}>
696 {shown.map((model) => {
697 const isSelected = model.id === selected;
698 const label = (
699 <>
700 <span className="grid min-w-0 flex-1">
701 <span className="truncate">{model.name}</span>
702 {model.name !== model.id ? (
703 <span className="truncate font-mono text-xs text-muted-foreground">
704 {model.id}
705 </span>
706 ) : null}
707 </span>
708 {isSelected ? <CheckIcon className="size-4 shrink-0 text-primary" /> : null}
709 </>
710 );
711 return (
712 <li
713 key={model.id}
714 role={onSelect ? "option" : undefined}
715 aria-selected={onSelect ? isSelected : undefined}
716 >
717 {onSelect ? (
718 <button
719 type="button"
720 className="flex w-full items-center gap-2 px-3 py-2 text-left text-sm hover:bg-accent focus-visible:bg-accent focus-visible:outline-none"
721 onClick={() => onSelect(model.id)}
722 >
723 {label}
724 </button>
725 ) : (
726 <div className="flex items-center gap-2 px-3 py-2 text-sm">{label}</div>
727 )}
728 </li>
729 );
730 })}
731 </ul>
732 )}
733 </div>
734 </div>
735 );
737​
738/** A saved generator's models, with a refresh that asks the API again. */
739function TextGeneratorModelsDialog({
740 environmentId,
741 saved,
742 onClose,
743}: {
744 readonly environmentId: EnvironmentId;
745 readonly saved: Saved;
746 readonly onClose: () => void;
747}) {
748 const gt = useGT();
749 const messages = useMessages();
750 const name = textGeneratorDisplayName(saved.config, messages);
751 const result = useTextGeneratorModels(environmentId, saved.id, saved.config);
752 const [refreshing, setRefreshing] = useState(false);
753 const refresh = async () => {
754 setRefreshing(true);
755 const outcome = await refreshTextGeneratorModels(environmentId, saved.id);
756 setRefreshing(false);
757 if ("error" in outcome) {
758 toastManager.add({
759 type: "error",
760 title: gt("Couldn't load {name} models", { name }),
761 description: outcome.error,
762 });
763 }
764 };
765 const models = AsyncResult.isSuccess(result) ? result.value : null;
766 const error = Option.getOrUndefined(AsyncResult.error(result));
767 return (
768 <Dialog
769 open
770 onOpenChange={(open) => {
771 if (!open) onClose();
772 }}
773 >
774 <DialogPopup className="max-w-md">
775 <DialogHeader>
776 <DialogTitle>{gt("{name} models", { name })}</DialogTitle>
777 <DialogDescription>
778 {models === null
779 ? error
780 ? gt("The model list couldn't load.")
781 : gt("Loading the model list.")
782 : gt(
783 "{count, plural, one {{count} model available. Pick one in a text generation model picker.} other {{count} models available. Pick one in a text generation model picker.}}",
784 { count: models.length },
785 )}
786 </DialogDescription>
787 </DialogHeader>
788 <DialogPanel>
789 {error ? (
790 <p role="alert" className="text-sm text-destructive">
791 {error}
792 </p>
793 ) : models === null ? (
794 <Spinner tone="muted" />
795 ) : (
796 <TextGeneratorModelList models={models} />
797 )}
798 </DialogPanel>
799 <DialogFooter variant="bare">
800 <Button
801 variant="outline"
802 aria-busy={refreshing}
803 disabled={refreshing}
804 onClick={() => void refresh()}
805 >
806 <RefreshIcon refreshing={refreshing} />
807 <T>Refresh</T>
808 </Button>
809 <Button onClick={onClose}>
810 <T>Done</T>
811 </Button>
812 </DialogFooter>
813 </DialogPopup>
814 </Dialog>
815 );