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

SourceControlWritingSettings.tsx

606 lines24.9 KB

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 { AdvancedSettings } from "./AdvancedSettings";
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="Writing & review">
182 <SettingsRow
183 serverScoped
184 settingKeys={["sourceControlWritingStyle"]}
185 mixed={writingStyleMixed}
186 {...searchableSetting("source-control-writing-style")}
187 description={MODE_OPTIONS[style.mode].description}
188 resetAction={
189 isSourceControlWritingStyleDirty ? (
190 <SettingResetButton
191 label="source control writing style"
192 onClick={() =>
193 updateSettings({
194 sourceControlWritingStyle: {
195 mode: defaults.mode,
196 customInstructions: defaults.customInstructions,
197 },
198 })
199 }
200 />
201 ) : null
202 }
203 control={
204 <Select
205 value={modeMixed ? null : style.mode}
206 onValueChange={(value) => {
207 const customInstructions = customInstructionsRef.current?.value.trim();
208 updateSettings({
209 sourceControlWritingStyle: {
210 mode: value as SourceControlWritingStyleMode,
211 ...(customInstructions !== undefined ? { customInstructions } : {}),
212 },
213 });
214 }}
215 >
216 <SelectTrigger
217 size="sm"
218 className="w-full sm:w-56"
219 aria-label="Source control writing style"
220 >
221 <SelectValue>
222 {(value: SourceControlWritingStyleMode | null) =>
223 value === null ? "Mixed" : MODE_OPTIONS[value].label
224 }
225 </SelectValue>
226 </SelectTrigger>
227 <SelectPopup align="end" alignItemWithTrigger={false}>
228 {(Object.keys(MODE_OPTIONS) as SourceControlWritingStyleMode[]).map((mode) => (
229 <SelectItem key={mode} hideIndicator value={mode}>
230 {MODE_OPTIONS[mode].label}
231 </SelectItem>
232 ))}
233 </SelectPopup>
234 </Select>
235 }
236 >
237 {writingStyleMixed ? (
238 <div className="mt-3 max-w-2xl space-y-2 pb-3.5">
239 {editingAllInstructions ? (
240 <>
241 <Textarea
242 value={allInstructions ?? ""}
243 onChange={(event) => setAllInstructions(event.target.value)}
244 rows={4}
245 aria-label="Custom source control instructions for all selected environments"
246 placeholder="Write the instructions each selected environment should use."
247 />
248 <Button
249 size="sm"
250 variant="outline"
251 disabled={allInstructions === null}
252 onClick={() => {
253 if (allInstructions === null) return;
254 updateSettings({
255 sourceControlWritingStyle: {
256 mode: "custom",
257 customInstructions: allInstructions.trim(),
258 },
259 });
260 setEditingAllInstructions(false);
261 }}
262 >
263 Apply instructions to all
264 </Button>
265 </>
266 ) : (
267 <Button
268 size="sm"
269 variant="outline"
270 onClick={() => {
271 setAllInstructions(null);
272 setEditingAllInstructions(true);
273 }}
274 >
275 Write custom instructions for all
276 </Button>
277 )}
278 </div>
279 ) : style.mode === "custom" ? (
280 <div className="mt-3 max-w-2xl pb-3.5">
281 <Textarea
282 key={style.customInstructions}
283 ref={customInstructionsRef}
284 defaultValue={style.customInstructions}
285 onBlur={(event) => {
286 const customInstructions = event.target.value.trim();
287 if (customInstructions !== style.customInstructions) {
288 updateSettings({ sourceControlWritingStyle: { customInstructions } });
289 }
290 }}
291 rows={4}
292 placeholder="Keep titles concise. Use short bullet points in descriptions."
293 aria-label="Custom source control writing instructions"
294 />
295 </div>
296 ) : null}
297 </SettingsRow>
298​
299 <SettingsRow
300 serverScoped
301 settingKeys={["reviewGuidesEnabled"]}
302 mixed={mixedReviewGuidesEnabled}
303 {...searchableSetting("review-guides")}
304 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."
305 control={
306 <Switch
307 mixed={mixedReviewGuidesEnabled}
308 checked={mixedReviewGuidesEnabled ? false : settings.reviewGuidesEnabled}
309 onCheckedChange={(checked) => updateSettings({ reviewGuidesEnabled: Boolean(checked) })}
310 aria-label="Review guides"
311 />
312 }
313 />
314​
315 {settings.reviewGuidesEnabled || mixedReviewGuidesEnabled ? (
316 <>
317 <SettingsRow
318 serverScoped
319 settingKeys={["reviewGuideModelSelection"]}
320 {...searchableSetting("review-guide-model")}
321 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."
322 control={
323 !hasServerTargets ? (
324 <span className="text-sm text-muted-foreground">
325 Connect an environment to choose its review guide model.
326 </span>
327 ) : (
328 <div className="flex flex-wrap items-center justify-end gap-2">
329 {(usesReviewGuideModel || mixedReviewGuideModel) && canEnableDedicatedModel ? (
330 <ProviderModelPicker
331 environmentId={environmentId}
332 activeInstanceId={reviewGuideSelection.instanceId}
333 model={reviewGuideSelection.model}
334 lockedProvider={null}
335 instanceEntries={instanceEntries}
336 modelOptionsByInstance={reviewGuideModelOptionsByInstance}
337 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
338 triggerAriaLabel="Review guide model"
339 {...(mixedReviewGuideModel ? { triggerLabel: "Mixed" } : {})}
340 getModelDisabledReason={writerModelDisabledReason}
341 onInstanceModelChange={(instanceId, model) => {
342 const reason = writerModelDisabledReason(instanceId, model);
343 if (reason) {
344 toastManager.add({
345 type: "error",
346 title: "Review guide model not saved",
347 description: reason,
348 });
349 return;
350 }
351 updateSettings({
352 reviewGuideModelSelection: createModelSelection(instanceId, model),
353 });
354 }}
355 />
356 ) : null}
357 {usesReviewGuideModel &&
358 canEnableDedicatedModel &&
359 !mixedReviewGuideModel &&
360 reviewGuideInstanceEntry ? (
361 <TraitsPicker
362 provider={reviewGuideInstanceEntry.driverKind}
363 models={reviewGuideInstanceEntry.models}
364 model={reviewGuideSelection.model}
365 modelOptions={reviewGuideSelection.options ?? []}
366 allowPromptInjectedEffort={false}
367 planModeEnabled={
368 settings.planModeEnabled || selectsPlanAgent(reviewGuideSelection.options)
369 }
370 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
371 onModelOptionsChange={(options) =>
372 updateSettings({
373 reviewGuideModelSelection: createModelSelection(
374 reviewGuideSelection.instanceId,
375 reviewGuideSelection.model,
376 options,
377 ),
378 })
379 }
380 />
381 ) : null}
382 <Switch
383 mixed={mixedReviewGuideModel}
384 checked={mixedReviewGuideModel ? false : usesReviewGuideModel}
385 disabled={!usesReviewGuideModel && !canEnableDedicatedModel}
386 onCheckedChange={(checked) => {
387 if (!checked) {
388 updateSettings({ reviewGuideModelSelection: null });
389 return;
390 }
391 const reason = writerModelDisabledReason(
392 activeSelection.instanceId,
393 activeSelection.model,
394 );
395 if (reason) {
396 toastManager.add({
397 type: "error",
398 title: "Review guide model not saved",
399 description: reason,
400 });
401 return;
402 }
403 updateSettings({
404 reviewGuideModelSelection: createModelSelection(
405 activeSelection.instanceId,
406 activeSelection.model,
407 activeSelection.options,
408 ),
409 });
410 }}
411 aria-label="Use a separate review guide model"
412 />
413 </div>
414 )
415 }
416 />
417​
418 <SettingsRow
419 serverScoped
420 settingKeys={["reviewGuideInstructions"]}
421 {...searchableSetting("review-guide-instructions")}
422 description="Your preferences for review guides: what to show first, dwell on, or skip. The guide's format and coverage stay the same."
423 resetAction={
424 mixedReviewGuideInstructions || settings.reviewGuideInstructions !== "" ? (
425 <SettingResetButton
426 label="review guide instructions"
427 onClick={() => updateSettings({ reviewGuideInstructions: "" })}
428 />
429 ) : null
430 }
431 >
432 <div className="mt-3 max-w-2xl pb-3.5">
433 <Textarea
434 key={`${scopeKey}:${mixedReviewGuideInstructions}:${settings.reviewGuideInstructions}`}
435 aria-label="Review guide instructions"
436 onChange={() => {
437 reviewGuideInstructionsEdited.current = true;
438 }}
439 rows={4}
440 defaultValue={mixedReviewGuideInstructions ? "" : settings.reviewGuideInstructions}
441 placeholder={
442 mixedReviewGuideInstructions
443 ? "Mixed. Enter instructions to apply to all selected targets."
444 : "Show service interfaces before implementations. Skip test files unless they change behavior. Keep summaries to two sentences."
445 }
446 onBlur={(event) => {
447 const value = event.target.value.trim();
448 if (
449 reviewGuideInstructionsEdited.current &&
450 (mixedReviewGuideInstructions || value !== settings.reviewGuideInstructions)
451 )
452 updateSettings({ reviewGuideInstructions: value });
453 reviewGuideInstructionsEdited.current = false;
454 }}
455 />
456 </div>
457 </SettingsRow>
458 </>
459 ) : null}
460 <AdvancedSettings
461 targetIds={[
462 searchableSetting("follow-change-request-templates").id,
463 searchableSetting("source-control-writer-model").id,
464 ]}
465 >
466 <SettingsRow
467 serverScoped
468 settingKeys={["sourceControlWritingStyle"]}
469 mixed={templatesMixed}
470 {...searchableSetting("follow-change-request-templates")}
471 description="Use the repository's template for change request descriptions when available."
472 resetAction={
473 templatesMixed ||
474 style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
475 <SettingResetButton
476 label="change request templates"
477 onClick={() =>
478 updateSettings({
479 sourceControlWritingStyle: {
480 followChangeRequestTemplates: defaults.followChangeRequestTemplates,
481 },
482 })
483 }
484 />
485 ) : null
486 }
487 control={
488 <Switch
489 mixed={templatesMixed}
490 checked={templatesMixed ? false : style.followChangeRequestTemplates}
491 onCheckedChange={(checked) =>
492 updateSettings({
493 sourceControlWritingStyle: {
494 followChangeRequestTemplates: Boolean(checked),
495 },
496 })
497 }
498 aria-label="Follow change request templates"
499 />
500 }
501 />
502​
503 <SettingsRow
504 serverScoped
505 settingKeys={["sourceControlWriterModelSelection"]}
506 {...searchableSetting("source-control-writer-model")}
507 description="Model for source control text and branch or bookmark names. Off uses the environment's text generation model."
508 control={
509 !hasServerTargets ? (
510 <span className="text-sm text-muted-foreground">
511 Connect an environment to choose its source control writer model.
512 </span>
513 ) : (
514 <div className="flex flex-wrap items-center justify-end gap-2">
515 {usesDedicatedModel && !canEnableDedicatedModel ? (
516 <span className="text-sm text-muted-foreground">
517 No text generation providers available.
518 </span>
519 ) : null}
520 {usesDedicatedModel && canEnableDedicatedModel ? (
521 <ProviderModelPicker
522 environmentId={environmentId}
523 activeInstanceId={activeSelection.instanceId}
524 model={activeSelection.model}
525 lockedProvider={null}
526 instanceEntries={instanceEntries}
527 modelOptionsByInstance={modelOptionsByInstance}
528 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
529 triggerAriaLabel="Source control writer model"
530 {...(mixedWriterModel ? { triggerLabel: "Mixed" } : {})}
531 {...(environmentId
532 ? {
533 onOpenProviderSetup: (instanceId: ProviderInstanceId) => {
534 void navigate({
535 to: "/settings/providers",
536 search: { environmentId, instanceId },
537 });
538 },
539 }
540 : {})}
541 getModelDisabledReason={writerModelDisabledReason}
542 onInstanceModelChange={(instanceId, model) => {
543 const reason = writerModelDisabledReason(instanceId, model);
544 if (reason) {
545 toastManager.add({
546 type: "error",
547 title: "Source control writer model not saved",
548 description: reason,
549 });
550 return;
551 }
552 updateSettings({
553 sourceControlWriterModelSelection: createModelSelection(instanceId, model),
554 });
555 }}
556 />
557 ) : null}
558 {usesDedicatedModel &&
559 canEnableDedicatedModel &&
560 !mixedWriterModel &&
561 writerInstanceEntry ? (
562 <TraitsPicker
563 provider={writerInstanceEntry.driverKind}
564 models={writerInstanceEntry.models}
565 model={activeSelection.model}
566 modelOptions={activeSelection.options ?? []}
567 allowPromptInjectedEffort={false}
568 planModeEnabled={
569 settings.planModeEnabled || selectsPlanAgent(activeSelection.options)
570 }
571 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
572 onModelOptionsChange={(options) =>
573 updateSettings({
574 sourceControlWriterModelSelection: createModelSelection(
575 activeSelection.instanceId,
576 activeSelection.model,
577 options,
578 ),
579 })
580 }
581 />
582 ) : null}
583 <Switch
584 checked={usesDedicatedModel}
585 disabled={!usesDedicatedModel && !canEnableDedicatedModel}
586 onCheckedChange={(checked) =>
587 updateSettings({
588 sourceControlWriterModelSelection: checked
589 ? createModelSelection(
590 defaultModelSelection.instanceId,
591 defaultModelSelection.model,
592 defaultModelSelection.options,
593 )
594 : null,
595 })
596 }
597 aria-label="Use a separate source control writer model"
598 />
599 </div>
600 )
601 }
602 />
603 </AdvancedSettings>
604 </SettingsSection>
605 );