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