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 {
11 resolveReviewGuideModelSelection,
12 resolveSourceControlWriterModelSelection,
13} from "@t3tools/shared/serverSettings";
14
15import {
16 useScopedSettings,
17 useScopedSettingsMixed,
18 useUpdateScopedSettings,
19} from "./useScopedSettings";
20import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
21import { useSettingsScope } from "./SettingsScopeContext";
22import {
23 applyProviderInstanceSettings,
24 deriveProviderInstanceEntries,
25 sortProviderInstanceEntries,
26} from "../../providerInstances";
27import {
28 getCustomModelOptionsByInstance,
29 resolveAppModelSelectionState,
30} from "../../modelSelection";
31import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
32import { ProviderModelPicker } from "../chat/ProviderModelPicker";
33import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
34import { Switch } from "../ui/switch";
35import { Textarea } from "../ui/textarea";
36import { toastManager } from "../ui/toast";
37import { Button } from "../ui/button";
38import {
39 SETTINGS_PICKER_TRIGGER_CLASSNAME,
40 SettingResetButton,
41 SettingsRow,
42 SettingsSection,
43} from "./settingsLayout";
44import { BranchNamingSettings } from "./BranchNamingSettings";
45import { searchableSetting } from "./settingsSearch";
46
47const MODE_OPTIONS: Record<SourceControlWritingStyleMode, { label: string; description: string }> =
48 {
49 repo_conventions: {
50 label: "Repository conventions",
51 description: "In each project, matches recent change descriptions and change request titles.",
52 },
53 conventional_commits: {
54 label: "Conventional Commits",
55 description: "Use Conventional Commit prefixes and keep change request text concise.",
56 },
57 custom: {
58 label: "Custom instructions",
59 description:
60 "Use your instructions for change descriptions and change requests in every project.",
61 },
62 };
63
64export function SourceControlWritingSettingsSection() {
65 const settings = useScopedSettings();
66 const updateSettings = useUpdateScopedSettings();
67 const mixedReviewGuidesEnabled = useScopedSettingsMixed(["reviewGuidesEnabled"]);
68 const navigate = useNavigate();
69 const { environment, connectedEnvironments, targets } = useSettingsScope();
70 // The representative supplies the provider list; a model choice is checked
71 // against every target before it fans out.
72 const environmentId = environment?.environmentId ?? null;
73 const hasServerTargets = connectedEnvironments.length > 0;
74 const serverProviders = environment?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
75 // The writing style is one object; each control only cares about its own field.
76 const styleFieldMixed = (field: keyof ServerSettings["sourceControlWritingStyle"]) => {
77 const first = targets[0];
78 return (
79 first !== undefined &&
80 targets.some(
81 (candidate) =>
82 candidate.settings.sourceControlWritingStyle[field] !==
83 first.settings.sourceControlWritingStyle[field],
84 )
85 );
86 };
87 const modeMixed = styleFieldMixed("mode");
88 const instructionsMixed = styleFieldMixed("customInstructions");
89 const templatesMixed = styleFieldMixed("followChangeRequestTemplates");
90 const writingStyleMixed = modeMixed || instructionsMixed;
91 const mixedWriterModel = useScopedSettingsMixed(["sourceControlWriterModelSelection"]);
92 const mixedReviewGuideModel = useScopedSettingsMixed(["reviewGuideModelSelection"]);
93 const mixedReviewGuideInstructions = useScopedSettingsMixed(["reviewGuideInstructions"]);
94 const reviewGuideInstructionsEdited = useRef(false);
95 const scopeKey = targets.map((target) => `${target.environmentId}:${target.projectId}`).join(",");
96 const customInstructionsRef = useRef<HTMLTextAreaElement>(null);
97 const [editingAllInstructions, setEditingAllInstructions] = useState(false);
98 const [allInstructions, setAllInstructions] = useState<string | null>(null);
99 const style = settings.sourceControlWritingStyle;
100 const defaults = DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
101 const isSourceControlWritingStyleDirty =
102 writingStyleMixed ||
103 style.mode !== defaults.mode ||
104 style.customInstructions !== defaults.customInstructions;
105
106 const textGenerationProviders = serverProviders.filter(
107 (provider) => provider.supportsTextGeneration !== false,
108 );
109 const defaultModelSelection = resolveAppModelSelectionState(settings, textGenerationProviders);
110 const usesDedicatedModel = settings.sourceControlWriterModelSelection !== null;
111 const activeSelection = resolveAppModelSelectionState(
112 {
113 ...settings,
114 textGenerationModelSelection: resolveSourceControlWriterModelSelection(
115 settings,
116 textGenerationProviders,
117 ),
118 },
119 textGenerationProviders,
120 );
121 const instanceEntries = sortProviderInstanceEntries(
122 applyProviderInstanceSettings(deriveProviderInstanceEntries(textGenerationProviders), settings),
123 );
124 const canEnableDedicatedModel = instanceEntries.some(
125 (entry) =>
126 entry.instanceId === defaultModelSelection.instanceId && entry.enabled && entry.isAvailable,
127 );
128 const modelOptionsByInstance = getCustomModelOptionsByInstance(
129 settings,
130 textGenerationProviders,
131 activeSelection.instanceId,
132 activeSelection.model,
133 );
134 const writerModelDisabledReason = useScopedModelDisabledReason(settings, instanceEntries);
135 const usesReviewGuideModel = settings.reviewGuideModelSelection !== null;
136 const reviewGuideSelection = resolveAppModelSelectionState(
137 {
138 ...settings,
139 textGenerationModelSelection: resolveReviewGuideModelSelection(
140 settings,
141 textGenerationProviders,
142 ),
143 },
144 textGenerationProviders,
145 );
146 // Its own list: a custom model chosen for guides is not among the writer model's options.
147 const reviewGuideModelOptionsByInstance = getCustomModelOptionsByInstance(
148 settings,
149 textGenerationProviders,
150 reviewGuideSelection.instanceId,
151 reviewGuideSelection.model,
152 );
153
154 return (
155 <SettingsSection id="source-control-text-generation" title="Text generation">
156 <BranchNamingSettings />
157 <SettingsRow
158 serverScoped
159 settingKeys={["sourceControlWritingStyle"]}
160 mixed={writingStyleMixed}
161 {...searchableSetting("source-control-writing-style")}
162 description={MODE_OPTIONS[style.mode].description}
163 resetAction={
164 isSourceControlWritingStyleDirty ? (
165 <SettingResetButton
166 label="source control writing style"
167 onClick={() =>
168 updateSettings({
169 sourceControlWritingStyle: {
170 mode: defaults.mode,
171 customInstructions: defaults.customInstructions,
172 },
173 })
174 }
175 />
176 ) : null
177 }
178 control={
179 <Select
180 value={modeMixed ? null : style.mode}
181 onValueChange={(value) => {
182 const customInstructions = customInstructionsRef.current?.value.trim();
183 updateSettings({
184 sourceControlWritingStyle: {
185 mode: value as SourceControlWritingStyleMode,
186 ...(customInstructions !== undefined ? { customInstructions } : {}),
187 },
188 });
189 }}
190 >
191 <SelectTrigger
192 size="sm"
193 className="w-full sm:w-56"
194 aria-label="Source control writing style"
195 >
196 <SelectValue>
197 {(value: SourceControlWritingStyleMode | null) =>
198 value === null ? "Mixed" : MODE_OPTIONS[value].label
199 }
200 </SelectValue>
201 </SelectTrigger>
202 <SelectPopup align="end" alignItemWithTrigger={false}>
203 {(Object.keys(MODE_OPTIONS) as SourceControlWritingStyleMode[]).map((mode) => (
204 <SelectItem key={mode} hideIndicator value={mode}>
205 {MODE_OPTIONS[mode].label}
206 </SelectItem>
207 ))}
208 </SelectPopup>
209 </Select>
210 }
211 >
212 {writingStyleMixed ? (
213 <div className="mt-3 max-w-2xl space-y-2 pb-3.5">
214 {editingAllInstructions ? (
215 <>
216 <Textarea
217 value={allInstructions ?? ""}
218 onChange={(event) => setAllInstructions(event.target.value)}
219 rows={4}
220 aria-label="Custom source control instructions for all selected environments"
221 placeholder="Write the instructions each selected environment should use."
222 />
223 <Button
224 size="sm"
225 variant="outline"
226 disabled={allInstructions === null}
227 onClick={() => {
228 if (allInstructions === null) return;
229 updateSettings({
230 sourceControlWritingStyle: {
231 mode: "custom",
232 customInstructions: allInstructions.trim(),
233 },
234 });
235 setEditingAllInstructions(false);
236 }}
237 >
238 Apply instructions to all
239 </Button>
240 </>
241 ) : (
242 <Button
243 size="sm"
244 variant="outline"
245 onClick={() => {
246 setAllInstructions(null);
247 setEditingAllInstructions(true);
248 }}
249 >
250 Write custom instructions for all
251 </Button>
252 )}
253 </div>
254 ) : style.mode === "custom" ? (
255 <div className="mt-3 max-w-2xl pb-3.5">
256 <Textarea
257 key={style.customInstructions}
258 ref={customInstructionsRef}
259 defaultValue={style.customInstructions}
260 onBlur={(event) => {
261 const customInstructions = event.target.value.trim();
262 if (customInstructions !== style.customInstructions) {
263 updateSettings({ sourceControlWritingStyle: { customInstructions } });
264 }
265 }}
266 rows={4}
267 placeholder="Keep titles concise. Use short bullet points in descriptions."
268 aria-label="Custom source control writing instructions"
269 />
270 </div>
271 ) : null}
272 </SettingsRow>
273
274 <SettingsRow
275 serverScoped
276 settingKeys={["sourceControlWritingStyle"]}
277 mixed={templatesMixed}
278 {...searchableSetting("follow-change-request-templates")}
279 description="Use the repository's template for change request descriptions when available."
280 resetAction={
281 templatesMixed ||
282 style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
283 <SettingResetButton
284 label="change request templates"
285 onClick={() =>
286 updateSettings({
287 sourceControlWritingStyle: {
288 followChangeRequestTemplates: defaults.followChangeRequestTemplates,
289 },
290 })
291 }
292 />
293 ) : null
294 }
295 control={
296 <Switch
297 mixed={templatesMixed}
298 checked={templatesMixed ? false : style.followChangeRequestTemplates}
299 onCheckedChange={(checked) =>
300 updateSettings({
301 sourceControlWritingStyle: {
302 followChangeRequestTemplates: Boolean(checked),
303 },
304 })
305 }
306 aria-label="Follow change request templates"
307 />
308 }
309 />
310
311 <SettingsRow
312 serverScoped
313 settingKeys={["sourceControlWriterModelSelection"]}
314 {...searchableSetting("source-control-writer-model")}
315 description="Model for source control text and branch or bookmark names. Off uses the environment's text generation model."
316 control={
317 !hasServerTargets ? (
318 <span className="text-sm text-muted-foreground">
319 Connect an environment to choose its source control writer model.
320 </span>
321 ) : (
322 <div className="flex flex-wrap items-center justify-end gap-2">
323 {usesDedicatedModel && !canEnableDedicatedModel ? (
324 <span className="text-sm text-muted-foreground">
325 No text generation providers available.
326 </span>
327 ) : null}
328 {usesDedicatedModel && canEnableDedicatedModel ? (
329 <ProviderModelPicker
330 environmentId={environmentId}
331 activeInstanceId={activeSelection.instanceId}
332 model={activeSelection.model}
333 lockedProvider={null}
334 instanceEntries={instanceEntries}
335 modelOptionsByInstance={modelOptionsByInstance}
336 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
337 triggerAriaLabel="Source control writer model"
338 {...(mixedWriterModel ? { triggerLabel: "Mixed" } : {})}
339 {...(environmentId
340 ? {
341 onOpenProviderSetup: (instanceId: ProviderInstanceId) => {
342 void navigate({
343 to: "/settings/providers",
344 search: { environmentId, instanceId },
345 });
346 },
347 }
348 : {})}
349 getModelDisabledReason={writerModelDisabledReason}
350 onInstanceModelChange={(instanceId, model) => {
351 const reason = writerModelDisabledReason(instanceId, model);
352 if (reason) {
353 toastManager.add({
354 type: "error",
355 title: "Source control writer model not saved",
356 description: reason,
357 });
358 return;
359 }
360 updateSettings({
361 sourceControlWriterModelSelection: createModelSelection(instanceId, model),
362 });
363 }}
364 />
365 ) : null}
366 <Switch
367 checked={usesDedicatedModel}
368 disabled={!usesDedicatedModel && !canEnableDedicatedModel}
369 onCheckedChange={(checked) =>
370 updateSettings({
371 sourceControlWriterModelSelection: checked
372 ? createModelSelection(
373 defaultModelSelection.instanceId,
374 defaultModelSelection.model,
375 defaultModelSelection.options,
376 )
377 : null,
378 })
379 }
380 aria-label="Use a separate source control writer model"
381 />
382 </div>
383 )
384 }
385 />
386
387 {/* A beta the server owns: off hides the Guide tab in every client and refuses agents. */}
388 <SettingsRow
389 serverScoped
390 settingKeys={["reviewGuidesEnabled"]}
391 mixed={mixedReviewGuidesEnabled}
392 {...searchableSetting("review-guides")}
393 description="Adds a Guide tab to pull requests: an agent writes a tour of the change, stop by stop, with the calls a maintainer should make."
394 control={
395 <Switch
396 mixed={mixedReviewGuidesEnabled}
397 checked={mixedReviewGuidesEnabled ? false : settings.reviewGuidesEnabled}
398 onCheckedChange={(checked) => updateSettings({ reviewGuidesEnabled: Boolean(checked) })}
399 aria-label="Review guides"
400 />
401 }
402 />
403
404 {settings.reviewGuidesEnabled || mixedReviewGuidesEnabled ? (
405 <>
406 <SettingsRow
407 serverScoped
408 settingKeys={["reviewGuideModelSelection"]}
409 {...searchableSetting("review-guide-model")}
410 description="Model that reads a pull request to write its review guide. It reads the change itself over many steps, so a stronger model helps. Off uses the source control writer model."
411 control={
412 !hasServerTargets ? (
413 <span className="text-sm text-muted-foreground">
414 Connect an environment to choose its review guide model.
415 </span>
416 ) : (
417 <div className="flex flex-wrap items-center justify-end gap-2">
418 {(usesReviewGuideModel || mixedReviewGuideModel) && canEnableDedicatedModel ? (
419 <ProviderModelPicker
420 environmentId={environmentId}
421 activeInstanceId={reviewGuideSelection.instanceId}
422 model={reviewGuideSelection.model}
423 lockedProvider={null}
424 instanceEntries={instanceEntries}
425 modelOptionsByInstance={reviewGuideModelOptionsByInstance}
426 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
427 triggerAriaLabel="Review guide model"
428 {...(mixedReviewGuideModel ? { triggerLabel: "Mixed" } : {})}
429 getModelDisabledReason={writerModelDisabledReason}
430 onInstanceModelChange={(instanceId, model) => {
431 const reason = writerModelDisabledReason(instanceId, model);
432 if (reason) {
433 toastManager.add({
434 type: "error",
435 title: "Review guide model not saved",
436 description: reason,
437 });
438 return;
439 }
440 updateSettings({
441 reviewGuideModelSelection: createModelSelection(instanceId, model),
442 });
443 }}
444 />
445 ) : null}
446 <Switch
447 mixed={mixedReviewGuideModel}
448 checked={mixedReviewGuideModel ? false : usesReviewGuideModel}
449 disabled={!usesReviewGuideModel && !canEnableDedicatedModel}
450 onCheckedChange={(checked) => {
451 if (!checked) {
452 updateSettings({ reviewGuideModelSelection: null });
453 return;
454 }
455 // Every selected target gets this model, so it must run on all of them.
456 const reason = writerModelDisabledReason(
457 activeSelection.instanceId,
458 activeSelection.model,
459 );
460 if (reason) {
461 toastManager.add({
462 type: "error",
463 title: "Review guide model not saved",
464 description: reason,
465 });
466 return;
467 }
468 updateSettings({
469 reviewGuideModelSelection: createModelSelection(
470 activeSelection.instanceId,
471 activeSelection.model,
472 activeSelection.options,
473 ),
474 });
475 }}
476 aria-label="Use a separate review guide model"
477 />
478 </div>
479 )
480 }
481 />
482
483 <SettingsRow
484 serverScoped
485 settingKeys={["reviewGuideInstructions"]}
486 {...searchableSetting("review-guide-instructions")}
487 description="Your preferences for review guides: what to show first, dwell on, or skip. The guide's format and coverage stay the same."
488 resetAction={
489 mixedReviewGuideInstructions || settings.reviewGuideInstructions !== "" ? (
490 <SettingResetButton
491 label="review guide instructions"
492 onClick={() => updateSettings({ reviewGuideInstructions: "" })}
493 />
494 ) : null
495 }
496 >
497 <div className="mt-3 max-w-2xl pb-3.5">
498 <Textarea
499 key={`${scopeKey}:${mixedReviewGuideInstructions}:${settings.reviewGuideInstructions}`}
500 aria-label="Review guide instructions"
501 onChange={() => {
502 reviewGuideInstructionsEdited.current = true;
503 }}
504 rows={4}
505 defaultValue={mixedReviewGuideInstructions ? "" : settings.reviewGuideInstructions}
506 placeholder={
507 mixedReviewGuideInstructions
508 ? "Mixed. Enter instructions to apply to all selected targets."
509 : "Show service interfaces before implementations. Skip test files unless they change behavior. Keep summaries to two sentences."
510 }
511 onBlur={(event) => {
512 const value = event.target.value.trim();
513 if (
514 reviewGuideInstructionsEdited.current &&
515 (mixedReviewGuideInstructions || value !== settings.reviewGuideInstructions)
516 )
517 updateSettings({ reviewGuideInstructions: value });
518 reviewGuideInstructionsEdited.current = false;
519 }}
520 />
521 </div>
522 </SettingsRow>
523 </>
524 ) : null}
525 </SettingsSection>
526 );
527}