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