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

SourceControlWritingSettings.tsx

361 lines14.0 KB

1import { useNavigate } from "@tanstack/react-router";
2import { useRef, useState } from "react";
3import type {
4 ProviderInstanceId,
5 ServerSettings,
6 SourceControlWritingStyleMode,
7} from "@t3tools/contracts";
8import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
9import { createModelSelection } from "@t3tools/shared/model";
10import { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
11​
12import {
13 useScopedSettings,
14 useScopedSettingsMixed,
15 useUpdateScopedSettings,
16} from "./useScopedSettings";
17import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
18import { useSettingsScope } from "./SettingsScopeContext";
19import {
20 applyProviderInstanceSettings,
21 deriveProviderInstanceEntries,
22 sortProviderInstanceEntries,
23} from "../../providerInstances";
24import {
25 getCustomModelOptionsByInstance,
26 resolveAppModelSelectionState,
27} from "../../modelSelection";
28import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
29import { ProviderModelPicker } from "../chat/ProviderModelPicker";
30import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
31import { Switch } from "../ui/switch";
32import { Textarea } from "../ui/textarea";
33import { toastManager } from "../ui/toast";
34import { Button } from "../ui/button";
35import {
36 SETTINGS_PICKER_TRIGGER_CLASSNAME,
37 SettingResetButton,
38 SettingsRow,
39 SettingsSection,
40} from "./settingsLayout";
41import { BranchNamingSettings } from "./BranchNamingSettings";
42import { searchableSetting } from "./settingsSearch";
43​
44const MODE_OPTIONS: Record<SourceControlWritingStyleMode, { label: string; description: string }> =
45 {
46 repo_conventions: {
47 label: "Repository conventions",
48 description: "In each project, matches recent change descriptions and change request titles.",
49 },
50 conventional_commits: {
51 label: "Conventional Commits",
52 description: "Use Conventional Commit prefixes and keep change request text concise.",
53 },
54 custom: {
55 label: "Custom instructions",
56 description:
57 "Use your instructions for change descriptions and change requests in every project.",
58 },
59 };
60​
61export function SourceControlWritingSettingsSection() {
62 const settings = useScopedSettings();
63 const updateSettings = useUpdateScopedSettings();
64 const navigate = useNavigate();
65 const { environment, connectedEnvironments, targets } = useSettingsScope();
66 // The representative supplies the provider list; a model choice is checked
67 // against every target before it fans out.
68 const environmentId = environment?.environmentId ?? null;
69 const hasServerTargets = connectedEnvironments.length > 0;
70 const serverProviders = environment?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
71 // The writing style is one object; each control only cares about its own field.
72 const styleFieldMixed = (field: keyof ServerSettings["sourceControlWritingStyle"]) => {
73 const first = targets[0];
74 return (
75 first !== undefined &&
76 targets.some(
77 (candidate) =>
78 candidate.settings.sourceControlWritingStyle[field] !==
79 first.settings.sourceControlWritingStyle[field],
80 )
81 );
82 };
83 const modeMixed = styleFieldMixed("mode");
84 const instructionsMixed = styleFieldMixed("customInstructions");
85 const templatesMixed = styleFieldMixed("followChangeRequestTemplates");
86 const writingStyleMixed = modeMixed || instructionsMixed;
87 const mixedWriterModel = useScopedSettingsMixed(["sourceControlWriterModelSelection"]);
88 const customInstructionsRef = useRef<HTMLTextAreaElement>(null);
89 const [editingAllInstructions, setEditingAllInstructions] = useState(false);
90 const [allInstructions, setAllInstructions] = useState<string | null>(null);
91 const style = settings.sourceControlWritingStyle;
92 const defaults = DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
93 const isSourceControlWritingStyleDirty =
94 writingStyleMixed ||
95 style.mode !== defaults.mode ||
96 style.customInstructions !== defaults.customInstructions;
97​
98 const textGenerationProviders = serverProviders.filter(
99 (provider) => provider.supportsTextGeneration !== false,
100 );
101 const defaultModelSelection = resolveAppModelSelectionState(settings, textGenerationProviders);
102 const usesDedicatedModel = settings.sourceControlWriterModelSelection !== null;
103 const activeSelection = resolveAppModelSelectionState(
104 {
105 ...settings,
106 textGenerationModelSelection: resolveSourceControlWriterModelSelection(
107 settings,
108 textGenerationProviders,
109 ),
110 },
111 textGenerationProviders,
112 );
113 const instanceEntries = sortProviderInstanceEntries(
114 applyProviderInstanceSettings(deriveProviderInstanceEntries(textGenerationProviders), settings),
115 );
116 const canEnableDedicatedModel = instanceEntries.some(
117 (entry) =>
118 entry.instanceId === defaultModelSelection.instanceId && entry.enabled && entry.isAvailable,
119 );
120 const modelOptionsByInstance = getCustomModelOptionsByInstance(
121 settings,
122 textGenerationProviders,
123 activeSelection.instanceId,
124 activeSelection.model,
125 );
126 const writerModelDisabledReason = useScopedModelDisabledReason(settings, instanceEntries);
127​
128 return (
129 <SettingsSection id="source-control-text-generation" title="Text generation">
130 <BranchNamingSettings />
131 <SettingsRow
132 serverScoped
133 settingKeys={["sourceControlWritingStyle"]}
134 mixed={writingStyleMixed}
135 {...searchableSetting("source-control-writing-style")}
136 description={MODE_OPTIONS[style.mode].description}
137 resetAction={
138 isSourceControlWritingStyleDirty ? (
139 <SettingResetButton
140 label="source control writing style"
141 onClick={() =>
142 updateSettings({
143 sourceControlWritingStyle: {
144 mode: defaults.mode,
145 customInstructions: defaults.customInstructions,
146 },
147 })
148 }
149 />
150 ) : null
151 }
152 control={
153 <Select
154 value={modeMixed ? null : style.mode}
155 onValueChange={(value) => {
156 const customInstructions = customInstructionsRef.current?.value.trim();
157 updateSettings({
158 sourceControlWritingStyle: {
159 mode: value as SourceControlWritingStyleMode,
160 ...(customInstructions !== undefined ? { customInstructions } : {}),
161 },
162 });
163 }}
164 >
165 <SelectTrigger
166 size="sm"
167 className="w-full sm:w-56"
168 aria-label="Source control writing style"
169 >
170 <SelectValue>
171 {(value: SourceControlWritingStyleMode | null) =>
172 value === null ? "Mixed" : MODE_OPTIONS[value].label
173 }
174 </SelectValue>
175 </SelectTrigger>
176 <SelectPopup align="end" alignItemWithTrigger={false}>
177 {(Object.keys(MODE_OPTIONS) as SourceControlWritingStyleMode[]).map((mode) => (
178 <SelectItem key={mode} hideIndicator value={mode}>
179 {MODE_OPTIONS[mode].label}
180 </SelectItem>
181 ))}
182 </SelectPopup>
183 </Select>
184 }
185 >
186 {writingStyleMixed ? (
187 <div className="mt-3 max-w-2xl space-y-2 pb-3.5">
188 {editingAllInstructions ? (
189 <>
190 <Textarea
191 value={allInstructions ?? ""}
192 onChange={(event) => setAllInstructions(event.target.value)}
193 rows={4}
194 aria-label="Custom source control instructions for all selected environments"
195 placeholder="Write the instructions each selected environment should use."
196 />
197 <Button
198 size="sm"
199 variant="outline"
200 disabled={allInstructions === null}
201 onClick={() => {
202 if (allInstructions === null) return;
203 updateSettings({
204 sourceControlWritingStyle: {
205 mode: "custom",
206 customInstructions: allInstructions.trim(),
207 },
208 });
209 setEditingAllInstructions(false);
210 }}
211 >
212 Apply instructions to all
213 </Button>
214 </>
215 ) : (
216 <Button
217 size="sm"
218 variant="outline"
219 onClick={() => {
220 setAllInstructions(null);
221 setEditingAllInstructions(true);
222 }}
223 >
224 Write custom instructions for all
225 </Button>
226 )}
227 </div>
228 ) : style.mode === "custom" ? (
229 <div className="mt-3 max-w-2xl pb-3.5">
230 <Textarea
231 key={style.customInstructions}
232 ref={customInstructionsRef}
233 defaultValue={style.customInstructions}
234 onBlur={(event) => {
235 const customInstructions = event.target.value.trim();
236 if (customInstructions !== style.customInstructions) {
237 updateSettings({ sourceControlWritingStyle: { customInstructions } });
238 }
239 }}
240 rows={4}
241 placeholder="Keep titles concise. Use short bullet points in descriptions."
242 aria-label="Custom source control writing instructions"
243 />
244 </div>
245 ) : null}
246 </SettingsRow>
247​
248 <SettingsRow
249 serverScoped
250 settingKeys={["sourceControlWritingStyle"]}
251 mixed={templatesMixed}
252 {...searchableSetting("follow-change-request-templates")}
253 description="Use the repository's template for change request descriptions when available."
254 resetAction={
255 templatesMixed ||
256 style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
257 <SettingResetButton
258 label="change request templates"
259 onClick={() =>
260 updateSettings({
261 sourceControlWritingStyle: {
262 followChangeRequestTemplates: defaults.followChangeRequestTemplates,
263 },
264 })
265 }
266 />
267 ) : null
268 }
269 control={
270 <Switch
271 mixed={templatesMixed}
272 checked={templatesMixed ? false : style.followChangeRequestTemplates}
273 onCheckedChange={(checked) =>
274 updateSettings({
275 sourceControlWritingStyle: {
276 followChangeRequestTemplates: Boolean(checked),
277 },
278 })
279 }
280 aria-label="Follow change request templates"
281 />
282 }
283 />
284​
285 <SettingsRow
286 serverScoped
287 settingKeys={["sourceControlWriterModelSelection"]}
288 {...searchableSetting("source-control-writer-model")}
289 description="Model for source control text and branch or bookmark names. Off uses the environment's text generation model."
290 control={
291 !hasServerTargets ? (
292 <span className="text-sm text-muted-foreground">
293 Connect an environment to choose its source control writer model.
294 </span>
295 ) : (
296 <div className="flex flex-wrap items-center justify-end gap-2">
297 {usesDedicatedModel && !canEnableDedicatedModel ? (
298 <span className="text-sm text-muted-foreground">
299 No text generation providers available.
300 </span>
301 ) : null}
302 {usesDedicatedModel && canEnableDedicatedModel ? (
303 <ProviderModelPicker
304 activeInstanceId={activeSelection.instanceId}
305 model={activeSelection.model}
306 lockedProvider={null}
307 instanceEntries={instanceEntries}
308 modelOptionsByInstance={modelOptionsByInstance}
309 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
310 triggerAriaLabel="Source control writer model"
311 {...(mixedWriterModel ? { triggerLabel: "Mixed" } : {})}
312 {...(environmentId
313 ? {
314 onOpenProviderSetup: (instanceId: ProviderInstanceId) => {
315 void navigate({
316 to: "/settings/providers",
317 search: { environmentId, instanceId },
318 });
319 },
320 }
321 : {})}
322 getModelDisabledReason={writerModelDisabledReason}
323 onInstanceModelChange={(instanceId, model) => {
324 const reason = writerModelDisabledReason(instanceId, model);
325 if (reason) {
326 toastManager.add({
327 type: "error",
328 title: "Source control writer model not saved",
329 description: reason,
330 });
331 return;
332 }
333 updateSettings({
334 sourceControlWriterModelSelection: createModelSelection(instanceId, model),
335 });
336 }}
337 />
338 ) : null}
339 <Switch
340 checked={usesDedicatedModel}
341 disabled={!usesDedicatedModel && !canEnableDedicatedModel}
342 onCheckedChange={(checked) =>
343 updateSettings({
344 sourceControlWriterModelSelection: checked
345 ? createModelSelection(
346 defaultModelSelection.instanceId,
347 defaultModelSelection.model,
348 defaultModelSelection.options,
349 )
350 : null,
351 })
352 }
353 aria-label="Use a separate source control writer model"
354 />
355 </div>
356 )
357 }
358 />
359 </SettingsSection>
360 );