Open History to see the last commit
1import { useNavigate } from "@tanstack/react-router";
2import { useRef, useState } from "react";
3import {
4 type ProviderInstanceId,
5 type ServerSettings,
6 type SourceControlWritingStyleMode,
7 textGeneratorForSelection,
8} from "@t3tools/contracts";
9import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
10import { createModelSelection, pickModelSelection } from "@t3tools/shared/model";
11import {
12 resolveReviewGuideModelSelection,
13 resolveSourceControlWriterModelSelection,
14} from "@t3tools/shared/serverSettings";
15import { msg, T, useGT, useMessages } from "gt-react";
16
17import {
18 useScopedSettings,
19 useScopedSettingsMixed,
20 useUpdateScopedSettings,
21} from "./useScopedSettings";
22import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
23import { useSettingsScope } from "./SettingsScopeContext";
24import { providerInstanceEntriesFor } from "../../providerInstances";
25import { useTextGenerationTargets } from "../../textGenerators";
26import {
27 getTextGenerationModelOptionsByInstance,
28 resolveAppModelSelectionState,
29 selectsPlanAgent,
30} from "../../modelSelection";
31import { useEnvironmentProviders } from "../../state/environments";
32import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
33import { ProviderModelPicker } from "../chat/ProviderModelPicker";
34import { TraitsPicker } from "../chat/TraitsPicker";
35import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
36import { Switch } from "../ui/switch";
37import { Textarea } from "../ui/textarea";
38import { toastManager } from "../ui/toast";
39import { Button } from "../ui/button";
40import {
41 SETTINGS_PICKER_TRIGGER_CLASSNAME,
42 SettingResetButton,
43 SettingsRow,
44 SettingsSection,
45} from "./settingsLayout";
46import { AdvancedSettings } from "./AdvancedSettings";
47import { useSearchableSetting } from "./settingsSearch";
48
49const MODE_OPTIONS: Record<SourceControlWritingStyleMode, { label: string; description: string }> =
50 {
51 repo_conventions: {
52 label: msg("Repository conventions"),
53 description: msg(
54 "Commit messages and pull request titles and descriptions match each project's history.",
55 ),
56 },
57 conventional_commits: {
58 label: msg("Conventional Commits"),
59 description: msg(
60 "Conventional Commit prefixes, with short pull request titles and descriptions.",
61 ),
62 },
63 custom: {
64 label: msg("Custom instructions"),
65 description: msg(
66 "Your instructions shape commit messages and pull request titles and descriptions.",
67 ),
68 },
69 };
70
71export function SourceControlWritingSettingsSection() {
72 const messages = useMessages();
73 const setting = useSearchableSetting();
74 const gt = useGT();
75 const settings = useScopedSettings();
76 const updateSettings = useUpdateScopedSettings();
77 const mixedReviewGuidesEnabled = useScopedSettingsMixed(["reviewGuidesEnabled"]);
78 const navigate = useNavigate();
79 const { environment, connectedEnvironments, targets, target } = useSettingsScope();
80 const environmentId = environment?.environmentId ?? null;
81 const hasServerTargets = connectedEnvironments.length > 0;
82 const providersByEnvironment = useEnvironmentProviders();
83 const serverProviders =
84 (environment?.serverConfig
85 ? providersByEnvironment.get(environment.environmentId)
86 : undefined) ?? EMPTY_SERVER_PROVIDERS;
87 const styleFieldMixed = (field: keyof ServerSettings["sourceControlWritingStyle"]) => {
88 const first = targets[0];
89 return (
90 first !== undefined &&
91 targets.some(
92 (candidate) =>
93 candidate.settings.sourceControlWritingStyle[field] !==
94 first.settings.sourceControlWritingStyle[field],
95 )
96 );
97 };
98 const modeMixed = styleFieldMixed("mode");
99 const instructionsMixed = styleFieldMixed("customInstructions");
100 const templatesMixed = styleFieldMixed("followChangeRequestTemplates");
101 const writingStyleMixed = modeMixed || instructionsMixed;
102 const mixedWriterModel = useScopedSettingsMixed(["sourceControlWriterModelSelection"]);
103 const mixedReviewGuideModel = useScopedSettingsMixed(["reviewGuideModelSelection"]);
104 const mixedReviewGuideInstructions = useScopedSettingsMixed(["reviewGuideInstructions"]);
105 const reviewGuideInstructionsEdited = useRef(false);
106 const scopeKey = targets.map((target) => `${target.environmentId}:${target.projectId}`).join(",");
107 const customInstructionsRef = useRef<HTMLTextAreaElement>(null);
108 const [editingAllInstructions, setEditingAllInstructions] = useState(false);
109 const [allInstructions, setAllInstructions] = useState<string | null>(null);
110 const style = settings.sourceControlWritingStyle;
111 const defaults = DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
112 const isSourceControlWritingStyleDirty =
113 writingStyleMixed ||
114 style.mode !== defaults.mode ||
115 style.customInstructions !== defaults.customInstructions;
116
117 const textGenerationProviders = serverProviders.filter(
118 (provider) => provider.supportsTextGeneration !== false,
119 );
120 const instanceEntries = providerInstanceEntriesFor(
121 textGenerationProviders,
122 settings,
123 target?.projectId ?? null,
124 );
125 // Text generators may write source control text, but never review guides.
126 const writerTargets = useTextGenerationTargets({
127 environmentId,
128 settings,
129 providers: textGenerationProviders,
130 projectId: target?.projectId ?? null,
131 selections: [settings.sourceControlWriterModelSelection, settings.textGenerationModelSelection],
132 });
133 const writerEntries = writerTargets.entries;
134 const projectEnabledInstanceIds = new Set(
135 writerEntries
136 .filter((entry) => entry.enabled && entry.isAvailable)
137 .map((entry) => entry.instanceId),
138 );
139 const projectEffectiveTextGenerationProviders = writerTargets.providers.filter((provider) =>
140 projectEnabledInstanceIds.has(provider.instanceId),
141 );
142 const defaultModelSelection = resolveAppModelSelectionState(
143 settings,
144 projectEffectiveTextGenerationProviders,
145 );
146 const usesDedicatedModel = settings.sourceControlWriterModelSelection !== null;
147 const activeSelection = resolveAppModelSelectionState(
148 {
149 ...settings,
150 textGenerationModelSelection: resolveSourceControlWriterModelSelection(
151 settings,
152 projectEffectiveTextGenerationProviders,
153 target?.projectId ?? null,
154 ),
155 },
156 projectEffectiveTextGenerationProviders,
157 );
158 const canEnableDedicatedModel = writerEntries.some(
159 (entry) =>
160 entry.instanceId === defaultModelSelection.instanceId && entry.enabled && entry.isAvailable,
161 );
162 const modelOptionsByInstance = getTextGenerationModelOptionsByInstance(
163 settings,
164 projectEffectiveTextGenerationProviders,
165 activeSelection.instanceId,
166 activeSelection.model,
167 );
168 const writerModelDisabledReason = useScopedModelDisabledReason(settings, writerEntries, true);
169 const writerInstanceEntry = writerEntries.find(
170 (entry) => entry.instanceId === activeSelection.instanceId,
171 );
172 const usesReviewGuideModel = settings.reviewGuideModelSelection !== null;
173 // Resolve against agents this project can use, so the fallback never lands on one it turned off.
174 const projectAgentProviders = textGenerationProviders.filter((provider) =>
175 instanceEntries.some(
176 (entry) => entry.instanceId === provider.instanceId && entry.enabled && entry.isAvailable,
177 ),
178 );
179 const reviewGuideSelection = resolveAppModelSelectionState(
180 {
181 ...settings,
182 textGenerationModelSelection: resolveReviewGuideModelSelection(
183 settings,
184 projectAgentProviders,
185 target?.projectId ?? null,
186 ),
187 },
188 projectAgentProviders,
189 );
190 const reviewGuideModelOptionsByInstance = getTextGenerationModelOptionsByInstance(
191 settings,
192 projectAgentProviders,
193 reviewGuideSelection.instanceId,
194 reviewGuideSelection.model,
195 );
196 const canEnableReviewGuideModel = instanceEntries.some(
197 (entry) =>
198 entry.instanceId === reviewGuideSelection.instanceId && entry.enabled && entry.isAvailable,
199 );
200 const reviewGuideInstanceEntry = instanceEntries.find(
201 (entry) => entry.instanceId === reviewGuideSelection.instanceId,
202 );
203
204 return (
205 <SettingsSection id="source-control-text-generation" title={gt`Commits & pull requests`}>
206 <SettingsRow
207 serverScoped
208 settingKeys={["sourceControlWritingStyle"]}
209 mixed={writingStyleMixed}
210 {...setting("source-control-writing-style")}
211 description={messages(MODE_OPTIONS[style.mode].description)}
212 resetAction={
213 isSourceControlWritingStyleDirty ? (
214 <SettingResetButton
215 ariaLabel={gt`Reset commit and pull request writing to default`}
216 onClick={() =>
217 updateSettings({
218 sourceControlWritingStyle: {
219 mode: defaults.mode,
220 customInstructions: defaults.customInstructions,
221 },
222 })
223 }
224 />
225 ) : null
226 }
227 control={
228 <Select
229 value={modeMixed ? null : style.mode}
230 onValueChange={(value) => {
231 const customInstructions = customInstructionsRef.current?.value.trim();
232 updateSettings({
233 sourceControlWritingStyle: {
234 mode: value as SourceControlWritingStyleMode,
235 ...(customInstructions !== undefined ? { customInstructions } : {}),
236 },
237 });
238 }}
239 >
240 <SelectTrigger
241 size="sm"
242 className="w-full sm:w-56"
243 aria-label={gt`Commit and pull request writing`}
244 >
245 <SelectValue>
246 {(value: SourceControlWritingStyleMode | null) =>
247 value === null ? gt`Mixed` : messages(MODE_OPTIONS[value].label)
248 }
249 </SelectValue>
250 </SelectTrigger>
251 <SelectPopup align="end" alignItemWithTrigger={false}>
252 {(Object.keys(MODE_OPTIONS) as SourceControlWritingStyleMode[]).map((mode) => (
253 <SelectItem key={mode} hideIndicator value={mode}>
254 {messages(MODE_OPTIONS[mode].label)}
255 </SelectItem>
256 ))}
257 </SelectPopup>
258 </Select>
259 }
260 >
261 {writingStyleMixed ? (
262 <div className="mt-3 max-w-2xl space-y-2 pb-3.5">
263 {editingAllInstructions ? (
264 <>
265 <Textarea
266 value={allInstructions ?? ""}
267 onChange={(event) => setAllInstructions(event.target.value)}
268 rows={4}
269 aria-label={gt`Custom commit and pull request instructions for all selected environments`}
270 placeholder={gt`Write the instructions each selected environment should use.`}
271 />
272 <Button
273 size="sm"
274 variant="outline"
275 disabled={allInstructions === null}
276 onClick={() => {
277 if (allInstructions === null) return;
278 updateSettings({
279 sourceControlWritingStyle: {
280 mode: "custom",
281 customInstructions: allInstructions.trim(),
282 },
283 });
284 setEditingAllInstructions(false);
285 }}
286 >
287 <T>Apply instructions to all</T>
288 </Button>
289 </>
290 ) : (
291 <Button
292 size="sm"
293 variant="outline"
294 onClick={() => {
295 setAllInstructions(null);
296 setEditingAllInstructions(true);
297 }}
298 >
299 <T>Write custom instructions for all</T>
300 </Button>
301 )}
302 </div>
303 ) : style.mode === "custom" ? (
304 <div className="mt-3 max-w-2xl pb-3.5">
305 <Textarea
306 key={style.customInstructions}
307 ref={customInstructionsRef}
308 defaultValue={style.customInstructions}
309 onBlur={(event) => {
310 const customInstructions = event.target.value.trim();
311 if (customInstructions !== style.customInstructions) {
312 updateSettings({ sourceControlWritingStyle: { customInstructions } });
313 }
314 }}
315 rows={4}
316 placeholder={gt`Keep commit subjects under 60 characters. Keep pull request descriptions short and plain.`}
317 aria-label={gt`Custom commit and pull request instructions`}
318 />
319 </div>
320 ) : null}
321 </SettingsRow>
322
323 <SettingsRow
324 serverScoped
325 settingKeys={["reviewGuidesEnabled"]}
326 mixed={mixedReviewGuidesEnabled}
327 {...setting("review-guides")}
328 description={gt`Add a Guide tab to pull requests. An agent explains the changes and points out decisions that need review.`}
329 control={
330 <Switch
331 mixed={mixedReviewGuidesEnabled}
332 checked={mixedReviewGuidesEnabled ? false : settings.reviewGuidesEnabled}
333 onCheckedChange={(checked) => updateSettings({ reviewGuidesEnabled: Boolean(checked) })}
334 aria-label={gt`Review guides`}
335 />
336 }
337 />
338
339 {settings.reviewGuidesEnabled || mixedReviewGuidesEnabled ? (
340 <>
341 <SettingsRow
342 serverScoped
343 settingKeys={["reviewGuideModelSelection"]}
344 {...setting("review-guide-model")}
345 description={gt`Must be a coding agent: it reads the pull request over many steps. Off uses the writer model, or Codex or Claude if that model is a text generator.`}
346 control={
347 !hasServerTargets ? (
348 <span className="text-sm text-muted-foreground">
349 <T>Connect an environment to choose its review guide model.</T>
350 </span>
351 ) : (
352 <div className="flex flex-wrap items-center justify-end gap-2">
353 {(usesReviewGuideModel || mixedReviewGuideModel) && canEnableReviewGuideModel ? (
354 <ProviderModelPicker
355 environmentId={environmentId}
356 activeInstanceId={reviewGuideSelection.instanceId}
357 model={reviewGuideSelection.model}
358 lockedProvider={null}
359 instanceEntries={instanceEntries}
360 modelOptionsByInstance={reviewGuideModelOptionsByInstance}
361 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
362 triggerAriaLabel={gt`Review guide model`}
363 {...(mixedReviewGuideModel ? { triggerLabel: gt`Mixed` } : {})}
364 getModelDisabledReason={writerModelDisabledReason}
365 onInstanceModelChange={(instanceId, model) => {
366 const reason = writerModelDisabledReason(instanceId, model);
367 if (reason) {
368 toastManager.add({
369 type: "error",
370 title: gt`Review guide model not saved`,
371 description: reason,
372 });
373 return;
374 }
375 updateSettings({
376 reviewGuideModelSelection: pickModelSelection(
377 mixedReviewGuideModel ? null : reviewGuideSelection,
378 instanceId,
379 model,
380 ),
381 });
382 }}
383 />
384 ) : null}
385 {usesReviewGuideModel &&
386 canEnableReviewGuideModel &&
387 !mixedReviewGuideModel &&
388 reviewGuideInstanceEntry ? (
389 <TraitsPicker
390 provider={reviewGuideInstanceEntry.driverKind}
391 models={reviewGuideInstanceEntry.models}
392 model={reviewGuideSelection.model}
393 modelOptions={reviewGuideSelection.options ?? []}
394 allowPromptInjectedEffort={false}
395 includePlanAgent={selectsPlanAgent(reviewGuideSelection.options)}
396 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
397 onModelOptionsChange={(options) =>
398 updateSettings({
399 reviewGuideModelSelection: createModelSelection(
400 reviewGuideSelection.instanceId,
401 reviewGuideSelection.model,
402 options,
403 ),
404 })
405 }
406 />
407 ) : null}
408 <Switch
409 mixed={mixedReviewGuideModel}
410 checked={mixedReviewGuideModel ? false : usesReviewGuideModel}
411 disabled={!usesReviewGuideModel && !canEnableReviewGuideModel}
412 onCheckedChange={(checked) => {
413 if (!checked) {
414 updateSettings({ reviewGuideModelSelection: null });
415 return;
416 }
417 const seed = textGeneratorForSelection(settings, activeSelection.instanceId)
418 ? reviewGuideSelection
419 : activeSelection;
420 const reason = writerModelDisabledReason(seed.instanceId, seed.model);
421 if (reason) {
422 toastManager.add({
423 type: "error",
424 title: gt`Review guide model not saved`,
425 description: reason,
426 });
427 return;
428 }
429 updateSettings({
430 reviewGuideModelSelection: createModelSelection(
431 seed.instanceId,
432 seed.model,
433 seed.options,
434 ),
435 });
436 }}
437 aria-label={gt`Use a separate review guide model`}
438 />
439 </div>
440 )
441 }
442 />
443
444 <SettingsRow
445 serverScoped
446 settingKeys={["reviewGuideInstructions"]}
447 {...setting("review-guide-instructions")}
448 description={gt`Your preferences for review guides: what to show first, dwell on, or skip. The guide's format and coverage stay the same.`}
449 resetAction={
450 mixedReviewGuideInstructions || settings.reviewGuideInstructions !== "" ? (
451 <SettingResetButton
452 ariaLabel={gt`Reset review guide instructions to default`}
453 onClick={() => updateSettings({ reviewGuideInstructions: "" })}
454 />
455 ) : null
456 }
457 >
458 <div className="mt-3 max-w-2xl pb-3.5">
459 <Textarea
460 key={`${scopeKey}:${mixedReviewGuideInstructions}:${settings.reviewGuideInstructions}`}
461 aria-label={gt`Review guide instructions`}
462 onChange={() => {
463 reviewGuideInstructionsEdited.current = true;
464 }}
465 rows={4}
466 defaultValue={mixedReviewGuideInstructions ? "" : settings.reviewGuideInstructions}
467 placeholder={
468 mixedReviewGuideInstructions
469 ? gt`Mixed. Enter instructions to apply to all selected targets.`
470 : gt`Show service interfaces before implementations. Skip test files unless they change behavior. Keep summaries to two sentences.`
471 }
472 onBlur={(event) => {
473 const value = event.target.value.trim();
474 if (
475 reviewGuideInstructionsEdited.current &&
476 (mixedReviewGuideInstructions || value !== settings.reviewGuideInstructions)
477 )
478 updateSettings({ reviewGuideInstructions: value });
479 reviewGuideInstructionsEdited.current = false;
480 }}
481 />
482 </div>
483 </SettingsRow>
484 </>
485 ) : null}
486 <AdvancedSettings
487 targetIds={[
488 setting("follow-change-request-templates").id,
489 setting("source-control-writer-model").id,
490 ]}
491 >
492 <SettingsRow
493 serverScoped
494 settingKeys={["sourceControlWritingStyle"]}
495 mixed={templatesMixed}
496 {...setting("follow-change-request-templates")}
497 description={gt`Use the repository's pull request template when it has one.`}
498 resetAction={
499 templatesMixed ||
500 style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
501 <SettingResetButton
502 ariaLabel={gt`Reset pull request templates to default`}
503 onClick={() =>
504 updateSettings({
505 sourceControlWritingStyle: {
506 followChangeRequestTemplates: defaults.followChangeRequestTemplates,
507 },
508 })
509 }
510 />
511 ) : null
512 }
513 control={
514 <Switch
515 mixed={templatesMixed}
516 checked={templatesMixed ? false : style.followChangeRequestTemplates}
517 onCheckedChange={(checked) =>
518 updateSettings({
519 sourceControlWritingStyle: {
520 followChangeRequestTemplates: Boolean(checked),
521 },
522 })
523 }
524 aria-label={gt`Follow pull request templates`}
525 />
526 }
527 />
528
529 <SettingsRow
530 serverScoped
531 settingKeys={["sourceControlWriterModelSelection"]}
532 {...setting("source-control-writer-model")}
533 description={gt`Model for commit messages, pull request text, and branch or bookmark names. When disabled, use the text generation model configured for this environment.`}
534 control={
535 !hasServerTargets ? (
536 <span className="text-sm text-muted-foreground">
537 <T>Connect an environment to choose its source control writer model.</T>
538 </span>
539 ) : (
540 <div className="flex flex-wrap items-center justify-end gap-2">
541 {usesDedicatedModel && !canEnableDedicatedModel ? (
542 <span className="text-sm text-muted-foreground">
543 <T>No text generation providers available.</T>
544 </span>
545 ) : null}
546 {usesDedicatedModel && canEnableDedicatedModel ? (
547 <ProviderModelPicker
548 environmentId={environmentId}
549 activeInstanceId={activeSelection.instanceId}
550 model={activeSelection.model}
551 lockedProvider={null}
552 instanceEntries={writerEntries}
553 modelOptionsByInstance={modelOptionsByInstance}
554 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
555 triggerAriaLabel={gt`Source control writer model`}
556 {...(mixedWriterModel ? { triggerLabel: gt`Mixed` } : {})}
557 {...(environmentId
558 ? {
559 onOpenProviderSetup: (instanceId: ProviderInstanceId) => {
560 void navigate({
561 to: "/settings/providers",
562 search: { environmentId, instanceId },
563 });
564 },
565 }
566 : {})}
567 getModelDisabledReason={writerModelDisabledReason}
568 onInstanceModelChange={(instanceId, model) => {
569 const reason = writerModelDisabledReason(instanceId, model);
570 if (reason) {
571 toastManager.add({
572 type: "error",
573 title: gt`Source control writer model not saved`,
574 description: reason,
575 });
576 return;
577 }
578 updateSettings({
579 sourceControlWriterModelSelection: pickModelSelection(
580 mixedWriterModel ? null : activeSelection,
581 instanceId,
582 model,
583 ),
584 });
585 }}
586 />
587 ) : null}
588 {usesDedicatedModel &&
589 canEnableDedicatedModel &&
590 !mixedWriterModel &&
591 writerInstanceEntry ? (
592 <TraitsPicker
593 provider={writerInstanceEntry.driverKind}
594 models={writerInstanceEntry.models}
595 model={activeSelection.model}
596 modelOptions={activeSelection.options ?? []}
597 allowPromptInjectedEffort={false}
598 includePlanAgent={selectsPlanAgent(activeSelection.options)}
599 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
600 onModelOptionsChange={(options) =>
601 updateSettings({
602 sourceControlWriterModelSelection: createModelSelection(
603 activeSelection.instanceId,
604 activeSelection.model,
605 options,
606 ),
607 })
608 }
609 />
610 ) : null}
611 <Switch
612 checked={usesDedicatedModel}
613 disabled={!usesDedicatedModel && !canEnableDedicatedModel}
614 onCheckedChange={(checked) => {
615 if (checked) {
616 const reason = writerModelDisabledReason(
617 defaultModelSelection.instanceId,
618 defaultModelSelection.model,
619 );
620 if (reason) {
621 toastManager.add({
622 type: "error",
623 title: gt`Writer model not saved`,
624 description: reason,
625 });
626 return;
627 }
628 }
629 updateSettings({
630 sourceControlWriterModelSelection: checked
631 ? createModelSelection(
632 defaultModelSelection.instanceId,
633 defaultModelSelection.model,
634 defaultModelSelection.options,
635 )
636 : null,
637 });
638 }}
639 aria-label={gt`Use a separate source control writer model`}
640 />
641 </div>
642 )
643 }
644 />
645 </AdvancedSettings>
646 </SettingsSection>
647 );
648}