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

SourceControlWritingSettings.tsx

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