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

SourceControlWritingSettings.tsx

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