feat(settings): resolve t3.json inside the project settings resolver (#12954)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
1262d2f3ab
commit
742173a132
25 files changed
+615
-236
No files matched your search
@@ -50,10 +50,16 @@ const PAGE_PROJECT_KEYS: Record<SettingsPage, readonly ProjectScopedServerSettin
|
||||
};
|
||||
|
||||
const WORKSPACE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: ThreadEnvMode;
|
||||
readonly mode: ThreadEnvMode | null;
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
}> = [
|
||||
// Only offered at environment scope; a project falls back through "Use defaults".
|
||||
{
|
||||
mode: null,
|
||||
label: "Inherit",
|
||||
description: "Use the repository's t3.json, or the current checkout.",
|
||||
},
|
||||
{
|
||||
mode: "local",
|
||||
label: "Current checkout",
|
||||
@@ -126,6 +132,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
|
||||
const value = reference.settings[key];
|
||||
return displayTargets.every((entry) => entry.settings[key] === value) ? value : null;
|
||||
};
|
||||
// `uniform` folds a real null into "mixed"; nullable keys need the distinction.
|
||||
const isMixed = (key: keyof ServerSettings) =>
|
||||
reference === null ||
|
||||
displayTargets.some((entry) => entry.settings[key] !== reference.settings[key]);
|
||||
const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
|
||||
label: "environment settings update",
|
||||
reportFailure: true,
|
||||
@@ -219,17 +229,22 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
|
||||
<SettingsSection
|
||||
title="Default workspace"
|
||||
trailing={
|
||||
pendingWrites === 0 && uniform("defaultThreadEnvMode") === null ? (
|
||||
pendingWrites === 0 && isMixed("defaultThreadEnvMode") ? (
|
||||
<MixedValuesLabel projectSelected={projectSelected} />
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{WORKSPACE_CHOICES.map((choice, index) => (
|
||||
{WORKSPACE_CHOICES.filter(
|
||||
(choice) => choice.mode !== null || !projectSelected,
|
||||
).map((choice, index) => (
|
||||
<ChoiceRow
|
||||
key={choice.mode}
|
||||
key={choice.mode ?? "inherit"}
|
||||
label={choice.label}
|
||||
description={choice.description}
|
||||
selected={uniform("defaultThreadEnvMode") === choice.mode}
|
||||
selected={
|
||||
!isMixed("defaultThreadEnvMode") &&
|
||||
uniform("defaultThreadEnvMode") === choice.mode
|
||||
}
|
||||
separated={index > 0}
|
||||
disabled={disabledFor("defaultThreadEnvMode")}
|
||||
onPress={() => write({ defaultThreadEnvMode: choice.mode })}
|
||||
|
||||
@@ -69,6 +69,39 @@ describe("mobile project settings scope", () => {
|
||||
expect(secondSettings.responseStreamingMode).toBe("token");
|
||||
});
|
||||
|
||||
it("removes a project override when a picker sends null for a key that cannot store it", () => {
|
||||
const settings: ServerSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
projectSettingsOverrides: {
|
||||
[firstProject]: { defaultThreadEnvMode: "worktree", defaultAutoPull: true },
|
||||
},
|
||||
};
|
||||
const targets = resolveMobileSettingsTargets(
|
||||
[environment(firstId, settings)],
|
||||
[{ environmentId: firstId, id: firstProject }],
|
||||
);
|
||||
expect(planMobileScopedSettingsPatch(targets, true, { defaultThreadEnvMode: null })).toEqual([
|
||||
{
|
||||
environmentId: firstId,
|
||||
patch: { projectSettingsOverrides: { [firstProject]: { defaultAutoPull: true } } },
|
||||
},
|
||||
]);
|
||||
expect(planMobileScopedSettingsPatch(targets, true, { defaultModelSelection: null })).toEqual([
|
||||
{
|
||||
environmentId: firstId,
|
||||
patch: {
|
||||
projectSettingsOverrides: {
|
||||
[firstProject]: {
|
||||
defaultThreadEnvMode: "worktree",
|
||||
defaultAutoPull: true,
|
||||
defaultModelSelection: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("resets only the selected page's override and rejects environment-wide writes", () => {
|
||||
const settings: ServerSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
isNullableProjectSettingsOverride,
|
||||
PROJECT_SCOPED_SERVER_SETTING_KEYS,
|
||||
type EnvironmentId,
|
||||
type ProjectId,
|
||||
@@ -69,7 +70,19 @@ export function planMobileScopedSettingsPatch(
|
||||
continue;
|
||||
const current =
|
||||
target.environment.serverConfig.settings.projectSettingsOverrides[target.projectId] ?? {};
|
||||
const next = { ...current, ...patch };
|
||||
const next: Record<string, unknown> = { ...current };
|
||||
for (const [key, value] of Object.entries(patch)) {
|
||||
// A picker's "Inherit" sends null; for keys whose override cannot
|
||||
// store null that means remove the override.
|
||||
if (
|
||||
value === null &&
|
||||
!isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
|
||||
) {
|
||||
delete next[key];
|
||||
} else {
|
||||
next[key] = value;
|
||||
}
|
||||
}
|
||||
const overrides = writes.get(target.environment.environmentId) ?? {};
|
||||
overrides[target.projectId] = next;
|
||||
writes.set(target.environment.environmentId, overrides);
|
||||
|
||||
@@ -20,10 +20,6 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
|
||||
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
|
||||
import {
|
||||
isDefaultThreadEnvModeSettled,
|
||||
resolveDefaultThreadEnvMode,
|
||||
} from "@t3tools/shared/threadEnvMode";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
|
||||
@@ -431,38 +427,35 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
: null,
|
||||
);
|
||||
const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
|
||||
const t3ProjectFileDefaultMode = useMemo(() => {
|
||||
if (t3ProjectFileData === null || t3ProjectFileData.truncated) return null;
|
||||
return parseT3ProjectFile(t3ProjectFileData.contents)?.defaultThreadEnvMode ?? null;
|
||||
}, [t3ProjectFileData]);
|
||||
// Environment settings with the project's overrides applied; the
|
||||
// aggregate's own legacy fields still count until the server folds them.
|
||||
const t3ProjectFile = useMemo(
|
||||
() =>
|
||||
t3ProjectFileData === null || t3ProjectFileData.truncated
|
||||
? null
|
||||
: parseT3ProjectFile(t3ProjectFileData.contents),
|
||||
[t3ProjectFileData],
|
||||
);
|
||||
// Environment settings with the project's overrides and its t3.json
|
||||
// applied; the aggregate's own legacy fields still count until the server
|
||||
// folds them.
|
||||
const projectSettings = useMemo(
|
||||
() =>
|
||||
resolveProjectSettings(
|
||||
selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
|
||||
selectedProject?.id ?? null,
|
||||
selectedProject,
|
||||
t3ProjectFile,
|
||||
),
|
||||
[selectedEnvironmentServerConfig?.settings, selectedProject],
|
||||
[selectedEnvironmentServerConfig?.settings, selectedProject, t3ProjectFile],
|
||||
);
|
||||
const projectThreadEnvMode =
|
||||
projectSettings.sources.defaultThreadEnvMode === "project"
|
||||
? projectSettings.settings.defaultThreadEnvMode
|
||||
: undefined;
|
||||
const defaultWorkspaceMode: WorkspaceMode = resolveDefaultThreadEnvMode({
|
||||
projectSetting: projectThreadEnvMode,
|
||||
projectFile: t3ProjectFileDefaultMode,
|
||||
globalDefault: projectSettings.settings.defaultThreadEnvMode,
|
||||
});
|
||||
// While unsettled the resolved default is provisional. Nothing may write
|
||||
// it into the draft during that window (the auto-branch effect does), or
|
||||
// the frozen interim value beats the t3.json default once it loads.
|
||||
const defaultWorkspaceModeSettled = isDefaultThreadEnvModeSettled({
|
||||
explicitMode: selectedProjectDraft.workspaceSelection?.mode,
|
||||
projectSetting: projectThreadEnvMode,
|
||||
projectFilePending: t3ProjectFileQuery.isPending,
|
||||
});
|
||||
const defaultWorkspaceMode: WorkspaceMode = projectSettings.settings.defaultThreadEnvMode;
|
||||
// While the file read is pending and nothing above it decided, the
|
||||
// resolved default is provisional. Nothing may write it into the draft
|
||||
// during that window (the auto-branch effect does), or the frozen interim
|
||||
// value beats the t3.json default once it loads.
|
||||
const defaultWorkspaceModeSettled =
|
||||
selectedProjectDraft.workspaceSelection?.mode !== undefined ||
|
||||
projectSettings.sources.defaultThreadEnvMode !== "environment" ||
|
||||
!t3ProjectFileQuery.isPending;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
|
||||
@@ -20,7 +20,12 @@ const EMPTY_PROJECT_FILE_PATH = "";
|
||||
const EMPTY_PROJECT_FILE_QUERY_ATOM = Atom.make(
|
||||
AsyncResult.initial<ProjectReadFileResult, never>(false),
|
||||
).pipe(Atom.withLabel("project-file-query:empty"));
|
||||
function optimisticFileAtom(environmentId: EnvironmentId, cwd: string, relativePath: string) {
|
||||
/** A pending in-app write to the file, overlaying the query until confirmed. */
|
||||
export function optimisticFileAtom(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
) {
|
||||
return projectEnvironment.optimisticFile({ environmentId, cwd, relativePath });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts";
|
||||
import { getCustomModelOptionsByInstance } from "../../modelSelection";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
@@ -75,25 +74,16 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting
|
||||
const mixedAutoPull = useScopedSettingsMixed(["defaultAutoPull"]);
|
||||
const mixedMergeMethod = useScopedSettingsMixed(["pullRequestMergeMethod"]);
|
||||
const modelSource = useScopedSettingSource(["defaultModelSelection"]);
|
||||
const workspaceSource = useScopedSettingSource(["defaultThreadEnvMode"]);
|
||||
const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
|
||||
const unavailable = connectedEnvironments.length === 0;
|
||||
|
||||
// A checkout's t3.json wins over the environment default when the project
|
||||
// has no override of its own; show which one "inherit" resolves to.
|
||||
const checkout = scope.kind === "checkout" ? scope.checkout : null;
|
||||
// The query is disabled without a checkout, so any id satisfies the hook.
|
||||
const t3File = useT3ProjectFileState(
|
||||
checkout?.environmentId ?? EnvironmentId.make("none"),
|
||||
category === "general" && checkout ? checkout.workspaceRoot : null,
|
||||
);
|
||||
const repositoryEnvMode = t3File.file?.defaultThreadEnvMode ?? null;
|
||||
const inheritedEnvModeLabel =
|
||||
workspaceSource === "project"
|
||||
? null
|
||||
: repositoryEnvMode
|
||||
? `${resolveEnvModeLabel(repositoryEnvMode)} (t3.json)`
|
||||
: null;
|
||||
// File-backed keys show their effective value; the target already carries
|
||||
// the checkout's t3.json, and a null file here only fills the built-in.
|
||||
// The reset arrow beside the title clears the tier (SettingsRow handles a
|
||||
// project override, the environment value is cleared here), so the picker
|
||||
// has no "inherit" item.
|
||||
const effective = target
|
||||
? resolveProjectSettings(target.settings, null, null, null).settings
|
||||
: null;
|
||||
|
||||
function modelDisabledReason(instanceId: ProviderInstanceId, model: string): string | null {
|
||||
const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
|
||||
@@ -292,27 +282,20 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting
|
||||
title="Workspace"
|
||||
description={
|
||||
isProjectScope
|
||||
? "Where new threads in this project start. A t3.json preference applies when the project has no override."
|
||||
: "Where new threads start, unless overridden by the project or t3.json."
|
||||
}
|
||||
status={
|
||||
inheritedEnvModeLabel ? `Repository default: ${inheritedEnvModeLabel}` : undefined
|
||||
? "Where new threads in this project start."
|
||||
: "Where new threads start. Projects and their t3.json can override it."
|
||||
}
|
||||
resetAction={
|
||||
settings.defaultThreadEnvMode !== DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode ? (
|
||||
!isProjectScope && settings.defaultThreadEnvMode !== null ? (
|
||||
<SettingResetButton
|
||||
label="default workspace"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
defaultThreadEnvMode: DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode,
|
||||
})
|
||||
}
|
||||
onClick={() => updateSettings({ defaultThreadEnvMode: null })}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={mixedWorkspace ? null : settings.defaultThreadEnvMode}
|
||||
value={mixedWorkspace ? null : (effective?.defaultThreadEnvMode ?? null)}
|
||||
onValueChange={(value) => {
|
||||
if (value === "local" || value === "worktree")
|
||||
updateSettings({ defaultThreadEnvMode: value });
|
||||
|
||||
@@ -54,4 +54,41 @@ describe("settingInheritanceLayers", () => {
|
||||
["Off", false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows the checkout's t3.json as a layer for file-backed keys", () => {
|
||||
const file = { defaultThreadEnvMode: "worktree" as const };
|
||||
const fromFile = settingInheritanceLayers(
|
||||
{
|
||||
environmentId,
|
||||
label: "Laptop",
|
||||
projectId,
|
||||
...resolveProjectSettings(DEFAULT_SERVER_SETTINGS, projectId, null, file),
|
||||
},
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
"defaultThreadEnvMode",
|
||||
);
|
||||
expect(fromFile.map((layer) => [layer.label, layer.value, layer.effective])).toEqual([
|
||||
["Project", "Inherits", false],
|
||||
["Laptop", "Inherits", false],
|
||||
["t3.json", "New worktree", true],
|
||||
["Default", "Current checkout", false],
|
||||
]);
|
||||
const settings = { ...DEFAULT_SERVER_SETTINGS, defaultThreadEnvMode: "local" as const };
|
||||
const fromEnvironment = settingInheritanceLayers(
|
||||
{
|
||||
environmentId,
|
||||
label: "Laptop",
|
||||
projectId,
|
||||
...resolveProjectSettings(settings, projectId, null, file),
|
||||
},
|
||||
settings,
|
||||
"defaultThreadEnvMode",
|
||||
);
|
||||
expect(fromEnvironment.map((layer) => [layer.value, layer.effective])).toEqual([
|
||||
["Inherits", false],
|
||||
["Current checkout", true],
|
||||
["Inherits", false],
|
||||
["Current checkout", false],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
PROJECT_FILE_BACKED_SETTINGS,
|
||||
type ProjectFileBackedSettingKey,
|
||||
resolveEnvironmentMachineKind,
|
||||
type ServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -18,7 +20,7 @@ import type { ProjectOverrideEntry, ScopedSettingsTarget } from "./scopedSetting
|
||||
import { isProjectScopedSettingKey } from "./scopedSettings";
|
||||
|
||||
interface InheritanceLayer {
|
||||
readonly key: "project" | "environment" | "built-in";
|
||||
readonly key: "project" | "environment" | "t3.json" | "built-in";
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly effective: boolean;
|
||||
@@ -42,7 +44,9 @@ function formatValue(key: keyof ServerSettings, value: unknown): string {
|
||||
? "Automatic"
|
||||
: key === "sourceControlWriterModelSelection"
|
||||
? "Text generation model"
|
||||
: "Not set";
|
||||
: key === "defaultThreadEnvMode"
|
||||
? "Inherit"
|
||||
: "Not set";
|
||||
}
|
||||
if (typeof value === "boolean") return value ? "On" : "Off";
|
||||
if (typeof value === "number") {
|
||||
@@ -74,44 +78,65 @@ function formatValue(key: keyof ServerSettings, value: unknown): string {
|
||||
/**
|
||||
* The layers a setting resolves through for one target, top-down: the
|
||||
* project override when the target is a project, the environment's value,
|
||||
* and the built-in default. The first layer that is set wins.
|
||||
* the checkout's t3.json for file-backed keys, and the built-in default. The
|
||||
* first layer that is set wins. Same order as `resolveProjectSettings`.
|
||||
*/
|
||||
export function settingInheritanceLayers(
|
||||
target: ScopedSettingsTarget,
|
||||
environmentSettings: ServerSettings,
|
||||
key: keyof ServerSettings,
|
||||
): readonly InheritanceLayer[] {
|
||||
const builtIn = DEFAULT_SERVER_SETTINGS[key];
|
||||
const environmentValue = environmentSettings[key];
|
||||
const projectSource = isProjectScopedSettingKey(key) ? target.sources[key] : "environment";
|
||||
const environmentSet = !Equal.equals(environmentValue, builtIn);
|
||||
const source = isProjectScopedSettingKey(key) ? target.sources[key] : "environment";
|
||||
const environmentSet = !Equal.equals(environmentValue, DEFAULT_SERVER_SETTINGS[key]);
|
||||
const fileBacked = isProjectFileBackedSettingKey(key);
|
||||
const layers: InheritanceLayer[] = [];
|
||||
if (target.projectId !== null && isProjectScopedSettingKey(key)) {
|
||||
layers.push({
|
||||
key: "project",
|
||||
label: "Project",
|
||||
value: projectSource === "project" ? formatValue(key, target.settings[key]) : "Inherits",
|
||||
effective: projectSource === "project",
|
||||
set: projectSource === "project",
|
||||
value: source === "project" ? formatValue(key, target.settings[key]) : "Inherits",
|
||||
effective: source === "project",
|
||||
set: source === "project",
|
||||
});
|
||||
}
|
||||
layers.push({
|
||||
key: "environment",
|
||||
label: target.label,
|
||||
value: environmentSet ? formatValue(key, environmentValue) : "Inherits",
|
||||
effective: projectSource !== "project" && environmentSet,
|
||||
effective: source === "environment" && environmentSet,
|
||||
set: environmentSet,
|
||||
});
|
||||
if (fileBacked && target.projectId !== null) {
|
||||
layers.push({
|
||||
key: "t3.json",
|
||||
label: "t3.json",
|
||||
value: source === "t3.json" ? formatValue(key, target.settings[key]) : "Inherits",
|
||||
effective: source === "t3.json",
|
||||
set: source === "t3.json",
|
||||
});
|
||||
}
|
||||
// For a file-backed key the built-in is what the resolver produced with
|
||||
// nothing set, not the null the schema decodes to.
|
||||
const builtIn = fileBacked
|
||||
? PROJECT_FILE_BACKED_SETTINGS[key].builtIn
|
||||
: DEFAULT_SERVER_SETTINGS[key];
|
||||
layers.push({
|
||||
key: "built-in",
|
||||
label: "Default",
|
||||
value: formatValue(key, builtIn),
|
||||
effective: projectSource !== "project" && !environmentSet,
|
||||
effective: source === "environment" && !environmentSet,
|
||||
set: true,
|
||||
});
|
||||
return layers;
|
||||
}
|
||||
|
||||
function isProjectFileBackedSettingKey(
|
||||
key: keyof ServerSettings,
|
||||
): key is ProjectFileBackedSettingKey {
|
||||
return Object.hasOwn(PROJECT_FILE_BACKED_SETTINGS, key);
|
||||
}
|
||||
|
||||
export type SettingInheritanceState =
|
||||
| "default"
|
||||
| "environment"
|
||||
|
||||
@@ -1,22 +1,78 @@
|
||||
import { T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts";
|
||||
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { createContext, type ReactNode, useContext, useMemo } from "react";
|
||||
|
||||
import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
|
||||
import { getProjectFileQueryAtom, optimisticFileAtom } from "../files/projectFilesQueryState";
|
||||
import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
|
||||
import { resolveScopedSettingsTargets, selectScopedSettingsEnvironments } from "./scopedSettings";
|
||||
import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
|
||||
|
||||
/**
|
||||
* Each member's decoded t3.json, so file-backed settings show the file as a
|
||||
* layer in the inheritance chain. A member is only present once its read has
|
||||
* settled; the query atom caches per (environment, cwd).
|
||||
*/
|
||||
function useMemberProjectFiles(scope: ReturnType<typeof resolveSettingsScope>) {
|
||||
const members = scope.kind === "project" || scope.kind === "checkout" ? scope.members : [];
|
||||
return useAtomValue(
|
||||
useMemo(
|
||||
() =>
|
||||
Atom.make((get) => {
|
||||
const files = new Map<string, T3ProjectFile | null>();
|
||||
for (const member of members) {
|
||||
const result = get(
|
||||
getProjectFileQueryAtom(
|
||||
member.environmentId,
|
||||
member.workspaceRoot,
|
||||
T3_PROJECT_FILE_NAME,
|
||||
),
|
||||
);
|
||||
if (result.waiting) continue;
|
||||
// A pending in-app save overlays the query, like useProjectFileQuery.
|
||||
const data =
|
||||
get(
|
||||
optimisticFileAtom(
|
||||
member.environmentId,
|
||||
member.workspaceRoot,
|
||||
T3_PROJECT_FILE_NAME,
|
||||
),
|
||||
)?.data ?? Option.getOrNull(AsyncResult.value(result));
|
||||
files.set(
|
||||
member.physicalProjectKey,
|
||||
data === null || data.truncated ? null : parseT3ProjectFile(data.contents),
|
||||
);
|
||||
}
|
||||
return files;
|
||||
}),
|
||||
[members],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function useResolvedSettingsScope(search: SettingsScopeSearch) {
|
||||
const groups = useSettingsProjectGroups();
|
||||
const { environments: availableEnvironments } = useEnvironments();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const scope = useMemo(
|
||||
() => resolveSettingsScope(search, groups, availableEnvironments),
|
||||
[availableEnvironments, groups, search],
|
||||
);
|
||||
const projectFiles = useMemberProjectFiles(scope);
|
||||
return useMemo(() => {
|
||||
const scope = resolveSettingsScope(search, groups, availableEnvironments);
|
||||
const selected = selectScopedSettingsEnvironments(
|
||||
scope,
|
||||
availableEnvironments,
|
||||
primaryEnvironmentId,
|
||||
);
|
||||
const targets = resolveScopedSettingsTargets(scope, selected.connectedEnvironments);
|
||||
const targets = resolveScopedSettingsTargets(
|
||||
scope,
|
||||
selected.connectedEnvironments,
|
||||
projectFiles,
|
||||
);
|
||||
// The representative target supplies display values; project scopes
|
||||
// prefer the member on the primary environment, like environments do.
|
||||
const target =
|
||||
@@ -26,7 +82,7 @@ function useResolvedSettingsScope(search: SettingsScopeSearch) {
|
||||
targets[0] ??
|
||||
null;
|
||||
return { scope, groups, ...selected, targets, target };
|
||||
}, [availableEnvironments, groups, primaryEnvironmentId, search]);
|
||||
}, [availableEnvironments, groups, primaryEnvironmentId, projectFiles, scope]);
|
||||
}
|
||||
|
||||
const SettingsScopeContext = createContext<
|
||||
|
||||
@@ -510,6 +510,53 @@ describe("project overrides at environment scope", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("null patches at project scope", () => {
|
||||
it("removes the override for keys that cannot store null and keeps it for keys that can", () => {
|
||||
const environmentId = EnvironmentId.make("laptop");
|
||||
const projectId = ProjectId.make("fleet");
|
||||
const scope = {
|
||||
kind: "project" as const,
|
||||
group: {} as never,
|
||||
environmentId: null,
|
||||
label: "fleet",
|
||||
members: [{ id: projectId, environmentId } as never],
|
||||
environmentIds: [environmentId],
|
||||
};
|
||||
const environments = [
|
||||
{
|
||||
environmentId,
|
||||
label: "Laptop",
|
||||
connection: { phase: "connected" as const },
|
||||
serverConfig: {
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
projectSettingsOverrides: {
|
||||
[projectId]: { defaultThreadEnvMode: "worktree" as const, defaultAutoPull: true },
|
||||
},
|
||||
},
|
||||
environment: { capabilities: { projectSettingsOverrides: true } },
|
||||
},
|
||||
},
|
||||
];
|
||||
expect(
|
||||
planScopedSettingsPatch(scope, environments, { defaultThreadEnvMode: null }).serverWrites[0]
|
||||
?.patch,
|
||||
).toEqual({ projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } } });
|
||||
expect(
|
||||
planScopedSettingsPatch(scope, environments, { defaultModelSelection: null }).serverWrites[0]
|
||||
?.patch,
|
||||
).toEqual({
|
||||
projectSettingsOverrides: {
|
||||
[projectId]: {
|
||||
defaultThreadEnvMode: "worktree",
|
||||
defaultAutoPull: true,
|
||||
defaultModelSelection: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("partial object patches at project scope", () => {
|
||||
it("completes a writing style field patch from the target's effective value", () => {
|
||||
const environmentId = EnvironmentId.make("laptop");
|
||||
|
||||
@@ -2,11 +2,13 @@ import {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettingsPatch,
|
||||
type EnvironmentId,
|
||||
isNullableProjectSettingsOverride,
|
||||
PROJECT_SCOPED_SERVER_SETTING_KEYS,
|
||||
type ProjectId,
|
||||
type ProjectScopedServerSettingKey,
|
||||
type ProjectSettingsOverrides,
|
||||
ServerSettings,
|
||||
type T3ProjectFile,
|
||||
type ServerSettingsPatch,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
@@ -85,6 +87,9 @@ export interface ScopedSettingsTarget {
|
||||
export function resolveScopedSettingsTargets(
|
||||
scope: ResolvedSettingsScope,
|
||||
connectedEnvironments: readonly ScopedSettingsEnvironment[],
|
||||
// Each member's decoded t3.json, keyed by physical project key, once read.
|
||||
// A member absent here has no file tier yet; null is a missing or invalid file.
|
||||
projectFiles?: ReadonlyMap<string, T3ProjectFile | null>,
|
||||
): readonly ScopedSettingsTarget[] {
|
||||
const byId = new Map(
|
||||
connectedEnvironments.map((environment) => [environment.environmentId, environment]),
|
||||
@@ -93,7 +98,11 @@ export function resolveScopedSettingsTargets(
|
||||
return scope.members.flatMap((member) => {
|
||||
const environment = byId.get(member.environmentId);
|
||||
if (!environment?.serverConfig) return [];
|
||||
const resolved = resolveProjectSettings(environment.serverConfig.settings, member.id);
|
||||
const projectFile = projectFiles?.get(member.physicalProjectKey);
|
||||
const resolved =
|
||||
projectFile === undefined
|
||||
? resolveProjectSettings(environment.serverConfig.settings, member.id)
|
||||
: resolveProjectSettings(environment.serverConfig.settings, member.id, null, projectFile);
|
||||
return [
|
||||
{
|
||||
environmentId: member.environmentId,
|
||||
@@ -143,7 +152,13 @@ export function scopedSettingsSource(
|
||||
const scoped = keys.filter(isProjectScopedSettingKey);
|
||||
if (scoped.length === 0 || targets.length === 0) return "environment";
|
||||
const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
|
||||
return sources.size > 1 ? "mixed" : sources.has("project") ? "project" : "environment";
|
||||
return sources.size > 1
|
||||
? "mixed"
|
||||
: sources.has("project")
|
||||
? "project"
|
||||
: sources.has("t3.json")
|
||||
? "t3.json"
|
||||
: "environment";
|
||||
}
|
||||
|
||||
interface ScopedServerWrite {
|
||||
@@ -234,6 +249,15 @@ export function planScopedSettingsPatch(
|
||||
};
|
||||
continue;
|
||||
}
|
||||
// A picker's "Inherit" sends null; for keys whose override
|
||||
// cannot store null that means remove the override.
|
||||
if (
|
||||
value === null &&
|
||||
!isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
|
||||
) {
|
||||
delete next[key];
|
||||
continue;
|
||||
}
|
||||
const base = effective[key as keyof ServerSettings];
|
||||
next[key] =
|
||||
isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
|
||||
|
||||
@@ -407,11 +407,13 @@ export function SettingsRow({
|
||||
? { state: "mixed", summary: "Mixed across selected environments" }
|
||||
: source === "project"
|
||||
? { state: "overridden", summary: "Overridden for this project" }
|
||||
: source === "environment" && scopedKeys.length > 0
|
||||
? { state: "inherited", summary: `Inherited from ${inheritedFrom}` }
|
||||
: customized
|
||||
? { state: "environment", summary: "Set on the environment" }
|
||||
: { state: "default", summary: "Built-in default" };
|
||||
: source === "t3.json"
|
||||
? { state: "inherited", summary: "Inherited from the repository's t3.json" }
|
||||
: source === "environment" && scopedKeys.length > 0
|
||||
? { state: "inherited", summary: `Inherited from ${inheritedFrom}` }
|
||||
: customized
|
||||
? { state: "environment", summary: "Set on the environment" }
|
||||
: { state: "default", summary: "Built-in default" };
|
||||
const renderedInheritance =
|
||||
context && serverScoped && settingKeys.length > 0 ? (
|
||||
<SettingInheritance
|
||||
|
||||
@@ -100,18 +100,25 @@ vi.mock("@t3tools/contracts", () => ({
|
||||
vi.mock("@t3tools/shared/projectSettings", () => ({
|
||||
// Environment settings pass through; the tests set project fields on the
|
||||
// project record, which the hook still honors until the server folds them.
|
||||
resolveProjectSettings: (settings: Record<string, unknown>) => ({
|
||||
settings,
|
||||
// With a file argument the env mode resolves like the real chain.
|
||||
resolveProjectSettings: (
|
||||
settings: Record<string, unknown>,
|
||||
_projectId: unknown,
|
||||
_project: unknown,
|
||||
projectFile?: { defaultThreadEnvMode?: "local" | "worktree" } | null,
|
||||
) => ({
|
||||
settings:
|
||||
projectFile === undefined
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
defaultThreadEnvMode:
|
||||
settings.defaultThreadEnvMode ?? projectFile?.defaultThreadEnvMode ?? "local",
|
||||
},
|
||||
sources: { defaultModelSelection: "environment", defaultThreadEnvMode: "environment" },
|
||||
overrides: {},
|
||||
}),
|
||||
}));
|
||||
vi.mock("@t3tools/shared/threadEnvMode", () => ({
|
||||
resolveDefaultThreadEnvMode: (input: {
|
||||
readonly projectFile: "local" | "worktree" | null;
|
||||
readonly globalDefault: "local" | "worktree";
|
||||
}) => input.projectFile ?? input.globalDefault,
|
||||
}));
|
||||
vi.mock("@tanstack/react-router", () => ({
|
||||
useParams: () => null,
|
||||
useRouter: () => testState.router,
|
||||
@@ -137,7 +144,7 @@ vi.mock("../lib/chatThreadActions", async (importOriginal) => ({
|
||||
resolveNewThreadModelSelectionOverride: () => null,
|
||||
}));
|
||||
vi.mock("../lib/t3ProjectFileDefaults", () => ({
|
||||
readT3ProjectFileDefaultThreadEnvMode: () => testState.projectFileRead,
|
||||
readT3ProjectFile: () => testState.projectFileRead,
|
||||
}));
|
||||
vi.mock("../lib/utils", () => ({
|
||||
newDraftId: () => "draft-delayed",
|
||||
|
||||
@@ -23,14 +23,13 @@ import {
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
|
||||
import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode";
|
||||
import { readProjects, readThreadShell, useProjects, useThread } from "../state/entities";
|
||||
import {
|
||||
hasExplicitComposerModelSelection,
|
||||
resolveNewDraftStartFromOrigin,
|
||||
resolveNewThreadModelSelectionOverride,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { readT3ProjectFileDefaultThreadEnvMode } from "../lib/t3ProjectFileDefaults";
|
||||
import { readT3ProjectFile } from "../lib/t3ProjectFileDefaults";
|
||||
import { environmentServerConfigsAtom } from "../state/server";
|
||||
import { resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
|
||||
@@ -138,10 +137,6 @@ export function useNewThreadHandler() {
|
||||
);
|
||||
const projectDefaultModelSelection = projectSettings.settings.defaultModelSelection;
|
||||
const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode;
|
||||
const projectThreadEnvMode =
|
||||
projectSettings.sources.defaultThreadEnvMode === "project"
|
||||
? projectSettings.settings.defaultThreadEnvMode
|
||||
: undefined;
|
||||
const resolveModelSelectionOverride = (destinationDraftId: DraftId) =>
|
||||
resolveNewThreadModelSelectionOverride({
|
||||
projectDefaultSelection: projectDefaultModelSelection ?? null,
|
||||
@@ -154,17 +149,17 @@ export function useNewThreadHandler() {
|
||||
// skipped entirely when a higher-priority source decides, and its
|
||||
// query atom caches per project after the first call.
|
||||
const resolveDefaultEnvMode = async (): Promise<DraftThreadEnvMode> => {
|
||||
const consultProjectFile = project !== undefined && projectThreadEnvMode == null;
|
||||
return resolveDefaultThreadEnvMode({
|
||||
projectSetting: projectThreadEnvMode,
|
||||
projectFile: consultProjectFile
|
||||
? await readT3ProjectFileDefaultThreadEnvMode(
|
||||
project.environmentId,
|
||||
project.workspaceRoot,
|
||||
)
|
||||
: null,
|
||||
globalDefault: projectSettings.settings.defaultThreadEnvMode,
|
||||
});
|
||||
const consultProjectFile =
|
||||
project !== undefined && projectSettings.settings.defaultThreadEnvMode === null;
|
||||
const projectFile = consultProjectFile
|
||||
? await readT3ProjectFile(project.environmentId, project.workspaceRoot)
|
||||
: null;
|
||||
return resolveProjectSettings(
|
||||
targetServerSettings,
|
||||
project?.id ?? null,
|
||||
project,
|
||||
projectFile,
|
||||
).settings.defaultThreadEnvMode;
|
||||
};
|
||||
const logicalProjectKey = project
|
||||
? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { T3_PROJECT_FILE_NAME, type EnvironmentId, type ThreadEnvMode } from "@t3tools/contracts";
|
||||
import { T3_PROJECT_FILE_NAME, type EnvironmentId, type T3ProjectFile } from "@t3tools/contracts";
|
||||
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
|
||||
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
@@ -9,19 +9,19 @@ import {
|
||||
import { appAtomRegistry } from "~/rpc/atomRegistry";
|
||||
|
||||
/**
|
||||
* Read `defaultThreadEnvMode` from the project's checked-in `t3.json`.
|
||||
* Read and decode the project's checked-in `t3.json`.
|
||||
*
|
||||
* Imperative counterpart to `useT3ProjectFileScripts` for the new-thread
|
||||
* path, which resolves defaults at call time rather than render time. The
|
||||
* file query atom caches per (environment, cwd), so repeat calls don't
|
||||
* re-fetch. Optimistic in-app writes overlay the query result, matching what
|
||||
* Imperative counterpart to `useT3ProjectFileState` for the new-thread path,
|
||||
* which resolves defaults at call time rather than render time. The file
|
||||
* query atom caches per (environment, cwd), so repeat calls don't re-fetch.
|
||||
* Optimistic in-app writes overlay the query result, matching what
|
||||
* `useProjectFileQuery` renders. Missing, truncated, or invalid files
|
||||
* resolve to null.
|
||||
*/
|
||||
export async function readT3ProjectFileDefaultThreadEnvMode(
|
||||
export async function readT3ProjectFile(
|
||||
environmentId: EnvironmentId,
|
||||
workspaceRoot: string,
|
||||
): Promise<ThreadEnvMode | null> {
|
||||
): Promise<T3ProjectFile | null> {
|
||||
const result = await executeAtomQuery(
|
||||
appAtomRegistry,
|
||||
getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME),
|
||||
@@ -34,5 +34,5 @@ export async function readT3ProjectFileDefaultThreadEnvMode(
|
||||
result._tag === "Success" ? result.value : null,
|
||||
);
|
||||
if (data === null || data.truncated) return null;
|
||||
return parseT3ProjectFile(data.contents)?.defaultThreadEnvMode ?? null;
|
||||
return parseT3ProjectFile(data.contents);
|
||||
}
|
||||
@@ -49,7 +49,9 @@ checkouts and removal. Actions belong to a project: editing them creates the pro
|
||||
on each selected environment, and reset returns to the environment's shared list. A project's
|
||||
`t3.json` actions can be imported there.
|
||||
|
||||
For workspace mode, a project's `t3.json` preference applies when the project has no override.
|
||||
Settings a repository can also declare in `t3.json`, such as the workspace for new threads,
|
||||
resolve in one order: a project override, then the environment setting, then `t3.json`, then the
|
||||
built-in default. Leave a setting on **Inherit** to let the next tier decide.
|
||||
Browser access changes apply when an agent session next starts.
|
||||
|
||||
New worktrees initialize git submodules recursively. If that step is slow because the repository
|
||||
|
||||
@@ -82,6 +82,31 @@ export const ForwardCompatibleNullable = <Value extends Schema.Top>(value: Value
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* A nullable setting whose null is "unset" and never crosses the wire: it
|
||||
* decodes from a missing or unknown key and encodes back to a missing key.
|
||||
* For a field that older clients decode as a required literal, so a null
|
||||
* on the wire would fail their whole settings snapshot.
|
||||
*/
|
||||
export const OmittedWhenNull = <Value extends Schema.Top>(value: Value) => {
|
||||
const decodeValue = Schema.decodeUnknownOption(value as never);
|
||||
return Schema.optionalKey(Schema.Unknown).pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.NullOr(value),
|
||||
SchemaTransformation.transformOptional<Value["Encoded"] | null, unknown>({
|
||||
decode: (raw) =>
|
||||
Option.some(
|
||||
Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
|
||||
? (raw.value as Value["Encoded"])
|
||||
: null,
|
||||
),
|
||||
encode: (raw) =>
|
||||
Option.isSome(raw) && raw.value !== null ? Option.some(raw.value) : Option.none(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const ForwardCompatibleArray = <Element extends Schema.Top>(element: Element) => {
|
||||
const decodeElement = Schema.decodeUnknownOption(element as never);
|
||||
return Schema.Array(Schema.Unknown).pipe(
|
||||
|
||||
@@ -805,6 +805,27 @@ describe("provider enabled defaults", () => {
|
||||
});
|
||||
|
||||
describe("ServerSettings worktree defaults", () => {
|
||||
it("defaults the thread env mode to inherit and keeps stored values", () => {
|
||||
expect(decodeServerSettings({}).defaultThreadEnvMode).toBeNull();
|
||||
expect(decodeServerSettings({ defaultThreadEnvMode: "worktree" }).defaultThreadEnvMode).toBe(
|
||||
"worktree",
|
||||
);
|
||||
expect(
|
||||
decodeServerSettings({ defaultThreadEnvMode: "remote" }).defaultThreadEnvMode,
|
||||
).toBeNull();
|
||||
expect(
|
||||
decodeServerSettingsPatch({ defaultThreadEnvMode: null }).defaultThreadEnvMode,
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps an inherited thread env mode off the wire for older clients", () => {
|
||||
const encode = Schema.encodeSync(ServerSettings);
|
||||
expect("defaultThreadEnvMode" in encode(decodeServerSettings({}))).toBe(false);
|
||||
expect(
|
||||
encode(decodeServerSettings({ defaultThreadEnvMode: "worktree" })).defaultThreadEnvMode,
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("defaults start-from-origin on for legacy configs", () => {
|
||||
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as SchemaTransformation from "effect/SchemaTransformation";
|
||||
import {
|
||||
ForwardCompatibleNullable,
|
||||
OmittedWhenNull,
|
||||
ProjectId,
|
||||
TrimmedNonEmptyString,
|
||||
TrimmedString,
|
||||
@@ -1041,6 +1042,26 @@ export const ProjectSettingsOverrides = Schema.Struct({
|
||||
} satisfies Record<ProjectScopedServerSettingKey, unknown>);
|
||||
export type ProjectSettingsOverrides = typeof ProjectSettingsOverrides.Type;
|
||||
|
||||
/**
|
||||
* Whether `null` is a stored override value for this key rather than "unset".
|
||||
* Clients writing a project override treat null for every other key as a
|
||||
* request to remove the override, so a picker's "Inherit" item and the row's
|
||||
* reset do the same thing.
|
||||
*/
|
||||
export function isNullableProjectSettingsOverride(key: ProjectScopedServerSettingKey): boolean {
|
||||
return NULLABLE_PROJECT_SETTINGS_OVERRIDES.has(key);
|
||||
}
|
||||
const NULLABLE_PROJECT_SETTINGS_OVERRIDES: ReadonlySet<ProjectScopedServerSettingKey> = new Set<
|
||||
{
|
||||
[K in ProjectScopedServerSettingKey]: null extends ProjectSettingsOverrides[K] ? K : never;
|
||||
}[ProjectScopedServerSettingKey]
|
||||
>([
|
||||
"defaultModelSelection",
|
||||
"sourceControlWriterModelSelection",
|
||||
"pullRequestMergeMethod",
|
||||
"sidebarAutoSettleAfterDays",
|
||||
]);
|
||||
|
||||
export const StorageCleanupSettings = Schema.Struct({
|
||||
worktreeAfterDays: StorageRetentionDays.pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
worktreeOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
@@ -1176,9 +1197,14 @@ export const ServerSettings = Schema.Struct({
|
||||
environmentIcon: ForwardCompatibleNullable(EnvironmentMachineKind).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
defaultThreadEnvMode: ThreadEnvMode.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
|
||||
),
|
||||
/**
|
||||
* Null means inherit: the repository's t3.json, then "local". The old
|
||||
* default "local" was never persisted (defaults are stripped on write), so
|
||||
* it now decodes as inherit, which resolves the same way because the old
|
||||
* chain also let t3.json outrank the environment. Null stays off the wire
|
||||
* so older clients, which require a literal here, keep decoding.
|
||||
*/
|
||||
defaultThreadEnvMode: OmittedWhenNull(ThreadEnvMode),
|
||||
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
),
|
||||
@@ -1471,7 +1497,7 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
|
||||
environmentIcon: Schema.optionalKey(Schema.NullOr(EnvironmentMachineKind)),
|
||||
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
|
||||
defaultThreadEnvMode: Schema.optionalKey(Schema.NullOr(ThreadEnvMode)),
|
||||
newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
|
||||
addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
|
||||
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as SchemaTransformation from "effect/SchemaTransformation";
|
||||
|
||||
import { ThreadEnvMode, WorktreeSubmodules } from "./environment.ts";
|
||||
import { ProjectScriptIcon } from "./orchestration.ts";
|
||||
import type { ProjectScopedServerSettingKey, ServerSettings } from "./settings.ts";
|
||||
|
||||
/** File name of the checked-in T3 project file, resolved at the workspace root. */
|
||||
export const T3_PROJECT_FILE_NAME = "t3.json";
|
||||
@@ -105,3 +106,37 @@ export const T3ProjectFile = Schema.Struct({
|
||||
"Checked-in project configuration for T3 Code (t3.json at the repository root). See https://t3.codes for documentation.",
|
||||
});
|
||||
export type T3ProjectFile = typeof T3ProjectFile.Type;
|
||||
|
||||
/**
|
||||
* Settings a repository can also declare in t3.json. A key here must be
|
||||
* nullable on `ServerSettings` (null means inherit) so both the project
|
||||
* override and the environment value can defer to the file; `field` names
|
||||
* the t3.json field carrying the same value and `builtIn` is what applies
|
||||
* when every tier is unset. `resolveProjectSettings` walks project override,
|
||||
* environment value, file, built-in, so listing a key here is the whole
|
||||
* change for a new file-backed setting.
|
||||
*/
|
||||
export const PROJECT_FILE_BACKED_SETTINGS = {
|
||||
defaultThreadEnvMode: { field: "defaultThreadEnvMode", builtIn: "local" },
|
||||
} as const satisfies {
|
||||
readonly [K in ProjectScopedServerSettingKey]?: {
|
||||
readonly field: {
|
||||
readonly [F in keyof T3ProjectFile]: T3ProjectFile[F] extends
|
||||
| Exclude<ServerSettings[K], null>
|
||||
| undefined
|
||||
? F
|
||||
: never;
|
||||
}[keyof T3ProjectFile];
|
||||
readonly builtIn: Exclude<ServerSettings[K], null>;
|
||||
};
|
||||
};
|
||||
export type ProjectFileBackedSettingKey = keyof typeof PROJECT_FILE_BACKED_SETTINGS;
|
||||
|
||||
/**
|
||||
* `ServerSettings` with every file-backed key resolved to a concrete value.
|
||||
* What `resolveProjectSettings(...).settings` produces once a t3.json (or
|
||||
* its absence) has been accounted for.
|
||||
*/
|
||||
export type ResolvedServerSettings = Omit<ServerSettings, ProjectFileBackedSettingKey> & {
|
||||
readonly [K in ProjectFileBackedSettingKey]: Exclude<ServerSettings[K], null>;
|
||||
};
|
||||
@@ -127,10 +127,6 @@
|
||||
"types": "./src/projectSettings.ts",
|
||||
"import": "./src/projectSettings.ts"
|
||||
},
|
||||
"./threadEnvMode": {
|
||||
"types": "./src/threadEnvMode.ts",
|
||||
"import": "./src/threadEnvMode.ts"
|
||||
},
|
||||
"./t3ProjectFile": {
|
||||
"types": "./src/t3ProjectFile.ts",
|
||||
"import": "./src/t3ProjectFile.ts"
|
||||
|
||||
@@ -30,6 +30,24 @@ describe("resolveProjectSettings", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores an override left undefined by a forward-compatible decode", () => {
|
||||
const resolved = resolveProjectSettings(
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
defaultRuntimeMode: "full-access",
|
||||
projectSettingsOverrides: { [projectId]: { defaultRuntimeMode: undefined } as never },
|
||||
},
|
||||
projectId,
|
||||
);
|
||||
expect(resolved.settings.defaultRuntimeMode).toBe("full-access");
|
||||
expect(resolved.sources.defaultRuntimeMode).toBe("environment");
|
||||
expect(
|
||||
hasProjectSettingsOverrides({
|
||||
projectSettingsOverrides: { [projectId]: { defaultRuntimeMode: undefined } as never },
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a null project like an absent one before the shell snapshot arrives", () => {
|
||||
// The mobile new-task flow resolves settings while its selected project is
|
||||
// still null; reading the aggregate's legacy fields off null crashed launch.
|
||||
@@ -118,6 +136,64 @@ describe("resolveProjectSettings", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveProjectSettings with a t3.json", () => {
|
||||
it("walks project override, environment value, file, then built-in for file-backed keys", () => {
|
||||
const file = { defaultThreadEnvMode: "worktree" as const };
|
||||
const fromOverride = resolveProjectSettings(
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
projectSettingsOverrides: { [projectId]: { defaultThreadEnvMode: "local" } },
|
||||
},
|
||||
projectId,
|
||||
null,
|
||||
file,
|
||||
);
|
||||
expect(fromOverride.settings.defaultThreadEnvMode).toBe("local");
|
||||
expect(fromOverride.sources.defaultThreadEnvMode).toBe("project");
|
||||
|
||||
const fromEnvironment = resolveProjectSettings(
|
||||
{ ...DEFAULT_SERVER_SETTINGS, defaultThreadEnvMode: "local" },
|
||||
projectId,
|
||||
null,
|
||||
file,
|
||||
);
|
||||
expect(fromEnvironment.settings.defaultThreadEnvMode).toBe("local");
|
||||
expect(fromEnvironment.sources.defaultThreadEnvMode).toBe("environment");
|
||||
|
||||
const fromFile = resolveProjectSettings(DEFAULT_SERVER_SETTINGS, projectId, null, file);
|
||||
expect(fromFile.settings.defaultThreadEnvMode).toBe("worktree");
|
||||
expect(fromFile.sources.defaultThreadEnvMode).toBe("t3.json");
|
||||
|
||||
const builtIn = resolveProjectSettings(DEFAULT_SERVER_SETTINGS, projectId, null, null);
|
||||
expect(builtIn.settings.defaultThreadEnvMode).toBe("local");
|
||||
expect(builtIn.sources.defaultThreadEnvMode).toBe("environment");
|
||||
// A stored null override defers like an unset one and is not reported
|
||||
// as the project's value.
|
||||
const nullOverride = resolveProjectSettings(
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
projectSettingsOverrides: { [projectId]: { defaultThreadEnvMode: null } as never },
|
||||
},
|
||||
projectId,
|
||||
null,
|
||||
file,
|
||||
);
|
||||
expect(nullOverride.settings.defaultThreadEnvMode).toBe("worktree");
|
||||
expect(nullOverride.sources.defaultThreadEnvMode).toBe("t3.json");
|
||||
// A file that does not mention the key leaves the source alone too.
|
||||
expect(
|
||||
resolveProjectSettings(DEFAULT_SERVER_SETTINGS, projectId, null, {}).sources
|
||||
.defaultThreadEnvMode,
|
||||
).toBe("environment");
|
||||
});
|
||||
|
||||
it("leaves settings untouched when no file is passed", () => {
|
||||
expect(resolveProjectSettings(DEFAULT_SERVER_SETTINGS, projectId).settings).toBe(
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("projectSettingsOverrides patches", () => {
|
||||
it("replaces a project's entry, removes it with null, and drops empty entries", () => {
|
||||
const first = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
|
||||
|
||||
@@ -1,24 +1,34 @@
|
||||
import {
|
||||
type ModelSelection,
|
||||
PROJECT_FILE_BACKED_SETTINGS,
|
||||
PROJECT_SCOPED_SERVER_SETTING_KEYS,
|
||||
type ProjectId,
|
||||
type ProjectScopedServerSettingKey,
|
||||
type ProjectSettingsOverrides,
|
||||
type ResolvedServerSettings,
|
||||
type ServerSettings,
|
||||
type T3ProjectFile,
|
||||
type ThreadEnvMode,
|
||||
type WorktreeCleanupRules,
|
||||
} from "@t3tools/contracts";
|
||||
import { isModelSelectionProviderEnabled } from "./serverSettings.ts";
|
||||
|
||||
export type ProjectSettingSource = "environment" | "project";
|
||||
/**
|
||||
* Where a project-scoped value came from. The order is the priority order:
|
||||
* a project override, then the environment value, then the repository's
|
||||
* t3.json for keys in `PROJECT_FILE_BACKED_SETTINGS`, then the built-in
|
||||
* default (reported as "environment", since that is what the environment
|
||||
* value is when nothing set it).
|
||||
*/
|
||||
export type ProjectSettingSource = "environment" | "project" | "t3.json";
|
||||
|
||||
export type ProjectSettingSources = Readonly<
|
||||
Record<ProjectScopedServerSettingKey, ProjectSettingSource>
|
||||
>;
|
||||
|
||||
export interface ResolvedProjectSettings {
|
||||
export interface ResolvedProjectSettings<Settings extends ServerSettings = ServerSettings> {
|
||||
/** Environment settings with the project's overrides applied. */
|
||||
readonly settings: ServerSettings;
|
||||
readonly settings: Settings;
|
||||
/** Where each scopable key's effective value came from. */
|
||||
readonly sources: ProjectSettingSources;
|
||||
/** The project's raw override entry; `{}` when it has none. */
|
||||
@@ -36,7 +46,9 @@ export function hasProjectSettingsOverrides(
|
||||
settings: Pick<ServerSettings, "projectSettingsOverrides">,
|
||||
): boolean {
|
||||
for (const entry of Object.values(settings.projectSettingsOverrides)) {
|
||||
if (Object.keys(entry).length > 0) return true;
|
||||
// A forward-compatible decode can leave an unknown value as a present
|
||||
// undefined; that is not an override.
|
||||
if (Object.values(entry).some((value) => value !== undefined)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -63,6 +75,55 @@ export function resolveProjectSettings(
|
||||
// Nullable, not just optional: the mobile new-task flow passes its selected
|
||||
// project straight through, and that is null until the shell snapshot lands.
|
||||
project?: LegacyProjectSettingsFields | null,
|
||||
): ResolvedProjectSettings;
|
||||
/**
|
||||
* With the checkout's decoded t3.json (or null for a missing or invalid
|
||||
* one), every file-backed key resolves to a concrete value: the file fills
|
||||
* keys whose project and environment tiers are both unset, and the built-in
|
||||
* default fills what is left.
|
||||
*/
|
||||
export function resolveProjectSettings(
|
||||
settings: ServerSettings,
|
||||
projectId: ProjectId | null,
|
||||
project: LegacyProjectSettingsFields | null | undefined,
|
||||
projectFile: T3ProjectFile | null,
|
||||
): ResolvedProjectSettings<ResolvedServerSettings>;
|
||||
export function resolveProjectSettings(
|
||||
settings: ServerSettings,
|
||||
projectId: ProjectId | null,
|
||||
project?: LegacyProjectSettingsFields | null,
|
||||
projectFile?: T3ProjectFile | null,
|
||||
): ResolvedProjectSettings {
|
||||
const resolved = resolveProjectOverrides(settings, projectId, project);
|
||||
return projectFile === undefined ? resolved : applyProjectFile(resolved, projectFile);
|
||||
}
|
||||
|
||||
function applyProjectFile(
|
||||
resolved: ResolvedProjectSettings,
|
||||
projectFile: T3ProjectFile | null,
|
||||
): ResolvedProjectSettings {
|
||||
let effective: Record<string, unknown> | null = null;
|
||||
let sources: Record<ProjectScopedServerSettingKey, ProjectSettingSource> | null = null;
|
||||
for (const [key, { field, builtIn }] of Object.entries(PROJECT_FILE_BACKED_SETTINGS)) {
|
||||
const settingKey = key as ProjectScopedServerSettingKey;
|
||||
if (resolved.settings[settingKey] !== null) continue;
|
||||
const fromFile = projectFile?.[field];
|
||||
effective ??= { ...resolved.settings };
|
||||
sources ??= { ...resolved.sources };
|
||||
effective[settingKey] = fromFile ?? builtIn;
|
||||
// A project override of null defers like an unset one, so the value did
|
||||
// not come from the project either way.
|
||||
sources[settingKey] = fromFile === undefined ? "environment" : "t3.json";
|
||||
}
|
||||
return effective === null || sources === null
|
||||
? resolved
|
||||
: { ...resolved, settings: effective as ServerSettings, sources };
|
||||
}
|
||||
|
||||
function resolveProjectOverrides(
|
||||
settings: ServerSettings,
|
||||
projectId: ProjectId | null,
|
||||
project?: LegacyProjectSettingsFields | null,
|
||||
): ResolvedProjectSettings {
|
||||
const stored = projectId === null ? undefined : settings.projectSettingsOverrides[projectId];
|
||||
const overrides: ProjectSettingsOverrides =
|
||||
@@ -87,6 +148,9 @@ export function resolveProjectSettings(
|
||||
for (const key of PROJECT_SCOPED_SERVER_SETTING_KEYS) {
|
||||
if (!Object.hasOwn(overrides, key)) continue;
|
||||
const value = overrides[key];
|
||||
// A forward-compatible decode leaves an unknown value as a present
|
||||
// undefined; that is not an override.
|
||||
if (value === undefined) continue;
|
||||
// A model on a disabled provider falls back to the environment, like the
|
||||
// environment-level guards do for these keys.
|
||||
if (
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isDefaultThreadEnvModeSettled, resolveDefaultThreadEnvMode } from "./threadEnvMode.ts";
|
||||
|
||||
describe("resolveDefaultThreadEnvMode", () => {
|
||||
it("prefers the project setting over t3.json over the global default", () => {
|
||||
expect(
|
||||
resolveDefaultThreadEnvMode({
|
||||
projectSetting: "local",
|
||||
projectFile: "worktree",
|
||||
globalDefault: "worktree",
|
||||
}),
|
||||
).toBe("local");
|
||||
expect(
|
||||
resolveDefaultThreadEnvMode({
|
||||
projectSetting: null,
|
||||
projectFile: "local",
|
||||
globalDefault: "worktree",
|
||||
}),
|
||||
).toBe("local");
|
||||
expect(
|
||||
resolveDefaultThreadEnvMode({
|
||||
projectSetting: undefined,
|
||||
projectFile: null,
|
||||
globalDefault: "worktree",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isDefaultThreadEnvModeSettled", () => {
|
||||
it("settles on an explicit pick or project setting even while the file loads", () => {
|
||||
expect(
|
||||
isDefaultThreadEnvModeSettled({
|
||||
explicitMode: "local",
|
||||
projectSetting: null,
|
||||
projectFilePending: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isDefaultThreadEnvModeSettled({
|
||||
explicitMode: undefined,
|
||||
projectSetting: "worktree",
|
||||
projectFilePending: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("stays unsettled only while a consulted file read is pending", () => {
|
||||
expect(
|
||||
isDefaultThreadEnvModeSettled({
|
||||
explicitMode: undefined,
|
||||
projectSetting: null,
|
||||
projectFilePending: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isDefaultThreadEnvModeSettled({
|
||||
explicitMode: undefined,
|
||||
projectSetting: null,
|
||||
projectFilePending: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import type { ThreadEnvMode } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Canonical priority order for a project's default thread env mode:
|
||||
* per-project setting > checked-in t3.json > global server setting.
|
||||
*
|
||||
* An explicit composer pick outranks all of these; callers apply it before
|
||||
* consulting the defaults. Web resolves the sources imperatively at draft
|
||||
* creation, mobile reactively — both must route through this function so the
|
||||
* platforms cannot disagree on the order.
|
||||
*/
|
||||
export function resolveDefaultThreadEnvMode(sources: {
|
||||
readonly projectSetting: ThreadEnvMode | null | undefined;
|
||||
readonly projectFile: ThreadEnvMode | null | undefined;
|
||||
readonly globalDefault: ThreadEnvMode;
|
||||
}): ThreadEnvMode {
|
||||
return sources.projectSetting ?? sources.projectFile ?? sources.globalDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* True once the resolved default can no longer change: an explicit pick or a
|
||||
* source that outranks t3.json decided, or the file read settled. While
|
||||
* false, nothing may persist the provisional default (for example into a
|
||||
* draft's workspace selection) — it could differ from the final value.
|
||||
*/
|
||||
export function isDefaultThreadEnvModeSettled(sources: {
|
||||
readonly explicitMode: ThreadEnvMode | undefined;
|
||||
readonly projectSetting: ThreadEnvMode | null | undefined;
|
||||
readonly projectFilePending: boolean;
|
||||
}): boolean {
|
||||
return (
|
||||
sources.explicitMode !== undefined ||
|
||||
sources.projectSetting != null ||
|
||||
!sources.projectFilePending
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user