The best way to control Claude Code, Codex and more from any computer or phone

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