Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SourceControlWritingSettings.tsx

640 lines26.5 KB

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";
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: pickModelSelection(
369 mixedReviewGuideModel ? null : reviewGuideSelection,
370 instanceId,
371 model,
372 ),
373 });
374 }}
375 />
376 ) : null}
377 {usesReviewGuideModel &&
378 canEnableReviewGuideModel &&
379 !mixedReviewGuideModel &&
380 reviewGuideInstanceEntry ? (
381 <TraitsPicker
382 provider={reviewGuideInstanceEntry.driverKind}
383 models={reviewGuideInstanceEntry.models}
384 model={reviewGuideSelection.model}
385 modelOptions={reviewGuideSelection.options ?? []}
386 allowPromptInjectedEffort={false}
387 includePlanAgent={selectsPlanAgent(reviewGuideSelection.options)}
388 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
389 onModelOptionsChange={(options) =>
390 updateSettings({
391 reviewGuideModelSelection: createModelSelection(
392 reviewGuideSelection.instanceId,
393 reviewGuideSelection.model,
394 options,
395 ),
396 })
397 }
398 />
399 ) : null}
400 <Switch
401 mixed={mixedReviewGuideModel}
402 checked={mixedReviewGuideModel ? false : usesReviewGuideModel}
403 disabled={!usesReviewGuideModel && !canEnableReviewGuideModel}
404 onCheckedChange={(checked) => {
405 if (!checked) {
406 updateSettings({ reviewGuideModelSelection: null });
407 return;
408 }
409 const seed = textGeneratorForSelection(settings, activeSelection.instanceId)
410 ? reviewGuideSelection
411 : activeSelection;
412 const reason = writerModelDisabledReason(seed.instanceId, seed.model);
413 if (reason) {
414 toastManager.add({
415 type: "error",
416 title: "Review guide model not saved",
417 description: reason,
418 });
419 return;
420 }
421 updateSettings({
422 reviewGuideModelSelection: createModelSelection(
423 seed.instanceId,
424 seed.model,
425 seed.options,
426 ),
427 });
428 }}
429 aria-label="Use a separate review guide model"
430 />
431 </div>
432 )
433 }
434 />
435​
436 <SettingsRow
437 serverScoped
438 settingKeys={["reviewGuideInstructions"]}
439 {...searchableSetting("review-guide-instructions")}
440 description="Your preferences for review guides: what to show first, dwell on, or skip. The guide's format and coverage stay the same."
441 resetAction={
442 mixedReviewGuideInstructions || settings.reviewGuideInstructions !== "" ? (
443 <SettingResetButton
444 label="review guide instructions"
445 onClick={() => updateSettings({ reviewGuideInstructions: "" })}
446 />
447 ) : null
448 }
449 >
450 <div className="mt-3 max-w-2xl pb-3.5">
451 <Textarea
452 key={`${scopeKey}:${mixedReviewGuideInstructions}:${settings.reviewGuideInstructions}`}
453 aria-label="Review guide instructions"
454 onChange={() => {
455 reviewGuideInstructionsEdited.current = true;
456 }}
457 rows={4}
458 defaultValue={mixedReviewGuideInstructions ? "" : settings.reviewGuideInstructions}
459 placeholder={
460 mixedReviewGuideInstructions
461 ? "Mixed. Enter instructions to apply to all selected targets."
462 : "Show service interfaces before implementations. Skip test files unless they change behavior. Keep summaries to two sentences."
463 }
464 onBlur={(event) => {
465 const value = event.target.value.trim();
466 if (
467 reviewGuideInstructionsEdited.current &&
468 (mixedReviewGuideInstructions || value !== settings.reviewGuideInstructions)
469 )
470 updateSettings({ reviewGuideInstructions: value });
471 reviewGuideInstructionsEdited.current = false;
472 }}
473 />
474 </div>
475 </SettingsRow>
476 </>
477 ) : null}
478 <AdvancedSettings
479 targetIds={[
480 searchableSetting("follow-change-request-templates").id,
481 searchableSetting("source-control-writer-model").id,
482 ]}
483 >
484 <SettingsRow
485 serverScoped
486 settingKeys={["sourceControlWritingStyle"]}
487 mixed={templatesMixed}
488 {...searchableSetting("follow-change-request-templates")}
489 description="Use the repository's pull request template when it has one."
490 resetAction={
491 templatesMixed ||
492 style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
493 <SettingResetButton
494 label="pull request templates"
495 onClick={() =>
496 updateSettings({
497 sourceControlWritingStyle: {
498 followChangeRequestTemplates: defaults.followChangeRequestTemplates,
499 },
500 })
501 }
502 />
503 ) : null
504 }
505 control={
506 <Switch
507 mixed={templatesMixed}
508 checked={templatesMixed ? false : style.followChangeRequestTemplates}
509 onCheckedChange={(checked) =>
510 updateSettings({
511 sourceControlWritingStyle: {
512 followChangeRequestTemplates: Boolean(checked),
513 },
514 })
515 }
516 aria-label="Follow pull request templates"
517 />
518 }
519 />
520​
521 <SettingsRow
522 serverScoped
523 settingKeys={["sourceControlWriterModelSelection"]}
524 {...searchableSetting("source-control-writer-model")}
525 description="Model for commit messages, pull request text, and branch or bookmark names. When disabled, use the text generation model configured for this environment."
526 control={
527 !hasServerTargets ? (
528 <span className="text-sm text-muted-foreground">
529 Connect an environment to choose its source control writer model.
530 </span>
531 ) : (
532 <div className="flex flex-wrap items-center justify-end gap-2">
533 {usesDedicatedModel && !canEnableDedicatedModel ? (
534 <span className="text-sm text-muted-foreground">
535 No text generation providers available.
536 </span>
537 ) : null}
538 {usesDedicatedModel && canEnableDedicatedModel ? (
539 <ProviderModelPicker
540 environmentId={environmentId}
541 activeInstanceId={activeSelection.instanceId}
542 model={activeSelection.model}
543 lockedProvider={null}
544 instanceEntries={writerEntries}
545 modelOptionsByInstance={modelOptionsByInstance}
546 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
547 triggerAriaLabel="Source control writer model"
548 {...(mixedWriterModel ? { triggerLabel: "Mixed" } : {})}
549 {...(environmentId
550 ? {
551 onOpenProviderSetup: (instanceId: ProviderInstanceId) => {
552 void navigate({
553 to: "/settings/providers",
554 search: { environmentId, instanceId },
555 });
556 },
557 }
558 : {})}
559 getModelDisabledReason={writerModelDisabledReason}
560 onInstanceModelChange={(instanceId, model) => {
561 const reason = writerModelDisabledReason(instanceId, model);
562 if (reason) {
563 toastManager.add({
564 type: "error",
565 title: "Source control writer model not saved",
566 description: reason,
567 });
568 return;
569 }
570 updateSettings({
571 sourceControlWriterModelSelection: pickModelSelection(
572 mixedWriterModel ? null : activeSelection,
573 instanceId,
574 model,
575 ),
576 });
577 }}
578 />
579 ) : null}
580 {usesDedicatedModel &&
581 canEnableDedicatedModel &&
582 !mixedWriterModel &&
583 writerInstanceEntry ? (
584 <TraitsPicker
585 provider={writerInstanceEntry.driverKind}
586 models={writerInstanceEntry.models}
587 model={activeSelection.model}
588 modelOptions={activeSelection.options ?? []}
589 allowPromptInjectedEffort={false}
590 includePlanAgent={selectsPlanAgent(activeSelection.options)}
591 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
592 onModelOptionsChange={(options) =>
593 updateSettings({
594 sourceControlWriterModelSelection: createModelSelection(
595 activeSelection.instanceId,
596 activeSelection.model,
597 options,
598 ),
599 })
600 }
601 />
602 ) : null}
603 <Switch
604 checked={usesDedicatedModel}
605 disabled={!usesDedicatedModel && !canEnableDedicatedModel}
606 onCheckedChange={(checked) => {
607 if (checked) {
608 const reason = writerModelDisabledReason(
609 defaultModelSelection.instanceId,
610 defaultModelSelection.model,
611 );
612 if (reason) {
613 toastManager.add({
614 type: "error",
615 title: "Writer model not saved",
616 description: reason,
617 });
618 return;
619 }
620 }
621 updateSettings({
622 sourceControlWriterModelSelection: checked
623 ? createModelSelection(
624 defaultModelSelection.instanceId,
625 defaultModelSelection.model,
626 defaultModelSelection.options,
627 )
628 : null,
629 });
630 }}
631 aria-label="Use a separate source control writer model"
632 />
633 </div>
634 )
635 }
636 />
637 </AdvancedSettings>
638 </SettingsSection>
639 );