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