Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 PROJECT_FILE_BACKED_SETTINGS,
4 type ProjectFileBackedSettingKey,
5 resolveEnvironmentMachineKind,
6 type ServerSettings,
7 type WorktreeSubmodules,
8} from "@t3tools/contracts";
9import { CheckIcon, LayersIcon } from "lucide-react";
10import * as Equal from "effect/Equal";
11
12import { cn } from "../../lib/utils";
13import type { EnvironmentPresentation } from "../../state/environments";
14import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
15import { resolveEnvModeLabel, WORKTREE_SUBMODULES_LABELS } from "../BranchToolbar.logic";
16import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDetail.logic";
17import { Button, InlineButton } from "../ui/button";
18import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
19import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
20import type { ProjectOverrideEntry, ScopedSettingsTarget } from "./scopedSettings";
21import { isProjectScopedSettingKey } from "./scopedSettings";
22
23interface InheritanceLayer {
24 readonly key: "project" | "environment" | "t3.json" | "built-in";
25 readonly label: string;
26 readonly value: string;
27 readonly effective: boolean;
28 readonly set: boolean;
29}
30
31const WRITING_STYLE_LABELS: Record<string, string> = {
32 repo_conventions: "Repository conventions",
33 conventional_commits: "Conventional Commits",
34 custom: "Custom instructions",
35};
36
37/** Human labels for the values the chain can show; falls back to a type summary. */
38function formatValue(key: keyof ServerSettings, value: unknown): string {
39 if (value === null || value === undefined) {
40 return key === "pullRequestMergeMethod"
41 ? "Last selected"
42 : key === "sidebarAutoSettleAfterDays"
43 ? "Never"
44 : key === "defaultModelSelection"
45 ? "Automatic"
46 : key === "sourceControlWriterModelSelection"
47 ? "Text generation model"
48 : key === "defaultThreadEnvMode" || key === "worktreeSubmodules"
49 ? "Inherit"
50 : "Not set";
51 }
52 if (typeof value === "boolean") return value ? "On" : "Off";
53 if (typeof value === "number") {
54 return key === "sidebarAutoSettleAfterDays"
55 ? `${value} ${value === 1 ? "day" : "days"}`
56 : String(value);
57 }
58 if (typeof value === "string") {
59 if (key === "defaultThreadEnvMode" && (value === "local" || value === "worktree")) {
60 return resolveEnvModeLabel(value);
61 }
62 if (key === "worktreeSubmodules" && value in WORKTREE_SUBMODULES_LABELS) {
63 return WORKTREE_SUBMODULES_LABELS[value as WorktreeSubmodules];
64 }
65 if (key === "pullRequestMergeMethod" && value in PULL_REQUEST_MERGE_METHOD_LABELS) {
66 return PULL_REQUEST_MERGE_METHOD_LABELS[
67 value as keyof typeof PULL_REQUEST_MERGE_METHOD_LABELS
68 ];
69 }
70 return value === "" ? "Empty" : value;
71 }
72 if (Array.isArray(value)) return `${value.length} ${value.length === 1 ? "item" : "items"}`;
73 if (typeof value === "object") {
74 if ("model" in value && typeof value.model === "string") return value.model;
75 if ("mode" in value && typeof value.mode === "string") {
76 return WRITING_STYLE_LABELS[value.mode] ?? value.mode;
77 }
78 }
79 return "Custom";
80}
81
82/**
83 * The layers a setting resolves through for one target, top-down: the
84 * project override when the target is a project, the environment's value,
85 * the checkout's t3.json for file-backed keys, and the built-in default. The
86 * first layer that is set wins. Same order as `resolveProjectSettings`.
87 */
88export function settingInheritanceLayers(
89 target: ScopedSettingsTarget,
90 environmentSettings: ServerSettings,
91 key: keyof ServerSettings,
92): readonly InheritanceLayer[] {
93 const environmentValue = environmentSettings[key];
94 const source = isProjectScopedSettingKey(key) ? target.sources[key] : "environment";
95 const environmentSet = !Equal.equals(environmentValue, DEFAULT_SERVER_SETTINGS[key]);
96 const fileBacked = isProjectFileBackedSettingKey(key);
97 const layers: InheritanceLayer[] = [];
98 if (target.projectId !== null && isProjectScopedSettingKey(key)) {
99 layers.push({
100 key: "project",
101 label: "Project",
102 value: source === "project" ? formatValue(key, target.settings[key]) : "Inherits",
103 effective: source === "project",
104 set: source === "project",
105 });
106 }
107 layers.push({
108 key: "environment",
109 label: target.label,
110 value: environmentSet ? formatValue(key, environmentValue) : "Inherits",
111 effective: source === "environment" && environmentSet,
112 set: environmentSet,
113 });
114 if (fileBacked && target.projectId !== null) {
115 layers.push({
116 key: "t3.json",
117 label: "t3.json",
118 value: source === "t3.json" ? formatValue(key, target.settings[key]) : "Inherits",
119 effective: source === "t3.json",
120 set: source === "t3.json",
121 });
122 }
123 // For a file-backed key the built-in is what the resolver produced with
124 // nothing set, not the null the schema decodes to.
125 const builtIn = fileBacked
126 ? PROJECT_FILE_BACKED_SETTINGS[key].builtIn
127 : DEFAULT_SERVER_SETTINGS[key];
128 layers.push({
129 key: "built-in",
130 label: "Default",
131 value: formatValue(key, builtIn),
132 effective: source === "environment" && !environmentSet,
133 set: true,
134 });
135 return layers;
136}
137
138function isProjectFileBackedSettingKey(
139 key: keyof ServerSettings,
140): key is ProjectFileBackedSettingKey {
141 return Object.hasOwn(PROJECT_FILE_BACKED_SETTINGS, key);
142}
143
144export type SettingInheritanceState =
145 | "default"
146 | "environment"
147 | "inherited"
148 | "overridden"
149 | "mixed";
150
151/**
152 * A small indicator beside a row's title that opens a top-down view of where
153 * the setting's value comes from on each selected target. It sits inline so
154 * narrowing to a project does not add a caption line to every row.
155 */
156export interface SettingOverridingProject extends ProjectOverrideEntry {
157 readonly label: string;
158 /** Jumps the breadcrumb to this project so its override can be edited. */
159 readonly open: () => void;
160}
161
162export function SettingInheritance({
163 state,
164 summary,
165 targets,
166 environments,
167 keys,
168 overridingProjects = [],
169 onClearOverrides,
170}: {
171 state: SettingInheritanceState;
172 summary: string;
173 targets: readonly ScopedSettingsTarget[];
174 environments: readonly Pick<EnvironmentPresentation, "environmentId" | "serverConfig">[];
175 keys: readonly (keyof ServerSettings)[];
176 /** At environment scope: projects whose own value hides the environment's. */
177 overridingProjects?: readonly SettingOverridingProject[];
178 onClearOverrides?: (entries: readonly ProjectOverrideEntry[]) => void;
179}) {
180 const key = keys[0];
181 if (!key || targets.length === 0) return null;
182 const overrideSummary =
183 overridingProjects.length > 0
184 ? `${summary} · ${overridingProjects.length} project ${overridingProjects.length === 1 ? "override" : "overrides"}`
185 : summary;
186 const chains = targets.flatMap((target) => {
187 const environment = environments.find(
188 (candidate) => candidate.environmentId === target.environmentId,
189 );
190 if (!environment?.serverConfig) return [];
191 return [
192 {
193 target,
194 environment: { ...environment, serverConfig: environment.serverConfig },
195 machine: resolveEnvironmentMachineKind(environment.serverConfig),
196 layers: settingInheritanceLayers(target, environment.serverConfig.settings, key),
197 },
198 ];
199 });
200 return (
201 <Popover>
202 <Tooltip>
203 <TooltipTrigger
204 render={
205 <PopoverTrigger
206 render={
207 <Button
208 size="icon-micro"
209 variant="ghost-muted"
210 aria-label={`${overrideSummary}. Show where this value comes from`}
211 />
212 }
213 />
214 }
215 >
216 <LayersIcon
217 className={cn(
218 "size-3",
219 state === "overridden" && "text-primary",
220 state === "mixed" && "text-warning",
221 )}
222 />
223 </TooltipTrigger>
224 <TooltipPopup side="top">{overrideSummary}</TooltipPopup>
225 </Tooltip>
226 <PopoverPopup align="start" width="md" padding="none">
227 <div className="divide-y divide-border/60">
228 {chains.map(({ target, environment, machine, layers }) => (
229 <section
230 key={`${target.environmentId}:${target.projectId ?? ""}`}
231 className="px-3 py-2.5"
232 >
233 <h4 className="flex items-center gap-1.5 pb-1.5 text-xs font-medium text-muted-foreground">
234 <EnvironmentMachineIcon aria-hidden kind={machine} className="size-3.5 shrink-0" />
235 <span className="min-w-0 truncate">{target.label}</span>
236 </h4>
237 <ol role="list" className="text-sm">
238 {layers.map((layer) => (
239 <li
240 key={layer.key}
241 className={cn(
242 "grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 rounded-md px-2 py-1",
243 layer.effective && "bg-foreground/[0.06]",
244 )}
245 >
246 <span
247 className={cn(
248 "min-w-0 truncate",
249 layer.effective ? "font-medium text-foreground" : "text-muted-foreground",
250 )}
251 >
252 {layer.key === "environment" ? "Environment" : layer.label}
253 </span>
254 <span
255 className={cn(
256 "flex items-center gap-1.5 tabular-nums",
257 layer.effective
258 ? "text-foreground"
259 : layer.set
260 ? "text-muted-foreground"
261 : "text-muted-foreground/60",
262 )}
263 >
264 <span className="max-w-32 truncate">{layer.value}</span>
265 {layer.effective ? (
266 <CheckIcon aria-hidden className="size-3.5 shrink-0 text-primary" />
267 ) : (
268 <span aria-hidden className="size-3.5 shrink-0" />
269 )}
270 </span>
271 </li>
272 ))}
273 </ol>
274 {(() => {
275 const overriding = overridingProjects.filter(
276 (project) => project.environmentId === target.environmentId,
277 );
278 if (overriding.length === 0) return null;
279 const overrides = environment.serverConfig.settings.projectSettingsOverrides;
280 return (
281 <div className="mt-2 border-t border-border/60 pt-2">
282 <div className="flex items-center justify-between gap-3 px-2 text-xs text-muted-foreground">
283 <span>Overridden by</span>
284 {onClearOverrides ? (
285 <InlineButton onClick={() => onClearOverrides(overriding)}>
286 Reset {overriding.length === 1 ? "it" : "all"}
287 </InlineButton>
288 ) : null}
289 </div>
290 <ul role="list" className="mt-0.5 text-sm">
291 {overriding.map((project) => (
292 <li
293 key={project.projectId}
294 className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 px-2 py-1"
295 >
296 <InlineButton className="min-w-0 justify-start" onClick={project.open}>
297 <span className="truncate">{project.label}</span>
298 </InlineButton>
299 <span className="max-w-32 truncate text-muted-foreground tabular-nums">
300 {isProjectScopedSettingKey(key)
301 ? formatValue(key, overrides[project.projectId]?.[key])
302 : null}
303 </span>
304 </li>
305 ))}
306 </ul>
307 </div>
308 );
309 })()}
310 </section>
311 ))}
312 </div>
313 </PopoverPopup>
314 </Popover>
315 );
316}