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