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

SourceControlWritingSettings.tsx

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