Skip to content
TypeScript

feat(settings): edit any scopable setting as a project override (#10639)

Julius Marmingee22040dfc190
diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
index 77036c21251..d57904b7e7a 100644
--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
@@ -41,14 +41,8 @@ import {
DEFAULT_SERVER_SETTINGS,
MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
- type ServerSettingsPatch,
} from "@t3tools/contracts";
-import {
- filterSharedServerPatch,
- findSharedSettingsMismatches,
- pickSharedServerSettings,
- supportsSharedSettingsSync,
-} from "@t3tools/client-runtime/state/shared-settings";
+import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import {
type AppUpdateCheckState,
@@ -61,6 +55,7 @@ import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
+import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync";
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
@@ -588,10 +583,9 @@ function GeneralSettingsSection() {
const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_SERVER_SETTINGS.sidebarAutoSettleAfterDays ?? 3;
/**
- * Auto-settlement is a user preference that every server has to hold. Mobile
- * has no primary environment, so the first eligible sync target provides the
- * reference value. Edits fan out to every eligible target, and a mismatch row
- * lets the user push the reference out.
+ * Mobile edits auto-settle defaults across connected, capable environments.
+ * The first target supplies the displayed values. Applying them leaves each
+ * environment's other defaults and overrides intact.
*/
function AutoSettleSettingsRows() {
const { environments } = useEnvironments();
@@ -610,24 +604,20 @@ function AutoSettleSettingsRows() {
return null;
}
- const writeToAll = (patch: ServerSettingsPatch) => {
+ const writeToAll = (patch: Partial<AutoSettleSettings>) => {
for (const environment of syncTargets) {
void updateSettings({ environmentId: environment.environmentId, input: { patch } });
}
};
- const mismatches = findSharedSettingsMismatches({
- primaryEnvironmentId: reference.environmentId,
- primarySettings: referenceSettings,
- primaryCapabilities: reference.serverConfig?.environment.capabilities,
- environments: environments.map((environment) => ({
+ const { patch: autoSettlePatch, mismatches } = planAutoSettleSettingsSync(
+ { environmentId: reference.environmentId, settings: referenceSettings },
+ syncTargets.map((environment) => ({
environmentId: environment.environmentId,
label: environment.label,
- syncEligible: supportsSharedSettingsSync(environment),
settings: environment.serverConfig?.settings ?? null,
- capabilities: environment.serverConfig?.environment.capabilities,
})),
- });
+ );
const afterDays = referenceSettings.sidebarAutoSettleAfterDays;
const commitDays = () => {
@@ -681,7 +671,7 @@ function AutoSettleSettingsRows() {
{mismatches.length > 0 ? (
<View className="flex-row items-center gap-4 border-t border-border-subtle p-4">
<View className="min-w-0 flex-1">
- <Text className="text-lg text-foreground">Settings differ</Text>
+ <Text className="text-lg text-foreground">Auto-settle defaults differ</Text>
<Text className="text-sm text-foreground-muted">
{mismatches.map((mismatch) => mismatch.label).join(", ")}
</Text>
@@ -689,30 +679,18 @@ function AutoSettleSettingsRows() {
<Pressable
accessibilityRole="button"
onPress={() => {
- const patch = pickSharedServerSettings(
- referenceSettings,
- reference.serverConfig?.environment.capabilities,
- );
for (const mismatch of mismatches) {
- const target = environments.find(
- (candidate) => candidate.environmentId === mismatch.environmentId,
- );
void updateSettings({
environmentId: mismatch.environmentId,
- input: {
- patch: filterSharedServerPatch(
- patch,
- target?.serverConfig?.environment.capabilities,
- target?.serverConfig?.settings,
- referenceSettings,
- ),
- },
+ input: { patch: autoSettlePatch },
});
}
}}
className="rounded-full bg-subtle px-4 py-2 active:opacity-70"
>
- <Text className="text-base font-t3-medium text-foreground">Apply to all</Text>
+ <Text className="text-base font-t3-medium text-foreground">
+ Apply auto-settle defaults
+ </Text>
</Pressable>
</View>
) : null}
diff --git a/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts b/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts
new file mode 100644
index 00000000000..ec550725adc
--- /dev/null
+++ b/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts
@@ -0,0 +1,78 @@
+import { DEFAULT_SERVER_SETTINGS, EnvironmentId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { planAutoSettleSettingsSync } from "./autoSettleSettingsSync";
+
+const reference = {
+ environmentId: EnvironmentId.make("reference"),
+ settings: {
+ ...DEFAULT_SERVER_SETTINGS,
+ sidebarAutoSettleAfterDays: 7,
+ sidebarAutoSettleOnMerge: true,
+ newWorktreesStartFromOrigin: false,
+ continueThreadsAfterServerUpdate: false,
+ },
+};
+
+describe("auto-settle settings sync", () => {
+ it("ignores differences in independently configured environment settings", () => {
+ const target = {
+ environmentId: EnvironmentId.make("remote"),
+ label: "Remote",
+ settings: {
+ ...reference.settings,
+ newWorktreesStartFromOrigin: true,
+ continueThreadsAfterServerUpdate: true,
+ sourceControlWritingStyle: {
+ ...reference.settings.sourceControlWritingStyle,
+ customInstructions: "Keep this environment's writing instructions.",
+ },
+ },
+ };
+
+ const plan = planAutoSettleSettingsSync(reference, [target]);
+
+ expect(plan.mismatches).toEqual([]);
+ expect(plan.patch).toEqual({
+ sidebarAutoSettleAfterDays: 7,
+ sidebarAutoSettleOnMerge: true,
+ });
+ });
+
+ it("applies only auto-settle defaults when another environment differs", () => {
+ const target = {
+ environmentId: EnvironmentId.make("remote"),
+ label: "Remote",
+ settings: {
+ ...reference.settings,
+ sidebarAutoSettleAfterDays: null,
+ sidebarAutoSettleOnMerge: false,
+ newWorktreesStartFromOrigin: true,
+ continueThreadsAfterServerUpdate: true,
+ sourceControlWritingStyle: {
+ ...reference.settings.sourceControlWritingStyle,
+ customInstructions: "Preserve these instructions.",
+ },
+ },
+ };
+
+ const plan = planAutoSettleSettingsSync(reference, [target]);
+ const updated = { ...target.settings, ...plan.patch };
+
+ expect(plan.mismatches).toEqual([target]);
+ expect(updated.sidebarAutoSettleAfterDays).toBe(7);
+ expect(updated.sidebarAutoSettleOnMerge).toBe(true);
+ expect(updated.newWorktreesStartFromOrigin).toBe(true);
+ expect(updated.continueThreadsAfterServerUpdate).toBe(true);
+ expect(updated.sourceControlWritingStyle).toEqual(target.settings.sourceControlWritingStyle);
+ });
+
+ it("does not compare the reference or a target without loaded settings", () => {
+ const plan = planAutoSettleSettingsSync(reference, [
+ { ...reference, label: "Reference" },
+ { environmentId: EnvironmentId.make("loading"), label: "Loading", settings: null },
+ ]);
+
+ expect(plan.mismatches).toEqual([]);
+ });
+});
diff --git a/apps/mobile/src/features/settings/autoSettleSettingsSync.ts b/apps/mobile/src/features/settings/autoSettleSettingsSync.ts
new file mode 100644
index 00000000000..6addfa381fd
--- /dev/null
+++ b/apps/mobile/src/features/settings/autoSettleSettingsSync.ts
@@ -0,0 +1,31 @@
+import type { EnvironmentId, ServerSettings } from "@t3tools/contracts";
+
+export type AutoSettleSettings = Pick<
+ ServerSettings,
+ "sidebarAutoSettleAfterDays" | "sidebarAutoSettleOnMerge"
+>;
+
+interface AutoSettleSyncTarget {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly settings: AutoSettleSettings | null;
+}
+
+/** Receives connected, capable targets. Applying these defaults must preserve other settings. */
+export function planAutoSettleSettingsSync(
+ reference: { readonly environmentId: EnvironmentId; readonly settings: AutoSettleSettings },
+ targets: readonly AutoSettleSyncTarget[],
+) {
+ const patch: AutoSettleSettings = {
+ sidebarAutoSettleAfterDays: reference.settings.sidebarAutoSettleAfterDays,
+ sidebarAutoSettleOnMerge: reference.settings.sidebarAutoSettleOnMerge,
+ };
+ const mismatches = targets.filter(
+ (target) =>
+ target.environmentId !== reference.environmentId &&
+ target.settings !== null &&
+ (target.settings.sidebarAutoSettleAfterDays !== patch.sidebarAutoSettleAfterDays ||
+ target.settings.sidebarAutoSettleOnMerge !== patch.sidebarAutoSettleOnMerge),
+ );
+ return { patch, mismatches };
+}
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index 535581b58e7..d0687e7e7b6 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -13,10 +13,12 @@ import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
+ DEFAULT_SERVER_SETTINGS,
MessageId,
T3_PROJECT_FILE_NAME,
ThreadId,
} from "@t3tools/contracts";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import {
isDefaultThreadEnvModeSettled,
@@ -428,17 +430,32 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
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 projectSettings = useMemo(
+ () =>
+ resolveProjectSettings(
+ selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
+ selectedProject?.id ?? null,
+ selectedProject,
+ ),
+ [selectedEnvironmentServerConfig?.settings, selectedProject],
+ );
+ const projectThreadEnvMode =
+ projectSettings.sources.defaultThreadEnvMode === "project"
+ ? projectSettings.settings.defaultThreadEnvMode
+ : undefined;
const defaultWorkspaceMode: WorkspaceMode = resolveDefaultThreadEnvMode({
- projectSetting: selectedProject?.defaultThreadEnvMode,
+ projectSetting: projectThreadEnvMode,
projectFile: t3ProjectFileDefaultMode,
- globalDefault: selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local",
+ 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: selectedProject?.defaultThreadEnvMode,
+ projectSetting: projectThreadEnvMode,
projectFilePending: t3ProjectFileQuery.isPending,
});
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
@@ -449,9 +466,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
// value keeps tracking the server setting when the config loads late.
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
const startFromOrigin =
- draftStartFromOrigin ??
- selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
- true;
+ draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
// Antigravity keeps unavailable selections so sign-out or a catalog change
@@ -463,9 +478,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const projectDefaultModelSelection = resolveDefaultableModelSelection(
selectedEnvironmentServerConfig,
- selectedProject?.defaultModelSelection ??
- selectedEnvironmentServerConfig?.settings.defaultModelSelection ??
- null,
+ projectSettings.settings.defaultModelSelection,
);
const storedStickyModelSelection = useStickyComposerModelSelection();
const stickyModelSelection = resolveDefaultableModelSelection(
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 51b9c5eabc4..fc529b02a73 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -68,6 +68,7 @@ import {
projectScriptRuntimeEnv,
resolveProjectScripts,
} from "@t3tools/shared/projectScripts";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { truncate } from "@t3tools/shared/String";
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
import {
@@ -304,7 +305,6 @@ import {
environmentServerConfigsAtom,
primaryServerAvailableEditorsAtom,
primaryServerKeybindingsAtom,
- primaryServerSettingsAtom,
serverEnvironment,
} from "../state/server";
import { terminalEnvironment } from "../state/terminal";
@@ -1516,7 +1516,6 @@ export default function ChatView(props: ChatViewProps) {
}, [routeKind, routeThreadRef, routeThreadState]);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const settings = useEnvironmentSettings(environmentId);
- const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
);
@@ -1802,17 +1801,14 @@ export default function ChatView(props: ChatViewProps) {
? buildLocalDraftThread(
threadId,
draftThread,
- fallbackDraftProject?.defaultModelSelection ??
- settings.defaultModelSelection ??
- NO_PROVIDER_MODEL_SELECTION,
+ resolveProjectSettings(
+ settings,
+ fallbackDraftProject?.id ?? null,
+ fallbackDraftProject ?? undefined,
+ ).settings.defaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION,
)
: undefined,
- [
- draftThread,
- fallbackDraftProject?.defaultModelSelection,
- settings.defaultModelSelection,
- threadId,
- ],
+ [draftThread, fallbackDraftProject, settings, threadId],
);
// Promotion is data-driven: the draft route keeps rendering while the
// server thread (same pre-allocated ref) starts, so live state must not
@@ -2033,12 +2029,16 @@ export default function ChatView(props: ChatViewProps) {
[activeThread?.environmentId, activeThread?.projectId],
);
const activeProject = useProject(activeProjectRef);
+ // Environment settings with the active project's overrides applied.
+ const activeProjectSettings = useMemo(
+ () => resolveProjectSettings(settings, activeProject?.id ?? null, activeProject ?? undefined),
+ [activeProject, settings],
+ );
const activeProjectScripts = useMemo(
() => (activeProject ? resolveProjectScripts(settings, activeProject) : []),
[activeProject, settings],
);
- const activeProjectDefaultModelSelection =
- activeProject?.defaultModelSelection ?? settings.defaultModelSelection;
+ const activeProjectDefaultModelSelection = activeProjectSettings.settings.defaultModelSelection;
const handleNewThreadInActiveProject = useCallback(() => {
startNewThreadForProject(activeProjectRef, handleNewThread);
}, [activeProjectRef, handleNewThread]);
@@ -3945,6 +3945,9 @@ export default function ChatView(props: ChatViewProps) {
],
);
+ const supportsProjectSettingsOverrides =
+ environmentById.get(environmentId)?.serverConfig?.environment.capabilities
+ .projectSettingsOverrides === true;
const persistProjectScripts = useCallback(
async (input: {
projectId: ProjectId;
@@ -3958,11 +3961,22 @@ export default function ChatView(props: ChatViewProps) {
await updateProjectScriptSettings({
environmentId,
input: {
- patch: {
- projectScriptOverrides: {
- [input.projectId]: input.nextScripts,
- },
- },
+ // The canonical key on servers that understand it; the legacy
+ // per-project map is still translated on older ones.
+ patch: supportsProjectSettingsOverrides
+ ? {
+ projectSettingsOverrides: {
+ [input.projectId]: {
+ ...settings.projectSettingsOverrides[input.projectId],
+ defaultProjectScripts: input.nextScripts,
+ },
+ },
+ }
+ : {
+ projectScriptOverrides: {
+ [input.projectId]: input.nextScripts,
+ },
+ },
},
}),
() => undefined,
@@ -3987,7 +4001,13 @@ export default function ChatView(props: ChatViewProps) {
}
return updateResult;
},
- [environmentId, updateProjectScriptSettings, upsertKeybinding],
+ [
+ environmentId,
+ settings.projectSettingsOverrides,
+ supportsProjectSettingsOverrides,
+ updateProjectScriptSettings,
+ upsertKeybinding,
+ ],
);
const saveProjectScript = useCallback(
async (input: NewProjectScriptInput): Promise<AtomCommandResult<void, unknown>> => {
@@ -5396,7 +5416,7 @@ export default function ChatView(props: ChatViewProps) {
? (draftThread?.startFromOrigin ?? false)
: canOverrideServerThreadEnvMode
? (pendingServerThreadStartFromOriginByThreadId[activeThread?.id ?? ""] ??
- primaryServerSettings.newWorktreesStartFromOrigin)
+ activeProjectSettings.settings.newWorktreesStartFromOrigin)
: false;
const sendEnvMode = resolveSendEnvMode({
requestedEnvMode: envMode,
@@ -8045,7 +8065,7 @@ export default function ChatView(props: ChatViewProps) {
envMode: mode,
startFromOrigin: resolveNewDraftStartFromOrigin({
envMode: mode,
- newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
+ newWorktreesStartFromOrigin: activeProjectSettings.settings.newWorktreesStartFromOrigin,
}),
...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}),
});
@@ -8057,7 +8077,7 @@ export default function ChatView(props: ChatViewProps) {
composerDraftTarget,
draftThread?.worktreePath,
isLocalDraftThread,
- primaryServerSettings.newWorktreesStartFromOrigin,
+ activeProjectSettings.settings.newWorktreesStartFromOrigin,
setPendingServerThreadEnvMode,
scheduleComposerFocus,
setDraftThreadContext,
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index 4a9877f87a0..3533678ecb2 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -1814,8 +1814,7 @@ function OpenCommandPaletteDialog(props: {
},
});
- // There is no projects listing page; the action targets the contextual
- // project (active thread/draft, falling back to the first sidebar group).
+ // Target the active thread or draft's project, falling back to the first sidebar group.
const contextualProjectGroup =
(contextualProjectRef
? projectGroupByTargetKey.get(
@@ -1867,8 +1866,6 @@ function OpenCommandPaletteDialog(props: {
run: async () => {
await navigate({
to: item.to,
- search: (previous) =>
- item.to === "/settings/projects" ? { ...previous, project: undefined } : previous,
hash: item.targetId ?? item.id,
replace: pathname === item.to,
hashScrollIntoView: false,
diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx
index 4a9421f2011..1e0d295c098 100644
--- a/apps/web/src/components/chat/DraftHeroHeadline.tsx
+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx
@@ -27,6 +27,7 @@ import {
MenuTrigger,
} from "../ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
interface DraftHeroHeadlineProps {
readonly draftId: DraftId | null;
@@ -150,11 +151,13 @@ export function DraftHeroHeadline({
);
if (!hasExplicitComposerModelSelection(currentDraft)) {
applyStickyState(draftId);
- const defaultModelSelection =
- project.defaultModelSelection ??
- environments.find(
- (environment) => environment.environmentId === project.environmentId,
- )?.serverConfig?.settings.defaultModelSelection;
+ const environmentSettings = environments.find(
+ (environment) => environment.environmentId === project.environmentId,
+ )?.serverConfig?.settings;
+ const defaultModelSelection = environmentSettings
+ ? resolveProjectSettings(environmentSettings, project.id, project).settings
+ .defaultModelSelection
+ : project.defaultModelSelection;
if (defaultModelSelection) {
setModelSelection(draftId, defaultModelSelection, {
replaceOptions: true,
diff --git a/apps/web/src/components/chat/ProviderModelPicker.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.test.tsx
index b1bb8ba9c74..41e86f841ee 100644
--- a/apps/web/src/components/chat/ProviderModelPicker.test.tsx
+++ b/apps/web/src/components/chat/ProviderModelPicker.test.tsx
@@ -34,6 +34,7 @@ function renderPicker(input: {
model: string;
options: ReadonlyArray<ModelEsque>;
includeEntry?: boolean;
+ triggerLabel?: string;
}) {
const instanceId = ProviderInstanceId.make(input.instanceId);
const entry = providerEntry(input.instanceId, input.driver);
@@ -45,11 +46,25 @@ function renderPicker(input: {
instanceEntries={input.includeEntry === false ? [] : [entry]}
modelOptionsByInstance={new Map([[instanceId, input.options]])}
onInstanceModelChange={() => {}}
+ {...(input.triggerLabel ? { triggerLabel: input.triggerLabel } : {})}
/>,
);
}
describe("ProviderModelPicker", () => {
+ it("shows a neutral aggregate value without a representative model or availability badge", () => {
+ const markup = renderPicker({
+ instanceId: "codex_personal",
+ driver: "codex",
+ model: "gpt-5",
+ options: [{ slug: "gpt-5", name: "GPT 5", isUnavailable: true }],
+ triggerLabel: "Mixed values",
+ });
+ expect(markup).toContain("Mixed values");
+ expect(markup).not.toContain("GPT 5");
+ expect(markup).not.toContain("Unavailable");
+ });
+
it.each(["", ANTIGRAVITY_DEFAULT_MODEL])(
"shows a choice prompt before Antigravity has an account catalog for %s",
(model) => {
diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx
index fb2cdb2f128..6f777399451 100644
--- a/apps/web/src/components/chat/ProviderModelPicker.tsx
+++ b/apps/web/src/components/chat/ProviderModelPicker.tsx
@@ -48,6 +48,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
open?: boolean;
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
triggerClassName?: string;
+ /** Aggregate settings can show a neutral value without claiming one provider is selected. */
+ triggerLabel?: string;
triggerAriaLabel?: string;
onOpenChange?: (open: boolean) => void;
onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
@@ -181,7 +183,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
<span
className={cn("flex min-w-0 flex-1 items-center", size === "xs" ? "gap-1" : "gap-1.5")}
>
- {activeEntry ? (
+ {activeEntry && props.triggerLabel === undefined ? (
<ProviderInstanceIcon
driverKind={activeEntry.driverKind}
displayName={activeEntry.displayName}
@@ -205,11 +207,11 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
/>
}
>
- {triggerTitle}
+ {props.triggerLabel ?? triggerTitle}
</TooltipTrigger>
- <TooltipPopup side="top">{triggerLabel}</TooltipPopup>
+ <TooltipPopup side="top">{props.triggerLabel ?? triggerLabel}</TooltipPopup>
</Tooltip>
- {selectedModel?.isUnavailable ? (
+ {selectedModel?.isUnavailable && props.triggerLabel === undefined ? (
<Badge variant="outline" size="sm">
Unavailable
</Badge>
diff --git a/apps/web/src/components/projectScriptEditor.test.tsx b/apps/web/src/components/projectScriptEditor.test.tsx
new file mode 100644
index 00000000000..becb3a369f6
--- /dev/null
+++ b/apps/web/src/components/projectScriptEditor.test.tsx
@@ -0,0 +1,245 @@
+import * as Cause from "effect/Cause";
+import { AsyncResult } from "effect/unstable/reactivity";
+import { act, StrictMode, type ReactNode } from "react";
+import { create, type ReactTestRenderer } from "react-test-renderer";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+vi.mock("./ui/dialog", () => ({
+ Dialog: ({ open, children }: { open: boolean; children: ReactNode }) => (open ? children : null),
+ DialogDescription: "p",
+ DialogFooter: "footer",
+ DialogHeader: "header",
+ DialogPanel: "section",
+ DialogPopup: "section",
+ DialogTitle: "h2",
+}));
+vi.mock("./ui/alert-dialog", () => ({
+ AlertDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
+ open ? children : null,
+ AlertDialogClose: "button",
+ AlertDialogDescription: "p",
+ AlertDialogFooter: "footer",
+ AlertDialogHeader: "header",
+ AlertDialogPopup: "section",
+ AlertDialogTitle: "h2",
+}));
+vi.mock("./ui/button", () => ({ Button: "button" }));
+vi.mock("./ui/input", () => ({ Input: "input" }));
+vi.mock("./ui/label", () => ({ Label: "label" }));
+vi.mock("./ui/popover", () => ({
+ Popover: ({ children }: { children: ReactNode }) => children,
+ PopoverPopup: () => null,
+ PopoverTrigger: "button",
+}));
+vi.mock("./ui/switch", () => ({ Switch: "input" }));
+vi.mock("./ui/textarea", () => ({ Textarea: "textarea" }));
+
+import {
+ EMPTY_PROJECT_SCRIPT_INPUT,
+ ProjectScriptEditorDialog,
+ type ProjectScriptActionResult,
+ type ProjectScriptEditorRequest,
+} from "./projectScriptEditor";
+
+const onSubmit = vi.fn<Parameters<typeof ProjectScriptEditorDialog>[0]["onSubmit"]>();
+const onClose = vi.fn();
+const onDelete = vi.fn();
+let renderer: ReactTestRenderer | null;
+
+function request(name: string, error?: string): ProjectScriptEditorRequest {
+ return {
+ scriptId: name,
+ initial: { ...EMPTY_PROJECT_SCRIPT_INPUT, name, command: `run-${name}` },
+ ...(error === undefined ? {} : { error }),
+ };
+}
+
+function editor(nextRequest: ProjectScriptEditorRequest) {
+ return (
+ <StrictMode>
+ <ProjectScriptEditorDialog
+ request={nextRequest}
+ scripts={[]}
+ onSubmit={onSubmit}
+ onClose={onClose}
+ onDelete={onDelete}
+ />
+ </StrictMode>
+ );
+}
+
+function open(nextRequest: ProjectScriptEditorRequest) {
+ act(() => {
+ if (renderer) renderer.update(editor(nextRequest));
+ else renderer = create(editor(nextRequest));
+ });
+}
+
+function submit(): Promise<void> {
+ return renderer!.root.findByType("form").props.onSubmit({ preventDefault() {} });
+}
+
+function saveButton() {
+ return renderer!.root.findAllByType("button").find((button) => button.props.type === "submit")!;
+}
+
+function deferredSave() {
+ let resolve!: (result: ProjectScriptActionResult) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<ProjectScriptActionResult>((resolveResult, rejectResult) => {
+ resolve = resolveResult;
+ reject = rejectResult;
+ });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => {
+ renderer = null;
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ onSubmit.mockReset();
+ onClose.mockReset();
+ onDelete.mockReset();
+});
+
+afterEach(async () => {
+ await act(async () => renderer?.unmount());
+ vi.unstubAllGlobals();
+});
+
+describe("project action editor save lifecycle", () => {
+ it("blocks repeated submits and edits until the current save completes", async () => {
+ const save = deferredSave();
+ onSubmit.mockReturnValue(save.promise);
+ open(request("build"));
+
+ let completion!: Promise<void>;
+ act(() => {
+ completion = submit();
+ void submit();
+ });
+
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ expect(saveButton().props.disabled).toBe(true);
+ expect(renderer!.root.findByType("fieldset").props.disabled).toBe(true);
+ const cancel = renderer!.root
+ .findAllByType("button")
+ .find((button) => button.children.includes("Cancel"))!;
+ expect(cancel.props.disabled).not.toBe(true);
+
+ await act(async () => {
+ save.resolve(AsyncResult.success(undefined));
+ await completion;
+ });
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not close a replacement request or release its in-flight save", async () => {
+ const first = deferredSave();
+ const second = deferredSave();
+ onSubmit.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+ open(request("build"));
+ let firstCompletion!: Promise<void>;
+ act(() => {
+ firstCompletion = submit();
+ });
+
+ open(request("test"));
+ expect(saveButton().props.disabled).toBe(false);
+ expect(renderer!.root.findByProps({ id: "script-name" }).props.value).toBe("test");
+ let secondCompletion!: Promise<void>;
+ act(() => {
+ secondCompletion = submit();
+ });
+
+ await act(async () => {
+ first.resolve(AsyncResult.success(undefined));
+ await firstCompletion;
+ });
+ expect(onClose).not.toHaveBeenCalled();
+ expect(saveButton().props.disabled).toBe(true);
+
+ await act(async () => {
+ second.resolve(AsyncResult.success(undefined));
+ await secondCompletion;
+ });
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]);
+ });
+
+ it.each(["failure", "rejection"] as const)(
+ "ignores a stale %s after the request changes",
+ async (outcome) => {
+ const save = deferredSave();
+ onSubmit.mockReturnValue(save.promise);
+ open(request("build"));
+ let completion!: Promise<void>;
+ act(() => {
+ completion = submit();
+ });
+
+ open(request("test", "New request error"));
+ await act(async () => {
+ if (outcome === "failure")
+ save.resolve(AsyncResult.failure(Cause.fail(new Error("Old save error"))));
+ else save.reject(new Error("Old save error"));
+ await completion;
+ });
+
+ const messages = renderer!.root.findAllByType("p").flatMap((paragraph) => paragraph.children);
+ expect(messages).toContain("New request error");
+ expect(messages).not.toContain("Old save error");
+ expect(saveButton().props.disabled).toBe(false);
+ expect(onClose).not.toHaveBeenCalled();
+ },
+ );
+
+ it("shows a current save error and allows retry", async () => {
+ onSubmit.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Save failed"))));
+ onSubmit.mockResolvedValueOnce(AsyncResult.success(undefined));
+ open(request("build"));
+
+ await act(async () => {
+ await submit();
+ });
+ expect(renderer!.root.findAllByType("p").flatMap((paragraph) => paragraph.children)).toContain(
+ "Save failed",
+ );
+ expect(saveButton().props.disabled).toBe(false);
+ expect(renderer!.root.findByType("fieldset").props.disabled).toBe(false);
+ expect(onClose).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await submit();
+ });
+ expect(onSubmit).toHaveBeenCalledTimes(2);
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(["cancel", "unmount"] as const)("ignores save completion after %s", async (exit) => {
+ const save = deferredSave();
+ onSubmit.mockReturnValue(save.promise);
+ open(request("build"));
+ let completion!: Promise<void>;
+ act(() => {
+ completion = submit();
+ });
+
+ act(() => {
+ if (exit === "cancel") {
+ renderer!.root
+ .findAllByType("button")
+ .find((button) => button.children.includes("Cancel"))!
+ .props.onClick();
+ } else {
+ renderer!.unmount();
+ renderer = null;
+ }
+ });
+ onClose.mockClear();
+ await act(async () => {
+ save.resolve(AsyncResult.success(undefined));
+ await completion;
+ });
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsx
index 4ffd453955e..74b189a02fc 100644
--- a/apps/web/src/components/projectScriptEditor.tsx
+++ b/apps/web/src/components/projectScriptEditor.tsx
@@ -16,7 +16,14 @@ import {
PlayIcon,
WrenchIcon,
} from "lucide-react";
-import React, { type FormEvent, type KeyboardEvent, useEffect, useState } from "react";
+import React, {
+ type FormEvent,
+ type KeyboardEvent,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import {
keybindingValueForCommand,
@@ -156,9 +163,22 @@ export function ProjectScriptEditorDialog({
const [autoOpenPreview, setAutoOpenPreview] = useState(false);
const [validationError, setValidationError] = useState<string | null>(null);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
+ const [savingRequest, setSavingRequest] = useState<ProjectScriptEditorRequest | null>(null);
+ const pendingSubmissionRef = useRef<{ request: ProjectScriptEditorRequest } | null>(null);
const isOpen = request !== null;
const isEditing = request?.scriptId != null;
+ const isSaving = request !== null && savingRequest === request;
+
+ // A save completion must not affect a replacement request or an unmounted editor.
+ useLayoutEffect(
+ () => () => {
+ if (pendingSubmissionRef.current?.request === request) {
+ pendingSubmissionRef.current = null;
+ }
+ },
+ [request],
+ );
// Hydrate the form whenever a new request opens the dialog.
useEffect(() => {
@@ -172,8 +192,16 @@ export function ProjectScriptEditorDialog({
setPreviewUrl(request.initial.previewUrl ?? "");
setAutoOpenPreview(request.initial.autoOpenPreview);
setValidationError(request.error ?? null);
+ setSavingRequest(null);
}, [request]);
+ const close = () => {
+ pendingSubmissionRef.current = null;
+ setSavingRequest(null);
+ setIconPickerOpen(false);
+ onClose();
+ };
+
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Tab") return;
event.preventDefault();
@@ -188,7 +216,7 @@ export function ProjectScriptEditorDialog({
const submit = async (event: FormEvent) => {
event.preventDefault();
- if (!request) return;
+ if (!request || pendingSubmissionRef.current !== null) return;
const trimmedName = name.trim();
const trimmedCommand = command.trim();
if (trimmedName.length === 0) {
@@ -228,16 +256,31 @@ export function ProjectScriptEditorDialog({
return;
}
- const result = await onSubmit(request.scriptId, payload);
- if (result._tag === "Failure") {
- if (!isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
+ const submission = { request };
+ pendingSubmissionRef.current = submission;
+ setSavingRequest(request);
+ setIconPickerOpen(false);
+ try {
+ const result = await onSubmit(request.scriptId, payload);
+ if (pendingSubmissionRef.current === submission) {
+ if (result._tag === "Failure") {
+ if (!isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ setValidationError(error instanceof Error ? error.message : "Failed to save action.");
+ }
+ } else {
+ close();
+ }
+ }
+ } catch (error) {
+ if (pendingSubmissionRef.current === submission) {
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
}
- return;
}
- setIconPickerOpen(false);
- onClose();
+ if (pendingSubmissionRef.current === submission) {
+ pendingSubmissionRef.current = null;
+ setSavingRequest(null);
+ }
};
return (
@@ -246,8 +289,7 @@ export function ProjectScriptEditorDialog({
open={isOpen}
onOpenChange={(open) => {
if (!open) {
- setIconPickerOpen(false);
- onClose();
+ close();
}
}}
>
@@ -259,112 +301,115 @@ export function ProjectScriptEditorDialog({
</DialogDescription>
</DialogHeader>
<DialogPanel>
- <form id={formId} className="space-y-4" onSubmit={submit}>
- <div className="space-y-1.5">
- <Label htmlFor="script-name">Name</Label>
- <div className="flex items-center gap-2">
- <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
- <PopoverTrigger
- render={
- <Button
- type="button"
- variant="outline"
- className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:border-transparent dark:bg-white/[0.035] dark:data-pressed:before:shadow-none"
- aria-label="Choose icon"
- />
- }
- >
- <ScriptIcon icon={icon} className="size-4.5" />
- </PopoverTrigger>
- <PopoverPopup align="start">
- <div className="grid grid-cols-3 gap-2">
- {SCRIPT_ICONS.map((entry) => {
- const isSelected = entry.id === icon;
- return (
- <button
- key={entry.id}
- type="button"
- className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
- isSelected
- ? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
- : "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
- }`}
- onClick={() => {
- setIcon(entry.id);
- setIconPickerOpen(false);
- }}
- >
- <ScriptIcon icon={entry.id} className="size-4" />
- <span>{entry.label}</span>
- </button>
- );
- })}
- </div>
- </PopoverPopup>
- </Popover>
+ <form id={formId} onSubmit={submit}>
+ <fieldset className="space-y-4" disabled={isSaving}>
+ <div className="space-y-1.5">
+ <Label htmlFor="script-name">Name</Label>
+ <div className="flex items-center gap-2">
+ <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
+ <PopoverTrigger
+ render={
+ <Button
+ type="button"
+ variant="outline"
+ className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:border-transparent dark:bg-white/[0.035] dark:data-pressed:before:shadow-none"
+ aria-label="Choose icon"
+ />
+ }
+ >
+ <ScriptIcon icon={icon} className="size-4.5" />
+ </PopoverTrigger>
+ <PopoverPopup align="start">
+ <div className="grid grid-cols-3 gap-2">
+ {SCRIPT_ICONS.map((entry) => {
+ const isSelected = entry.id === icon;
+ return (
+ <button
+ key={entry.id}
+ type="button"
+ className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
+ isSelected
+ ? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
+ : "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
+ }`}
+ onClick={() => {
+ setIcon(entry.id);
+ setIconPickerOpen(false);
+ }}
+ >
+ <ScriptIcon icon={entry.id} className="size-4" />
+ <span>{entry.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ </PopoverPopup>
+ </Popover>
+ <Input
+ id="script-name"
+ autoFocus
+ placeholder="Test"
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ />
+ </div>
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="script-keybinding">Keybinding</Label>
<Input
- id="script-name"
- autoFocus
- placeholder="Test"
- value={name}
- onChange={(event) => setName(event.target.value)}
+ id="script-keybinding"
+ placeholder="Press shortcut"
+ value={keybinding}
+ readOnly
+ onKeyDown={captureKeybinding}
/>
+ <p className="text-xs text-muted-foreground">
+ Press a shortcut. Use <code>Backspace</code> to clear. Shortcuts are
+ environment-wide. Projects using the same action share its shortcut.
+ </p>
</div>
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="script-keybinding">Keybinding</Label>
- <Input
- id="script-keybinding"
- placeholder="Press shortcut"
- value={keybinding}
- readOnly
- onKeyDown={captureKeybinding}
- />
- <p className="text-xs text-muted-foreground">
- Press a shortcut. Use <code>Backspace</code> to clear.
- </p>
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="script-command">Command</Label>
- <Textarea
- id="script-command"
- placeholder="bun test"
- value={command}
- onChange={(event) => setCommand(event.target.value)}
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="script-preview-url">Preview URL (optional)</Label>
- <Input
- id="script-preview-url"
- placeholder="http://localhost:5173"
- value={previewUrl}
- onChange={(event) => setPreviewUrl(event.target.value)}
- />
- <p className="text-xs text-muted-foreground">
- Open this URL in the in-app preview when this action runs.
- </p>
- </div>
- <label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
- <span>Run automatically on worktree creation</span>
- <Switch
- checked={runOnWorktreeCreate}
- onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
- />
- </label>
- <label
- className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${
- previewUrl.trim().length === 0 ? "opacity-60" : ""
- }`}
- >
- <span>Open preview automatically when this action runs</span>
- <Switch
- checked={autoOpenPreview}
- disabled={previewUrl.trim().length === 0}
- onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
- />
- </label>
- {validationError && <p className="text-sm text-destructive">{validationError}</p>}
+ <div className="space-y-1.5">
+ <Label htmlFor="script-command">Command</Label>
+ <Textarea
+ id="script-command"
+ placeholder="bun test"
+ value={command}
+ onChange={(event) => setCommand(event.target.value)}
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="script-preview-url">Preview URL (optional)</Label>
+ <Input
+ id="script-preview-url"
+ placeholder="http://localhost:5173"
+ value={previewUrl}
+ onChange={(event) => setPreviewUrl(event.target.value)}
+ />
+ <p className="text-xs text-muted-foreground">
+ Open this URL in the in-app preview when this action runs.
+ </p>
+ </div>
+ <label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
+ <span>Run automatically on worktree creation</span>
+ <Switch
+ checked={runOnWorktreeCreate}
+ onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
+ />
+ </label>
+ <label
+ className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${
+ previewUrl.trim().length === 0 ? "opacity-60" : ""
+ }`}
+ >
+ <span>Open preview automatically when this action runs</span>
+ <Switch
+ checked={autoOpenPreview}
+ disabled={previewUrl.trim().length === 0}
+ onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
+ />
+ </label>
+ {validationError && <p className="text-sm text-destructive">{validationError}</p>}
+ </fieldset>
</form>
</DialogPanel>
<DialogFooter className="dark:border-transparent dark:bg-transparent">
@@ -373,16 +418,17 @@ export function ProjectScriptEditorDialog({
type="button"
variant="destructive-outline"
className="mr-auto"
+ disabled={isSaving}
onClick={() => setDeleteConfirmOpen(true)}
>
Delete
</Button>
)}
- <Button type="button" variant="outline" onClick={onClose}>
+ <Button type="button" variant="outline" onClick={close}>
Cancel
</Button>
- <Button form={formId} type="submit">
- {isEditing ? "Save changes" : "Save action"}
+ <Button form={formId} type="submit" disabled={isSaving}>
+ {isSaving ? "Saving…" : isEditing ? "Save changes" : "Save action"}
</Button>
</DialogFooter>
</DialogPopup>
@@ -398,10 +444,11 @@ export function ProjectScriptEditorDialog({
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
variant="destructive"
+ disabled={isSaving}
onClick={() => {
if (!request?.scriptId) return;
setDeleteConfirmOpen(false);
- onClose();
+ close();
onDelete(request.scriptId);
}}
>
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index 0284a2e6cde..990b0ce3b9c 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -5,6 +5,7 @@ import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime/enviro
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
type EnvironmentId,
+ DEFAULT_SERVER_SETTINGS,
type PullRequestAction,
type PullRequestMergeMethod,
type PullRequestListEntry,
@@ -13,6 +14,7 @@ import {
resolveEnvironmentMachineKind,
type ScopedThreadRef,
} from "@t3tools/contracts";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import {
ArrowDownUpIcon,
ArrowLeftIcon,
@@ -55,8 +57,8 @@ import {
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
-import { useClientSettings } from "~/hooks/useSettings";
import { useCopyToClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard";
+import { useClientSettings } from "~/hooks/useSettings";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKey,
@@ -585,10 +587,19 @@ export function PullRequestDetailPanel({
}, [condensed]);
const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod);
const setLastSelectedMergeMethod = useUiStateStore((state) => state.setPullRequestMergeMethod);
- const mergeMethodOverrides = useClientSettings(
+ // Server-side and per project, like every other project setting. The
+ // client-local per-project map from before still answers when the server
+ // has no value, so a choice made on an older release keeps applying until
+ // it is set (or reset) in Settings.
+ const legacyMergeMethodOverrides = useClientSettings(
(settings) => settings.pullRequestMergeMethodOverrides,
);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
+ const projectDefaultMergeMethod =
+ resolveProjectSettings(
+ environmentConfigs.get(environmentId)?.settings ?? DEFAULT_SERVER_SETTINGS,
+ reference.projectId,
+ ).settings.pullRequestMergeMethod ?? undefined;
const [mergeMethodSelection, setMergeMethodSelection] = useState<{
readonly pullRequestKey: string;
readonly method: PullRequestMergeMethod;
@@ -834,9 +845,10 @@ export function PullRequestDetailPanel({
)?.repositoryIdentity;
return gitHubPullRequestBrowserUrl(identity, reference.repository, reference.number);
}, [environmentId, projects, reference.number, reference.projectId, reference.repository]);
- // Project settings store the override under the sidebar group's key, which a duplicate row
+ // Project settings stored the override under the sidebar group's key, which a duplicate row
// borrows from its siblings, so the project alone does not always name the same key.
- const projectDefaultMergeMethod = useMemo(() => {
+ const legacyProjectDefaultMergeMethod = useMemo(() => {
+ if (projectDefaultMergeMethod !== undefined) return undefined;
const project = projects.find(
(candidate) =>
candidate.environmentId === environmentId && candidate.id === reference.projectId,
@@ -849,11 +861,12 @@ export function PullRequestDetailPanel({
primaryEnvironmentId,
}).get(derivePhysicalProjectKey(project)) ??
deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
- return mergeMethodOverrides[projectKey];
+ return legacyMergeMethodOverrides[projectKey];
}, [
environmentId,
- mergeMethodOverrides,
+ legacyMergeMethodOverrides,
primaryEnvironmentId,
+ projectDefaultMergeMethod,
projectGroupingSettings,
projects,
reference.projectId,
@@ -1327,7 +1340,7 @@ export function PullRequestDetailPanel({
const selectedMergeMethod = resolvePullRequestMergeMethod(
allowedMergeMethods,
currentMergeMethod,
- projectDefaultMergeMethod,
+ projectDefaultMergeMethod ?? legacyProjectDefaultMergeMethod,
lastSelectedMergeMethod,
);
const selectedMergeMethodLabel = PULL_REQUEST_MERGE_METHOD_LABELS[selectedMergeMethod];
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index ad766565117..41c0e9ec3b0 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -3133,7 +3133,10 @@ export function ConnectionsSettings() {
<SettingsPageContainer>
{canManageLocalBackend ? (
<>
- <SettingsSection {...searchableSetting("connections-environment")}>
+ <SettingsSection
+ {...searchableSetting("connections-environment")}
+ title={primaryEnvironment?.label ?? "Primary environment"}
+ >
{primaryVersionMismatch || primaryServerUpdateState.status !== "idle" ? (
<SettingsRow
title={
diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsx
index ec3bf854d7b..ab22c40b5c6 100644
--- a/apps/web/src/components/settings/DiagnosticsSettings.tsx
+++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx
@@ -7,12 +7,11 @@ import {
FolderOpenIcon,
InfoIcon,
} from "lucide-react";
-import { useAtomValue } from "@effect/atom-react";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
-import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import type {
ServerProcessDiagnosticsEntry,
ServerProcessResourceHistorySummary,
@@ -26,13 +25,8 @@ import { ensureLocalApi } from "../../localApi";
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";
import { useEnvironmentQuery } from "../../state/query";
-import {
- primaryServerAvailableEditorsAtom,
- primaryServerObservabilityAtom,
- serverEnvironment,
-} from "../../state/server";
+import { serverEnvironment } from "../../state/server";
import { shellEnvironment } from "../../state/shell";
-import { usePrimaryEnvironment } from "../../state/environments";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { Button } from "../ui/button";
import { ScrollArea } from "../ui/scroll-area";
@@ -43,6 +37,7 @@ import { ExpandableText } from "./ExpandableText";
import { ResourceTelemetryDiagnostics } from "./ResourceTelemetryDiagnostics";
import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
import { useAtomCommand } from "../../state/use-atom-command";
+import { useSettingsScope } from "./SettingsScopeContext";
const NUMBER_FORMAT = new Intl.NumberFormat();
@@ -776,10 +771,12 @@ function DiagnosticsRefreshButton({
}
export function DiagnosticsSettingsPanel() {
- const observability = useAtomValue(primaryServerObservabilityAtom);
- const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
- const primaryEnvironment = usePrimaryEnvironment();
- const environmentId = primaryEnvironment?.environmentId ?? null;
+ const { environment } = useSettingsScope();
+ // The boundary only mounts this page when the selection resolves to one
+ // connected environment, so the representative is the one to inspect.
+ const environmentId = environment?.environmentId ?? null;
+ const observability = environment?.serverConfig?.observability;
+ const availableEditors = environment?.serverConfig?.availableEditors;
const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {
reportFailure: false,
});
@@ -827,8 +824,15 @@ export function DiagnosticsSettingsPanel() {
const signalingPidRef = useRef<number | null>(null);
const environmentIdRef = useRef(environmentId);
const processDataRef = useRef(processData);
- environmentIdRef.current = environmentId;
- processDataRef.current = processData;
+ useEffect(() => {
+ processDataRef.current = processData;
+ }, [processData]);
+ useEffect(() => {
+ environmentIdRef.current = environmentId;
+ return () => {
+ environmentIdRef.current = null;
+ };
+ }, [environmentId]);
const openLogsDirectory = useCallback(() => {
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
@@ -868,6 +872,9 @@ export function DiagnosticsSettingsPanel() {
const isProcessInitialLoading = isProcessPending && processData === null;
const signalProcess = useCallback(
async (pid: number, signal: ServerProcessSignal) => {
+ const targetEnvironmentId = environmentIdRef.current;
+ const process = processDataRef.current?.processes.find((entry) => entry.pid === pid);
+ if (targetEnvironmentId === null || process === undefined) return;
if (signalingPidRef.current !== null) return;
signalingPidRef.current = pid;
setSignalingPid(pid);
@@ -896,20 +903,21 @@ export function DiagnosticsSettingsPanel() {
return;
}
}
- const currentEnvironmentId = environmentIdRef.current;
- if (currentEnvironmentId === null) {
+ if (environmentIdRef.current !== targetEnvironmentId) {
clearSignaling();
return;
}
- const process = processDataRef.current?.processes.find((entry) => entry.pid === pid);
- if (process === undefined) {
+ if (
+ processDataRef.current?.processes.find((entry) => entry.pid === pid)?.startTimeMs !==
+ process.startTimeMs
+ ) {
clearSignaling();
return;
}
try {
const result = await signalServerProcess({
- environmentId: currentEnvironmentId,
+ environmentId: targetEnvironmentId,
input: { pid, startTimeMs: process.startTimeMs, signal },
});
if (result._tag === "Failure") {
@@ -960,7 +968,7 @@ export function DiagnosticsSettingsPanel() {
return (
<SettingsPageContainer width="expanded" className="gap-10">
- <ResourceTelemetryDiagnostics />
+ <ResourceTelemetryDiagnostics environmentId={environmentId} />
<SettingsSection
title="Live Processes"
diff --git a/apps/web/src/components/settings/IntegrationsSettings.test.tsx b/apps/web/src/components/settings/IntegrationsSettings.test.tsx
index 4ef218430ae..9ecd469f310 100644
--- a/apps/web/src/components/settings/IntegrationsSettings.test.tsx
+++ b/apps/web/src/components/settings/IntegrationsSettings.test.tsx
@@ -38,6 +38,18 @@ vi.mock("./settingsLayout", async (importOriginal) => ({
...(await importOriginal<typeof import("./settingsLayout")>()),
SettingsPageContainer: ({ children }: { children: ReactNode }) => children,
}));
+// The scoped agent-access rows need the settings layout's scope provider;
+// this test covers the device-local browser sections only.
+vi.mock("./ProjectDefaultsSettings", () => ({ ProjectDefaultsSettings: () => null }));
+vi.mock("./SettingsScopeContext", () => ({
+ useSettingsScope: () => ({
+ scope: { kind: "all", environmentIds: [] },
+ environment: null,
+ connectedEnvironments: [],
+ targets: [],
+ }),
+ useOptionalSettingsScope: () => null,
+}));
import { IntegrationsSettingsPanel } from "./IntegrationsSettings";
import { platformSetupStatus } from "../device/DeviceSetup";
diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsx
index 8cb21532a42..188c3045fbc 100644
--- a/apps/web/src/components/settings/IntegrationsSettings.tsx
+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx
@@ -36,7 +36,6 @@ import {
type PreviewViewportSetting,
} from "@t3tools/contracts";
import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
-import { Link } from "@tanstack/react-router";
import { MoreVertical, Plus as PlusIcon } from "lucide-react";
import { useCallback, useRef, useState } from "react";
@@ -110,6 +109,8 @@ import {
SettingsSection,
} from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
+import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
+import { useSettingsScope } from "./SettingsScopeContext";
import { BrowserImportWizard, type WizardTarget } from "./BrowserImportWizard";
import type { ImportOutcome } from "./browserImportWizard.logic";
@@ -564,65 +565,22 @@ function BrowserLinkTargetSetting({ disabled }: { readonly disabled: boolean })
);
}
-function AgentBrowserAccessSetting() {
- return (
- <SettingsRow
- {...searchableSetting("agent-browser-access")}
- description="Choose whether agents can use the preview browser for all projects or a specific project."
- control={
- <Button
- render={
- <Link to="/settings/projects" search={{ project: undefined, machine: undefined }} />
- }
- size="sm"
- variant="outline"
- >
- Project settings
- </Button>
- }
- />
- );
-}
-
+/**
+ * Device support installs helper processes and hosts on one machine, so it
+ * follows the environment crumb. With several environments selected it shows
+ * the representative, named in the section title.
+ */
function DeviceIntegrationSettings() {
- const primaryEnvironment = usePrimaryEnvironment();
- const { environments } = useEnvironments();
- const [selectedId, setSelectedId] = useState<string | null>(null);
- const selected =
- environments.find((environment) => environment.environmentId === selectedId) ??
- environments.find(
- (environment) => environment.environmentId === primaryEnvironment?.environmentId,
- ) ??
- environments[0];
+ const { scope, environment: selected, connectedEnvironments } = useSettingsScope();
const connected = selected?.connection.phase === "connected" && selected.serverConfig !== null;
const environmentId = connected ? selected.environmentId : null;
+ const aggregate = scope.environmentIds.length !== 1 && connectedEnvironments.length > 1;
return (
- <SettingsSection id="devices" title="Devices">
- {environments.length > 1 ? (
- <SettingsRow
- title="Environment"
- description="Device support and hosts are shared by all projects in this environment."
- control={
- <Select
- value={selected?.environmentId ?? ""}
- onValueChange={(value) => setSelectedId(value)}
- >
- <SelectTrigger size="sm" aria-label="Device environment">
- <SelectValue>{selected?.label ?? "Select environment"}</SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- {environments.map((environment) => (
- <SelectItem key={environment.environmentId} value={environment.environmentId}>
- {environment.label}
- {environment.connection.phase === "connected" ? "" : " · Offline"}
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- }
- />
- ) : null}
+ <SettingsSection
+ id="devices"
+ title={aggregate && selected ? `Devices · ${selected.label}` : "Devices"}
+ >
<DeviceIntegrationControls
key={selected?.environmentId ?? "none"}
environmentId={environmentId}
@@ -1339,11 +1297,10 @@ export function IntegrationsSettingsPanel() {
return (
<SettingsPageContainer>
+ {/* Server-authoritative agent access is scoped by the header selection;
+ the preview defaults below are device-local and ignore it. */}
+ <ProjectDefaultsSettings category="integrations" />
<SettingsSection id="browser" title="Browser">
- {/* Server-authoritative, so it stays editable on any client anchored to
- a server; `serverScoped` covers the hosted app, which has none. It
- sits outside the block covering the desktop-only defaults. */}
- <AgentBrowserAccessSetting />
{previewDefaultsDisabled ? (
<SettingsUnavailableGroup message="Only available in the desktop app.">
{previewDefaults}
diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx
index ad99328647a..85e32b1bf85 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.tsx
+++ b/apps/web/src/components/settings/KeybindingsSettings.tsx
@@ -26,7 +26,7 @@ import {
type ServerRemoveKeybindingInput,
type ServerUpsertKeybindingInput,
} from "@t3tools/contracts";
-import { useAtomValue } from "@effect/atom-react";
+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -36,13 +36,8 @@ import { isElectron } from "../../env";
import { useOpenInPreferredEditor } from "../../editorPreferences";
import { formatShortcutLabel } from "../../keybindings";
import { cn } from "../../lib/utils";
-import {
- primaryServerAvailableEditorsAtom,
- primaryServerKeybindingsAtom,
- primaryServerKeybindingsConfigPathAtom,
- serverEnvironment,
-} from "../../state/server";
-import { usePrimaryEnvironment } from "../../state/environments";
+import { serverEnvironment } from "../../state/server";
+import { useSettingsScope } from "./SettingsScopeContext";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
@@ -1335,10 +1330,13 @@ function BrowserKeybindingNotice() {
}
export function KeybindingsSettingsPanel() {
- const keybindings = useAtomValue(primaryServerKeybindingsAtom);
- const keybindingsConfigPath = useAtomValue(primaryServerKeybindingsConfigPathAtom);
- const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
- const primaryEnvironment = usePrimaryEnvironment();
+ // The representative environment supplies the displayed bindings; edits
+ // fan out to every connected environment in the selection, so one
+ // shortcut change reaches each machine the user runs T3 Code on.
+ const { environment: primaryEnvironment, connectedEnvironments } = useSettingsScope();
+ const keybindings = primaryEnvironment?.serverConfig?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS;
+ const keybindingsConfigPath = primaryEnvironment?.serverConfig?.keybindingsConfigPath ?? null;
+ const availableEditors = primaryEnvironment?.serverConfig?.availableEditors ?? [];
const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
reportFailure: false,
});
@@ -1411,17 +1409,19 @@ export function KeybindingsSettingsPanel() {
...(input.replace ? { replace: input.replace } : {}),
};
void (async () => {
- const result = await upsertKeybinding({
- environmentId: primaryEnvironment.environmentId,
- input: payload,
- });
+ const results = await Promise.all(
+ connectedEnvironments.map((target) =>
+ upsertKeybinding({ environmentId: target.environmentId, input: payload }),
+ ),
+ );
setSavingCommand(null);
- if (result._tag === "Success") {
+ const failed = results.find((result) => result._tag === "Failure");
+ if (!failed) {
setIsAddingBinding(false);
return;
}
- if (!isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
+ if (!isAtomCommandInterrupted(failed)) {
+ const error = squashAtomCommandFailure(failed);
toastManager.add({
title: "Unable to save keybinding",
description: error instanceof Error ? error.message : "The keybinding was not saved.",
@@ -1430,7 +1430,7 @@ export function KeybindingsSettingsPanel() {
}
})();
},
- [primaryEnvironment, upsertKeybinding],
+ [connectedEnvironments, primaryEnvironment, upsertKeybinding],
);
const removeKeybinding = useCallback(
@@ -1438,12 +1438,17 @@ export function KeybindingsSettingsPanel() {
if (!primaryEnvironment) return;
setSavingCommand(row.command);
void (async () => {
- const result = await removeKeybindingMutation({
- environmentId: primaryEnvironment.environmentId,
- input: rowKeybindingTarget(row),
- });
+ const results = await Promise.all(
+ connectedEnvironments.map((target) =>
+ removeKeybindingMutation({
+ environmentId: target.environmentId,
+ input: rowKeybindingTarget(row),
+ }),
+ ),
+ );
setSavingCommand(null);
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const result = results.find((entry) => entry._tag === "Failure") ?? results[0];
+ if (result?._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add({
title: "Unable to remove keybinding",
@@ -1453,7 +1458,7 @@ export function KeybindingsSettingsPanel() {
}
})();
},
- [primaryEnvironment, removeKeybindingMutation],
+ [connectedEnvironments, primaryEnvironment, removeKeybindingMutation],
);
const resetKeybinding = useCallback(
diff --git a/apps/web/src/components/settings/ProjectActionsSettings.tsx b/apps/web/src/components/settings/ProjectActionsSettings.tsx
new file mode 100644
index 00000000000..aa4d7077ff6
--- /dev/null
+++ b/apps/web/src/components/settings/ProjectActionsSettings.tsx
@@ -0,0 +1,226 @@
+import { EnvironmentId, type T3ProjectFileScript } from "@t3tools/contracts";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
+import { ChevronDownIcon, PlusIcon } from "lucide-react";
+import { useCallback, useMemo, useState } from "react";
+import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts";
+import { useEnvironments } from "../../state/environments";
+import {
+ EMPTY_PROJECT_SCRIPT_INPUT,
+ editorRequestForScript,
+ ProjectScriptEditorDialog,
+ ScriptIcon,
+ type NewProjectScriptInput,
+ type ProjectScriptEditorRequest,
+} from "../projectScriptEditor";
+import { Button } from "../ui/button";
+import {
+ Menu,
+ MenuGroup,
+ MenuGroupLabel,
+ MenuItem,
+ MenuPopup,
+ MenuSeparator,
+ MenuTrigger,
+} from "../ui/menu";
+import { ProjectActionsList } from "./ProjectActionsList";
+import { useProjectScriptSettings } from "./useProjectScriptSettings";
+import { SettingsRow, SettingsSection } from "./settingsLayout";
+import { useSettingsScope } from "./SettingsScopeContext";
+
+/**
+ * A project's actions on each selected environment. Actions belong to a
+ * project, so this only renders at a project scope; the environment's
+ * `defaultProjectScripts` is the layer a project without its own list
+ * inherits. Shortcuts are environment-wide, so the same action id shares its
+ * binding on an environment.
+ */
+export function ProjectActionsSettings() {
+ const { scope, targets, target } = useSettingsScope();
+ const { environments } = useEnvironments();
+ const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
+ const representativeConfig = target
+ ? environments.find((environment) => environment.environmentId === target.environmentId)
+ ?.serverConfig
+ : undefined;
+ const scripts = target?.settings.defaultProjectScripts ?? [];
+ const keybindings = representativeConfig?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS;
+ const mixed = targets.some(
+ (candidate) =>
+ JSON.stringify(candidate.settings.defaultProjectScripts) !== JSON.stringify(scripts),
+ );
+ const [request, setRequest] = useState<ProjectScriptEditorRequest | null>(null);
+ const memberById = new Map(
+ isProjectScope ? scope.members.map((member) => [member.id, member]) : [],
+ );
+ const { saving, persist, submit } = useProjectScriptSettings(
+ targets.flatMap((candidate) => {
+ const environment = environments.find(
+ (entry) => entry.environmentId === candidate.environmentId,
+ );
+ if (!environment?.serverConfig) return [];
+ const member = candidate.projectId ? memberById.get(candidate.projectId) : undefined;
+ // An older server ignores the override record, so a project edit there
+ // would report success and vanish; such environments are left out and
+ // the legacy per-project map keeps serving them.
+ if (
+ member &&
+ environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
+ ) {
+ return [];
+ }
+ return [
+ {
+ environmentId: candidate.environmentId,
+ // Writes read the raw environment settings so an override entry is
+ // extended, not derived from already-resolved values.
+ settings: environment.serverConfig.settings,
+ keybindings: environment.serverConfig.keybindings,
+ ...(member ? { project: member } : {}),
+ },
+ ];
+ }),
+ );
+
+ // A project's t3.json can declare actions to import. Read it from the
+ // representative checkout; the imported action still fans out.
+ const representativeMember = target?.projectId ? memberById.get(target.projectId) : undefined;
+ const t3File = useT3ProjectFileState(
+ representativeMember?.environmentId ?? EnvironmentId.make("none"),
+ representativeMember?.workspaceRoot ?? null,
+ );
+ const importableScripts = useMemo(
+ () =>
+ t3File.scripts.filter(
+ (fileScript) =>
+ !scripts.some(
+ (script) =>
+ script.command === fileScript.command ||
+ script.name.toLowerCase() === fileScript.name.toLowerCase(),
+ ),
+ ),
+ [scripts, t3File.scripts],
+ );
+ const importFileScript = useCallback(
+ async (fileScript: T3ProjectFileScript) => {
+ const payload: NewProjectScriptInput = {
+ name: fileScript.name,
+ command: fileScript.command,
+ icon: fileScript.icon ?? "play",
+ runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
+ keybinding: null,
+ previewUrl: fileScript.previewUrl ?? null,
+ autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
+ };
+ const result = await submit(null, payload);
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ setRequest({
+ scriptId: null,
+ initial: payload,
+ error: error instanceof Error ? error.message : "Failed to import action.",
+ });
+ }
+ },
+ [submit],
+ );
+
+ return (
+ <SettingsSection id="project-actions" title="Actions">
+ <SettingsRow
+ serverScoped
+ settingKeys={["defaultProjectScripts"]}
+ mixed={mixed}
+ title="Actions"
+ description="Commands that run in this project's checkout or its worktree, with optional shortcuts."
+ onResetOverride={() => void persist(() => null)}
+ control={
+ <div className="flex flex-wrap items-center gap-1.5">
+ {importableScripts.length > 0 ? (
+ <Menu>
+ <MenuTrigger
+ render={
+ <Button
+ id="import-scripts"
+ size="xs"
+ variant="ghost"
+ disabled={saving}
+ type="button"
+ />
+ }
+ >
+ Import scripts
+ <ChevronDownIcon className="size-3.5" />
+ </MenuTrigger>
+ <MenuPopup align="end" className="w-72">
+ <MenuGroup>
+ <MenuGroupLabel>Import from t3.json</MenuGroupLabel>
+ <p className="px-2 pb-2 text-pretty text-sm text-muted-foreground">
+ Add actions declared by this checkout without editing them first.
+ </p>
+ </MenuGroup>
+ <MenuSeparator />
+ {importableScripts.map((fileScript) => (
+ <MenuItem
+ key={`${fileScript.name} ${fileScript.command}`}
+ onClick={() => void importFileScript(fileScript)}
+ >
+ <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">{fileScript.name}</div>
+ <div className="truncate font-mono text-muted-foreground">
+ {fileScript.command}
+ </div>
+ </div>
+ </MenuItem>
+ ))}
+ </MenuPopup>
+ </Menu>
+ ) : null}
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={saving || targets.length === 0}
+ onClick={() => setRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT })}
+ >
+ <PlusIcon className="size-3.5" />
+ Add action
+ </Button>
+ </div>
+ }
+ />
+ {mixed ? (
+ <SettingsRow
+ title="Different actions across environments"
+ description="Choose one environment to edit its list. Adding an action here adds it on every selected environment."
+ />
+ ) : (
+ <ProjectActionsList
+ scripts={scripts}
+ keybindings={keybindings}
+ disabled={saving}
+ onEdit={(script) => setRequest(editorRequestForScript(script, keybindings))}
+ />
+ )}
+ {t3File.status === "invalid" ? (
+ <SettingsRow
+ title="t3.json is invalid"
+ description="A t3.json exists in this checkout but fails to parse, so every action and icon it declares is ignored. Check the JSON syntax and icon values."
+ className="text-warning"
+ />
+ ) : null}
+ <ProjectScriptEditorDialog
+ request={request}
+ scripts={scripts}
+ onSubmit={submit}
+ onDelete={(id) =>
+ void persist((current) => current.filter((script) => script.id !== id), id, null)
+ }
+ onClose={() => setRequest(null)}
+ />
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/components/settings/ProjectDefaultActionsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultActionsSettings.tsx
deleted file mode 100644
index 4385a5901b5..00000000000
--- a/apps/web/src/components/settings/ProjectDefaultActionsSettings.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import type { EnvironmentId } from "@t3tools/contracts";
-import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
-import { PlusIcon } from "lucide-react";
-import { useState } from "react";
-import { useEnvironments } from "../../state/environments";
-import {
- EMPTY_PROJECT_SCRIPT_INPUT,
- editorRequestForScript,
- ProjectScriptEditorDialog,
- type ProjectScriptEditorRequest,
-} from "../projectScriptEditor";
-import { Button } from "../ui/button";
-import { ProjectActionsList } from "./ProjectActionsList";
-import { useProjectScriptSettings } from "./ProjectSettingsPanel";
-import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout";
-
-export function ProjectDefaultActionsSettings({
- environmentId,
-}: {
- environmentId: EnvironmentId | null;
-}) {
- const { environments } = useEnvironments();
- const targets = environments.filter(
- (environment) =>
- (environmentId === null || environment.environmentId === environmentId) &&
- environment.connection.phase === "connected" &&
- environment.serverConfig !== null,
- );
- const representative = targets[0]?.serverConfig;
- const scripts = representative?.settings.defaultProjectScripts ?? [];
- const keybindings = representative?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS;
- const mixed = targets.some(
- (target) =>
- JSON.stringify(target.serverConfig?.settings.defaultProjectScripts) !==
- JSON.stringify(scripts),
- );
- const [request, setRequest] = useState<ProjectScriptEditorRequest | null>(null);
- const { saving, persist, submit } = useProjectScriptSettings(
- targets.flatMap(({ environmentId, serverConfig }) =>
- serverConfig
- ? [
- {
- environmentId,
- settings: serverConfig.settings,
- keybindings: serverConfig.keybindings,
- },
- ]
- : [],
- ),
- );
-
- return (
- <SettingsSection title="Actions">
- <SettingsRow
- title="Import scripts"
- aria-disabled
- description="Select a project to import actions from its checkout's t3.json."
- control={
- <Button size="xs" variant="ghost" disabled>
- Import scripts
- </Button>
- }
- />
- <SettingsRow
- title="Default actions"
- description="Available in every inheriting checkout. Commands run in that checkout or its worktree."
- resetAction={
- targets.some(
- (target) => (target.serverConfig?.settings.defaultProjectScripts.length ?? 0) > 0,
- ) ? (
- <SettingResetButton
- label="default actions"
- disabled={saving}
- onClick={() => void persist(() => [])}
- />
- ) : null
- }
- control={
- <Button
- size="xs"
- variant="outline"
- disabled={saving || targets.length === 0}
- onClick={() => setRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT })}
- >
- <PlusIcon className="size-3.5" />
- Add action
- </Button>
- }
- />
- {mixed ? (
- <SettingsRow
- title="Different actions across machines"
- description="Select a machine to edit its actions. Adding an action applies to all selected connected machines."
- />
- ) : (
- <ProjectActionsList
- scripts={scripts}
- keybindings={keybindings}
- disabled={saving}
- onEdit={(script) => setRequest(editorRequestForScript(script, keybindings))}
- />
- )}
- <ProjectScriptEditorDialog
- request={request}
- scripts={scripts}
- onSubmit={submit}
- onDelete={(id) =>
- void persist((current) => current.filter((script) => script.id !== id), id, null)
- }
- onClose={() => setRequest(null)}
- />
- </SettingsSection>
- );
-}
diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx
index 938000e0100..bb2c3e99bbb 100644
--- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx
+++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx
@@ -1,17 +1,13 @@
import {
- DEFAULT_CLIENT_SETTINGS,
DEFAULT_SERVER_SETTINGS,
- type EnvironmentId,
+ EnvironmentId,
type ModelSelection,
type ProviderInstanceId,
- type ServerSettingsPatch,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { useNavigate } from "@tanstack/react-router";
-import { useRef, useState } from "react";
-import { Trash2Icon } from "lucide-react";
-import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
+import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts";
import { getCustomModelOptionsByInstance } from "../../modelSelection";
import {
applyProviderInstanceSettings,
@@ -19,59 +15,47 @@ import {
resolveDefaultProviderModelSelection,
sortProviderInstanceEntries,
} from "../../providerInstances";
-import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
-import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
-import { useAtomCommand } from "../../state/use-atom-command";
+import { useEnvironments } from "../../state/environments";
+import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
import { resolveEnvModeLabel } from "../BranchToolbar.logic";
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
+import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDetail.logic";
import { TraitsPicker } from "../chat/TraitsPicker";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { toastManager } from "../ui/toast";
import { Switch } from "../ui/switch";
-import { Button } from "../ui/button";
-import { Input } from "../ui/input";
-import { PROJECT_GROUPING_MODE_LABELS } from "./ProjectSettingsPanel";
-import { ProjectDefaultActionsSettings } from "./ProjectDefaultActionsSettings";
+import type { ProjectSettingsCategory } from "./ProjectSettingsPanel";
import { searchableSetting } from "./settingsSearch";
+import { useSettingsScope } from "./SettingsScopeContext";
import {
SETTINGS_PICKER_TRIGGER_CLASSNAME,
SettingResetButton,
- SettingsPageContainer,
SettingsRow,
SettingsSection,
} from "./settingsLayout";
+import {
+ useScopedSettings,
+ useScopedSettingsMixed,
+ useScopedSettingSource,
+ useUpdateScopedSettings,
+} from "./useScopedSettings";
-/** Defaults are written only to the machines selected on the projects settings page. */
-export function ProjectDefaultsSettings({
- environmentId,
-}: {
- environmentId: EnvironmentId | null;
-}) {
- const { environments } = useEnvironments();
- const primaryEnvironmentId = usePrimaryEnvironmentId();
- const clientSettings = useClientSettings();
- const updateClientSettings = useUpdateClientSettings();
+/**
+ * Rows for the settings a project may override. The same rows edit
+ * environment defaults at an environment scope and project overrides at a
+ * project or checkout scope; the scoped hooks route the write.
+ */
+export function ProjectDefaultsSettings({ category }: { category: ProjectSettingsCategory }) {
+ const { scope, target, targets, connectedEnvironments } = useSettingsScope();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const navigate = useNavigate();
- const updateSettings = useAtomCommand(
- serverEnvironment.updateSettings,
- "project defaults update",
- );
- const savingRef = useRef(new Set<string>());
- const [saving, setSaving] = useState<ReadonlySet<string>>(new Set());
- const scoped = environments.filter(
- (environment) => environmentId === null || environment.environmentId === environmentId,
- );
- const targets = scoped.filter(
- (environment) =>
- environment.connection.phase === "connected" && environment.serverConfig !== null,
- );
- const representative =
- targets.find((environment) => environment.environmentId === primaryEnvironmentId) ?? targets[0];
- const serverSettings = representative?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS;
+ const { environments } = useEnvironments();
+ const representative = target
+ ? environments.find((environment) => environment.environmentId === target.environmentId)
+ : undefined;
const providers = representative?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
- const settings = { ...serverSettings, ...clientSettings };
- const storedSelection = serverSettings.defaultModelSelection;
- const selection = resolveDefaultProviderModelSelection(providers, storedSelection);
+ const selection = resolveDefaultProviderModelSelection(providers, settings.defaultModelSelection);
const entries = sortProviderInstanceEntries(
applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
);
@@ -82,36 +66,46 @@ export function ProjectDefaultsSettings({
selection?.model,
);
const activeEntry = entries.find((entry) => entry.instanceId === selection?.instanceId);
- const mixedModel = targets.some(
- (target) =>
- JSON.stringify(target.serverConfig?.settings.defaultModelSelection) !==
- JSON.stringify(storedSelection),
- );
- const mixedWorkspace = targets.some(
- (target) =>
- target.serverConfig?.settings.defaultThreadEnvMode !== serverSettings.defaultThreadEnvMode,
- );
- const mixedBrowser = targets.some(
- (target) =>
- target.serverConfig?.settings.enableAgentBrowserAccess !==
- serverSettings.enableAgentBrowserAccess,
- );
- const disabled = (key: keyof ServerSettingsPatch) => targets.length === 0 || saving.has(key);
- const mixedAutoPull = targets.some(
- (target) => target.serverConfig?.settings.defaultAutoPull !== serverSettings.defaultAutoPull,
+ const mixedModel = useScopedSettingsMixed(["defaultModelSelection"]);
+ const mixedWorkspace = useScopedSettingsMixed(["defaultThreadEnvMode"]);
+ const mixedBrowser = useScopedSettingsMixed(["enableAgentBrowserAccess"]);
+ 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;
function modelDisabledReason(instanceId: ProviderInstanceId, model: string): string | null {
const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
- for (const target of targets) {
- const config = target.serverConfig;
+ for (const candidate of targets) {
+ const environment = environments.find(
+ (entry) => entry.environmentId === candidate.environmentId,
+ );
+ const config = environment?.serverConfig;
if (!config) continue;
const entry = applyProviderInstanceSettings(
deriveProviderInstanceEntries(config.providers),
- config.settings,
- ).find((candidate) => candidate.instanceId === instanceId);
+ candidate.settings,
+ ).find((option) => option.instanceId === instanceId);
const options = getCustomModelOptionsByInstance(
- { ...config.settings, ...clientSettings },
+ { ...settings, ...candidate.settings },
config.providers,
).get(instanceId);
if (
@@ -120,355 +114,282 @@ export function ProjectDefaultsSettings({
entry.driverKind !== sourceEntry?.driverKind ||
!options?.some((option) => option.slug === model && !option.isUnavailable)
) {
- return `This model is unavailable on ${target.label}. Select that machine to choose its default separately.`;
+ return `This model is unavailable on ${environment?.label ?? "a selected environment"}. Select that environment to choose its model separately.`;
}
}
return null;
}
- async function save(patch: ServerSettingsPatch) {
- const keys = Object.keys(patch);
- if (targets.length === 0 || keys.some((key) => savingRef.current.has(key))) return;
- const nextModel = patch.defaultModelSelection;
- const reason = nextModel ? modelDisabledReason(nextModel.instanceId, nextModel.model) : null;
+ const setModel = (value: ModelSelection | null) => {
+ const reason = value ? modelDisabledReason(value.instanceId, value.model) : null;
if (reason) {
toastManager.add({ type: "error", title: "Default model not saved", description: reason });
return;
}
- for (const key of keys) savingRef.current.add(key);
- setSaving(new Set(savingRef.current));
- try {
- const results = await Promise.all(
- targets.map((target) =>
- updateSettings({ environmentId: target.environmentId, input: { patch } }),
- ),
- );
- const failedTargets = targets.filter((_, index) => results[index]?._tag === "Failure");
- if (failedTargets.length > 0) {
- toastManager.add({
- type: "error",
- title: "Project defaults not saved on every machine",
- description: `Could not update ${failedTargets.map((target) => target.label).join(", ")}. Other machines may have saved the change.`,
- });
- }
- } finally {
- for (const key of keys) savingRef.current.delete(key);
- setSaving(new Set(savingRef.current));
- }
- }
+ updateSettings({ defaultModelSelection: value });
+ };
- const setModel = (value: ModelSelection | null) => void save({ defaultModelSelection: value });
return (
- <SettingsPageContainer>
- <SettingsSection
- id={searchableSetting("project-defaults").id}
- title="Project defaults"
- hideTitle
- >
- <SettingsRow
- title="Name"
- aria-disabled
- description="Select a project to change its name."
- control={
- <Input
- size="sm"
- className="w-full sm:w-64"
- aria-label="Project name"
- placeholder="Select a project"
- disabled
- />
- }
- />
- <SettingsRow
- title="Project icon"
- aria-disabled
- description="Select a project to change its icon."
- control={
- <div className="flex items-center gap-2">
- <Button size="sm" variant="outline" disabled>
- Choose icon
- </Button>
- <Button size="sm" variant="outline" disabled>
- Choose file
- </Button>
- </div>
- }
- />
- {scoped.length > targets.length || targets.length === 0 ? (
- <p role="status" className="px-4 py-3 text-sm text-muted-foreground">
- {targets.length === 0
- ? "Connect a machine to change its project defaults."
- : "Changes apply to connected machines only. Offline machines keep their current defaults."}
- </p>
- ) : null}
- <SettingsRow
- title="Model"
- description="Default model for new threads. Projects can override it."
- status={
- targets.length === 0
- ? undefined
- : mixedModel
- ? "Differs by machine"
- : storedSelection === null
+ <SettingsSection
+ id={
+ category === "general"
+ ? "project-defaults"
+ : category === "integrations"
+ ? "browser-access"
+ : "source-control-defaults"
+ }
+ title={
+ category === "general"
+ ? "New threads"
+ : category === "integrations"
+ ? "Browser"
+ : "Repositories"
+ }
+ >
+ {category === "general" ? (
+ <>
+ <SettingsRow
+ serverScoped
+ settingKeys={["defaultModelSelection"]}
+ mixed={mixedModel}
+ id="default-model"
+ title="Model"
+ description={
+ isProjectScope
+ ? "Model for new threads in this project."
+ : "Default model for new threads. Projects can override it."
+ }
+ status={
+ unavailable || mixedModel || modelSource === "project"
+ ? undefined
+ : settings.defaultModelSelection === null
? "Automatic"
: undefined
- }
- resetAction={
- storedSelection !== null || mixedModel ? (
- <SettingResetButton
- label="default model"
- disabled={disabled("defaultModelSelection")}
- onClick={() => setModel(null)}
- />
- ) : null
- }
- control={
- selection && activeEntry ? (
- <fieldset
- disabled={disabled("defaultModelSelection")}
- className="flex min-w-0 flex-wrap items-center justify-end gap-1.5 disabled:opacity-50"
- >
- <ProviderModelPicker
- activeInstanceId={selection.instanceId}
- model={selection.model}
- lockedProvider={null}
- instanceEntries={entries}
- modelOptionsByInstance={modelOptions}
- disabled={disabled("defaultModelSelection")}
- triggerVariant="outline"
- triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
- getModelDisabledReason={modelDisabledReason}
- onOpenProviderSetup={(instanceId) => {
- if (representative)
- void navigate({
- to: "/settings/providers",
- search: { environmentId: representative.environmentId, instanceId },
- });
- }}
- onInstanceModelChange={(instanceId, model) =>
- setModel(createModelSelection(instanceId, model))
- }
- />
- {!mixedModel ? (
- <TraitsPicker
- provider={activeEntry.driverKind}
- models={activeEntry.models}
+ }
+ resetAction={
+ settings.defaultModelSelection !== null ? (
+ <SettingResetButton label="default model" onClick={() => setModel(null)} />
+ ) : null
+ }
+ control={
+ selection && activeEntry ? (
+ <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
+ <ProviderModelPicker
+ activeInstanceId={selection.instanceId}
model={selection.model}
- prompt=""
- onPromptChange={() => {}}
- modelOptions={selection.options ?? []}
- allowPromptInjectedEffort={false}
- planModeEnabled={settings.planModeEnabled}
+ lockedProvider={null}
+ instanceEntries={entries}
+ modelOptionsByInstance={modelOptions}
triggerVariant="outline"
triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
- onModelOptionsChange={(options) =>
- setModel(createModelSelection(selection.instanceId, selection.model, options))
+ {...(mixedModel ? { triggerLabel: "Mixed" } : {})}
+ getModelDisabledReason={modelDisabledReason}
+ onOpenProviderSetup={(instanceId) => {
+ if (representative)
+ void navigate({
+ to: "/settings/providers",
+ search: { environmentId: representative.environmentId, instanceId },
+ });
+ }}
+ onInstanceModelChange={(instanceId, model) =>
+ setModel(createModelSelection(instanceId, model))
}
/>
- ) : null}
- </fieldset>
- ) : (
- <span className="text-sm text-muted-foreground">No providers available</span>
- )
- }
- />
- <SettingsRow
- id={searchableSetting("new-threads").id}
- title="Workspace"
- description="Where new threads start, unless overridden by the project or t3.json."
- resetAction={
- mixedWorkspace ||
- serverSettings.defaultThreadEnvMode !== DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode ? (
- <SettingResetButton
- label="default workspace"
- disabled={disabled("defaultThreadEnvMode")}
- onClick={() =>
- void save({ defaultThreadEnvMode: DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode })
- }
- />
- ) : null
- }
- control={
- <Select
- disabled={disabled("defaultThreadEnvMode")}
- value={mixedWorkspace ? "mixed" : serverSettings.defaultThreadEnvMode}
- onValueChange={(value) => {
- if (value === "local" || value === "worktree")
- void save({ defaultThreadEnvMode: value });
- }}
- >
- <SelectTrigger size="sm" aria-label="Default workspace">
- <SelectValue>
- {targets.length === 0
- ? "Unavailable"
- : mixedWorkspace
- ? "Differs by machine"
- : resolveEnvModeLabel(serverSettings.defaultThreadEnvMode)}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
- <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
- </SelectPopup>
- </Select>
- }
- />
- <SettingsRow
- title="Automatically pull"
- description="Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
- status={mixedAutoPull ? "Differs by machine" : undefined}
- resetAction={
- serverSettings.defaultAutoPull || mixedAutoPull ? (
- <SettingResetButton
- label="default automatic pull"
- tooltip="Reset automatic pull to off"
- disabled={disabled("defaultAutoPull")}
- onClick={() => void save({ defaultAutoPull: false })}
+ {!mixedModel ? (
+ <TraitsPicker
+ provider={activeEntry.driverKind}
+ models={activeEntry.models}
+ model={selection.model}
+ prompt=""
+ onPromptChange={() => {}}
+ modelOptions={selection.options ?? []}
+ allowPromptInjectedEffort={false}
+ planModeEnabled={settings.planModeEnabled}
+ triggerVariant="outline"
+ triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
+ onModelOptionsChange={(options) =>
+ setModel(
+ createModelSelection(selection.instanceId, selection.model, options),
+ )
+ }
+ />
+ ) : null}
+ </div>
+ ) : (
+ <span className="text-sm text-muted-foreground">No providers available</span>
+ )
+ }
+ />
+ <SettingsRow
+ serverScoped
+ settingKeys={["defaultThreadEnvMode"]}
+ mixed={mixedWorkspace}
+ id={searchableSetting("new-threads").id}
+ 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
+ }
+ resetAction={
+ settings.defaultThreadEnvMode !== DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode ? (
+ <SettingResetButton
+ label="default workspace"
+ onClick={() =>
+ updateSettings({
+ defaultThreadEnvMode: DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode,
+ })
+ }
+ />
+ ) : null
+ }
+ control={
+ <Select
+ value={mixedWorkspace ? null : settings.defaultThreadEnvMode}
+ onValueChange={(value) => {
+ if (value === "local" || value === "worktree")
+ updateSettings({ defaultThreadEnvMode: value });
+ }}
+ >
+ <SelectTrigger size="sm" aria-label="Default workspace">
+ <SelectValue>
+ {(value: string | null) =>
+ value === "local" || value === "worktree"
+ ? resolveEnvModeLabel(value)
+ : unavailable
+ ? "Unavailable"
+ : "Mixed"
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
+ <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
+ </SelectPopup>
+ </Select>
+ }
+ />
+ </>
+ ) : category === "source-control" ? (
+ <>
+ <SettingsRow
+ serverScoped
+ settingKeys={["defaultAutoPull"]}
+ mixed={mixedAutoPull}
+ id="automatic-pull"
+ title="Automatically pull"
+ description={
+ isProjectScope
+ ? "Keeps this project's default branch current when the checkout has no local changes or commits."
+ : "Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
+ }
+ resetAction={
+ settings.defaultAutoPull ? (
+ <SettingResetButton
+ label="default automatic pull"
+ tooltip="Reset automatic pull to off"
+ onClick={() => updateSettings({ defaultAutoPull: false })}
+ />
+ ) : null
+ }
+ control={
+ <Switch
+ aria-label="Default automatic pull"
+ mixed={mixedAutoPull}
+ checked={mixedAutoPull ? false : settings.defaultAutoPull}
+ onCheckedChange={(enabled) => updateSettings({ defaultAutoPull: enabled })}
/>
- ) : null
- }
- control={
- <Switch
- aria-label="Default automatic pull"
- checked={serverSettings.defaultAutoPull}
- disabled={disabled("defaultAutoPull")}
- onCheckedChange={(enabled) => void save({ defaultAutoPull: enabled })}
- />
- }
- />
- <SettingsRow
- id={searchableSetting("agent-browser-access").id}
- title="Agent browser access"
- description="Allow agents to use the shared browser. Projects can override it."
- resetAction={
- mixedBrowser ||
- serverSettings.enableAgentBrowserAccess !==
+ }
+ />
+ <SettingsRow
+ serverScoped
+ settingKeys={["pullRequestMergeMethod"]}
+ mixed={mixedMergeMethod}
+ {...searchableSetting("pull-request-merge-method")}
+ description={
+ isProjectScope
+ ? "Pull requests in this project start with this method."
+ : "Pull requests start with this method. Last selected reuses whatever you chose most recently on this device."
+ }
+ resetAction={
+ settings.pullRequestMergeMethod !== null ? (
+ <SettingResetButton
+ label="default merge method"
+ tooltip="Reset to last selected"
+ onClick={() => updateSettings({ pullRequestMergeMethod: null })}
+ />
+ ) : null
+ }
+ control={
+ <Select
+ value={mixedMergeMethod ? null : (settings.pullRequestMergeMethod ?? "last")}
+ onValueChange={(value) => {
+ if (value === "last") updateSettings({ pullRequestMergeMethod: null });
+ else if (value === "merge" || value === "squash" || value === "rebase")
+ updateSettings({ pullRequestMergeMethod: value });
+ }}
+ >
+ <SelectTrigger size="sm" aria-label="Default pull request merge method">
+ <SelectValue>
+ {(value: string | null) =>
+ value === "merge" || value === "squash" || value === "rebase"
+ ? PULL_REQUEST_MERGE_METHOD_LABELS[value]
+ : value === "last"
+ ? "Last selected"
+ : "Mixed"
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem value="last">Last selected</SelectItem>
+ <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
+ <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
+ <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
+ </SelectPopup>
+ </Select>
+ }
+ />
+ </>
+ ) : (
+ <>
+ <SettingsRow
+ serverScoped
+ settingKeys={["enableAgentBrowserAccess"]}
+ mixed={mixedBrowser}
+ id={searchableSetting("agent-browser-access").id}
+ title="Agent browser access"
+ description={
+ isProjectScope
+ ? "Allow agents in this project to use the shared browser. Applies when the agent session next starts."
+ : "Allow agents to use the shared browser. Projects can override it."
+ }
+ resetAction={
+ settings.enableAgentBrowserAccess !==
DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess ? (
- <SettingResetButton
- label="default browser access"
- disabled={disabled("enableAgentBrowserAccess")}
- onClick={() =>
- void save({
- enableAgentBrowserAccess: DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess,
- })
- }
- />
- ) : null
- }
- control={
- <Select
- disabled={disabled("enableAgentBrowserAccess")}
- value={
- mixedBrowser
- ? "mixed"
- : serverSettings.enableAgentBrowserAccess
- ? "enabled"
- : "disabled"
- }
- onValueChange={(value) => {
- if (value === "enabled" || value === "disabled")
- void save({ enableAgentBrowserAccess: value === "enabled" });
- }}
- >
- <SelectTrigger size="sm" aria-label="Default agent browser access">
- <SelectValue>
- {targets.length === 0
- ? "Unavailable"
- : mixedBrowser
- ? "Differs by machine"
- : serverSettings.enableAgentBrowserAccess
- ? "Enabled"
- : "Disabled"}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- <SelectItem value="enabled">Enabled</SelectItem>
- <SelectItem value="disabled">Disabled</SelectItem>
- </SelectPopup>
- </Select>
- }
- />
- </SettingsSection>
- <SettingsSection title="Checkout">
- <SettingsRow
- title="Checkout"
- aria-disabled
- description="Select a project to choose one of its checkouts."
- control={
- <Select disabled>
- <SelectTrigger size="sm" aria-label="Checkout">
- <SelectValue placeholder="Select a project" />
- </SelectTrigger>
- </Select>
- }
- />
- <SettingsRow
- title="Project grouping"
- description="Default grouping across all machines in this client. Individual checkout overrides are preserved."
- resetAction={
- clientSettings.sidebarProjectGroupingMode !==
- DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode ? (
- <SettingResetButton
- label="default project grouping"
- onClick={() =>
- void updateClientSettings({
- sidebarProjectGroupingMode: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode,
- })
- }
+ <SettingResetButton
+ label="default browser access"
+ onClick={() =>
+ updateSettings({
+ enableAgentBrowserAccess: DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess,
+ })
+ }
+ />
+ ) : null
+ }
+ control={
+ <Switch
+ aria-label="Agent browser access"
+ mixed={mixedBrowser}
+ checked={mixedBrowser ? false : settings.enableAgentBrowserAccess}
+ onCheckedChange={(enabled) => updateSettings({ enableAgentBrowserAccess: enabled })}
/>
- ) : null
- }
- control={
- <Select
- value={clientSettings.sidebarProjectGroupingMode}
- onValueChange={(value) => {
- if (value === "repository" || value === "repository_path" || value === "separate")
- void updateClientSettings({ sidebarProjectGroupingMode: value });
- }}
- >
- <SelectTrigger size="sm" aria-label="Default project grouping">
- <SelectValue>
- {PROJECT_GROUPING_MODE_LABELS[clientSettings.sidebarProjectGroupingMode]}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- <SelectItem value="repository">
- {PROJECT_GROUPING_MODE_LABELS.repository}
- </SelectItem>
- <SelectItem value="repository_path">
- {PROJECT_GROUPING_MODE_LABELS.repository_path}
- </SelectItem>
- <SelectItem value="separate">{PROJECT_GROUPING_MODE_LABELS.separate}</SelectItem>
- </SelectPopup>
- </Select>
- }
- />
- <SettingsRow
- title="Remove checkout"
- aria-disabled
- description="Select a project to remove one of its checkouts."
- control={
- <Button size="sm" variant="destructive-outline" disabled>
- <Trash2Icon className="size-3.5" />
- Remove checkout
- </Button>
- }
- />
- </SettingsSection>
- <ProjectDefaultActionsSettings environmentId={environmentId} />
- <SettingsSection title="Danger">
- <SettingsRow
- title="Remove project"
- aria-disabled
- description="Select a project to remove its entries and threads. Files on disk are not touched."
- control={
- <Button size="sm" variant="destructive-outline" disabled>
- <Trash2Icon />
- Remove project
- </Button>
- }
- />
- </SettingsSection>
- </SettingsPageContainer>
+ }
+ />
+ </>
+ )}
+ </SettingsSection>
);
}
diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx
index a597e852c08..1a0f31d7783 100644
--- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx
+++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx
@@ -1,4 +1,3 @@
-import { useAtomValue } from "@effect/atom-react";
import {
isAtomCommandInterrupted,
mapAtomCommandResult,
@@ -8,102 +7,28 @@ import {
} from "@t3tools/client-runtime/state/runtime";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { AsyncResult } from "effect/unstable/reactivity";
-import {
- deriveProjectGroupingOverrideKey,
- selectProjectGroupingSettings,
-} from "../../logicalProject";
-import {
- type EnvironmentId,
- type ModelSelection,
- type ProjectIconOverride,
- type ProjectId,
- type ProjectScript,
- type ResolvedKeybindingsConfig,
- type ServerSettings,
- type ProviderDriverKind,
- type PullRequestMergeMethod,
- type SidebarProjectGroupingMode,
- type T3ProjectFileScript,
- type ThreadEnvMode,
-} from "@t3tools/contracts";
-import { resolveEnvModeLabel } from "../BranchToolbar.logic";
-import { createModelSelection } from "@t3tools/shared/model";
-import { resolveProjectAutoPull } from "@t3tools/shared/serverSettings";
-import {
- projectScriptsInheritDefaults,
- resolveProjectScripts,
-} from "@t3tools/shared/projectScripts";
-import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
-import { useNavigate } from "@tanstack/react-router";
-import * as Equal from "effect/Equal";
+import { type EnvironmentId, type ProjectIconOverride } from "@t3tools/contracts";
+import { useLocation, useNavigate } from "@tanstack/react-router";
import * as Cause from "effect/Cause";
-import { ChevronDownIcon, PlusIcon, Trash2Icon } from "lucide-react";
+import { Trash2Icon } from "lucide-react";
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useComposerDraftStore } from "../../composerDraftStore";
-import {
- useClientSettings,
- useEnvironmentSettings,
- useUpdateClientSettings,
-} from "../../hooks/useSettings";
-import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts";
-import { ProjectActionsList } from "./ProjectActionsList";
-import { isElectron } from "../../env";
-import {
- decodeProjectScriptKeybindingRule,
- keybindingValueForCommand,
-} from "../../lib/projectScriptKeybindings";
-import {
- buildProjectScript,
- commandForProjectScript,
- nextProjectScriptId,
-} from "../../projectScripts";
import { releaseProjectDraftUploads } from "../../lib/composerDraftUploads";
import { readLocalApi } from "../../localApi";
-import {
- applyProviderInstanceSettings,
- deriveProviderInstanceEntries,
- resolveDefaultProviderModelSelection,
- sortProviderInstanceEntries,
-} from "../../providerInstances";
-import { getCustomModelOptionsByInstance } from "../../modelSelection";
import {
type SidebarProjectGroupMember,
type SidebarProjectSnapshot,
} from "../../sidebarProjectGrouping";
import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
-import { useProjects, useThreadShells } from "../../state/entities";
+import { useThreadShells } from "../../state/entities";
import { projectEnvironment } from "../../state/projects";
-import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
-import { ProviderModelPicker } from "../chat/ProviderModelPicker";
-import { TraitsPicker } from "../chat/TraitsPicker";
import { ProjectFavicon } from "../ProjectFavicon";
-import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDetail.logic";
-import {
- EMPTY_PROJECT_SCRIPT_INPUT,
- editorRequestForScript,
- ProjectScriptEditorDialog,
- ScriptIcon,
- type NewProjectScriptInput,
- type ProjectScriptEditorRequest,
-} from "../projectScriptEditor";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
-import {
- Menu,
- MenuGroup,
- MenuGroupLabel,
- MenuItem,
- MenuPopup,
- MenuSeparator,
- MenuTrigger,
-} from "../ui/menu";
-import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
-import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
import {
- SETTINGS_PICKER_TRIGGER_CLASSNAME,
SettingResetButton,
SettingsPageContainer,
SettingsRow,
@@ -113,6 +38,7 @@ import {
canPickExternalProjectFavicon,
ProjectFaviconPickerDialog,
} from "./ProjectFaviconPickerDialog";
+import { ProjectActionsSettings } from "./ProjectActionsSettings";
import { projectGroupTitleNeedsUpdate } from "./ProjectSettingsPanel.logic";
import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
@@ -122,16 +48,12 @@ const ProjectIconPickerDialog = lazy(() =>
})),
);
-export const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = {
- repository: "Group by repository",
- repository_path: "Group by repository path",
- separate: "Keep separate",
-};
-
function memberKey(member: { environmentId: string; id: string }): string {
return `${member.environmentId}:${member.id}`;
}
+export type ProjectSettingsCategory = "general" | "integrations" | "source-control";
+
export function ProjectSettingsPanel({
projectKey,
environmentId = null,
@@ -142,7 +64,8 @@ export function ProjectSettingsPanel({
checkoutKey?: string | null;
}) {
const groups = useSettingsProjectGroups();
- const navigate = useNavigate();
+ const navigate = useNavigate({ from: "/settings" });
+ const pathname = useLocation({ select: (location) => location.pathname });
const selected = groups.find((group) => group.projectKey === projectKey) ?? null;
const members = useMemo(
@@ -189,17 +112,17 @@ export function ProjectSettingsPanel({
);
if (successor) {
void navigate({
- to: "/settings/projects",
- search: {
+ to: pathname,
+ search: () => ({
project: successor.projectKey,
machine: environmentId ?? undefined,
checkout: checkoutKey ?? undefined,
- },
+ }),
replace: true,
hashScrollIntoView: false,
});
}
- }, [groups, navigate, projectKey, members.length, environmentId, checkoutKey]);
+ }, [groups, navigate, pathname, projectKey, members.length, environmentId, checkoutKey]);
if (!selected) {
return (
@@ -231,146 +154,6 @@ export function ProjectSettingsPanel({
);
}
-function reportScriptFailure(result: AtomCommandResult<unknown, unknown>) {
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- toastManager.add({
- type: "error",
- title: "Failed to save project actions",
- description: error instanceof Error ? error.message : "An error occurred.",
- });
- }
- return mapAtomCommandResult(result, () => undefined);
-}
-
-export function useProjectScriptSettings(
- targets: readonly {
- environmentId: EnvironmentId;
- settings: ServerSettings;
- keybindings: ResolvedKeybindingsConfig;
- project?: { id: ProjectId; scripts: readonly ProjectScript[] };
- }[],
-) {
- const projects = useProjects();
- const [saving, setSaving] = useState(false);
- const savingRef = useRef(false);
- const updateSettings = useAtomCommand(serverEnvironment.updateSettings, "project actions update");
- const upsertKeybinding = useAtomCommand(
- serverEnvironment.upsertKeybinding,
- "action shortcut update",
- );
- const removeKeybinding = useAtomCommand(
- serverEnvironment.removeKeybinding,
- "action shortcut removal",
- );
-
- async function persist(
- transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null,
- scriptId?: string,
- keybinding?: string | null,
- ): Promise<AtomCommandResult<void, unknown>> {
- if (savingRef.current || targets.length === 0) {
- const message = "No available machine, or another action change is saving.";
- toastManager.add({ type: "error", title: "Actions not saved", description: message });
- return AsyncResult.failure(Cause.fail(new Error(message)));
- }
- savingRef.current = true;
- setSaving(true);
- try {
- for (const { environmentId, settings, keybindings, project } of targets) {
- const current = project
- ? resolveProjectScripts(settings, project)
- : settings.defaultProjectScripts;
- const nextScripts = transform(current);
- const effectiveScripts = nextScripts ?? settings.defaultProjectScripts;
- const result = await updateSettings({
- environmentId,
- input: {
- patch: project
- ? { projectScriptOverrides: { [project.id]: nextScripts } }
- : { defaultProjectScripts: nextScripts ?? [] },
- },
- });
- if (result._tag === "Failure") return reportScriptFailure(result);
- if (!isElectron) continue;
- const changedIds = scriptId
- ? [scriptId]
- : current
- .filter((script) => !effectiveScripts.some((next) => next.id === script.id))
- .map((script) => script.id);
- for (const id of changedIds) {
- const command = commandForProjectScript(id);
- const previousValue = keybindingValueForCommand(keybindings, command);
- const previous = previousValue
- ? decodeProjectScriptKeybindingRule({ keybinding: previousValue, command })
- : null;
- const next = decodeProjectScriptKeybindingRule({ keybinding, command });
- const retainedElsewhere =
- !nextScripts?.some((script) => script.id === id) &&
- ((project && settings.defaultProjectScripts.some((script) => script.id === id)) ||
- Object.entries(settings.projectScriptOverrides).some(
- ([projectId, scripts]) =>
- projectId !== project?.id && scripts?.some((script) => script.id === id),
- ) ||
- projects.some(
- (other) =>
- other.environmentId === environmentId &&
- other.id !== project?.id &&
- (project ? resolveProjectScripts(settings, other) : other.scripts).some(
- (script) => script.id === id,
- ),
- ));
- const bindingResult = next
- ? await upsertKeybinding({
- environmentId,
- input:
- previous && previous.key !== next.key ? { ...next, replace: previous } : next,
- })
- : previous && !retainedElsewhere
- ? await removeKeybinding({ environmentId, input: previous })
- : null;
- if (bindingResult?._tag === "Failure") return reportScriptFailure(bindingResult);
- }
- }
- return AsyncResult.success(undefined);
- } finally {
- savingRef.current = false;
- setSaving(false);
- }
- }
-
- function submit(scriptId: string | null, input: NewProjectScriptInput) {
- const existingIds = [
- ...projects.flatMap((project) => project.scripts.map((script) => script.id)),
- ...targets.flatMap(({ settings, project }) =>
- [
- ...settings.defaultProjectScripts,
- ...Object.values(settings.projectScriptOverrides).flatMap((scripts) => scripts ?? []),
- ...(project?.scripts ?? []),
- ].map((script) => script.id),
- ),
- ];
- const id = scriptId ?? nextProjectScriptId(input.name, existingIds);
- const next = buildProjectScript(id, input);
- return persist(
- (current) => {
- const updated = current.map((script) =>
- script.id === id
- ? next
- : input.runOnWorktreeCreate
- ? { ...script, runOnWorktreeCreate: false }
- : script,
- );
- return scriptId === null ? [...updated, next] : updated;
- },
- id,
- input.keybinding,
- );
- }
-
- return { saving, persist, submit };
-}
-
function ProjectDetail({
group,
hasOtherMembers,
@@ -378,7 +161,7 @@ function ProjectDetail({
group: SidebarProjectSnapshot;
hasOtherMembers: boolean;
}) {
- const navigate = useNavigate();
+ const navigate = useNavigate({ from: "/settings" });
const primaryEnvironmentId = usePrimaryEnvironmentId();
const { environments } = useEnvironments();
const environmentById = useMemo(
@@ -389,102 +172,10 @@ function ProjectDetail({
group.memberProjects.find(
(member) => environmentById.get(member.environmentId)?.serverConfig != null,
) ?? group.memberProjects[0]!;
- // Provider instances and model options belong to the environment that runs
- // the project's threads. The hosted app has no primary environment, so
- // reading them from there would show "No providers available" everywhere.
- const projectSettings = useEnvironmentSettings(representative.environmentId);
- const serverProviders =
- useAtomValue(serverEnvironment.providersValueAtom(representative.environmentId)) ??
- EMPTY_SERVER_PROVIDERS;
- const updateClientSettings = useUpdateClientSettings();
- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const threads = useThreadShells();
const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false });
- const updateServerSettings = useAtomCommand(serverEnvironment.updateSettings, "project setting");
- const [savingBrowserAccess, setSavingBrowserAccess] = useState(false);
- const savingBrowserAccessRef = useRef(false);
- const browserOverrides = group.memberProjects.map(
- (member) =>
- environmentById.get(member.environmentId)?.serverConfig?.settings
- .projectAgentBrowserAccessOverrides[member.id],
- );
- const browserOverride = projectSettings.projectAgentBrowserAccessOverrides[representative.id];
- const browserMixed = group.memberProjects.some((member, index) => {
- const settings = environmentById.get(member.environmentId)?.serverConfig?.settings;
- if (!settings || !environmentById.get(representative.environmentId)?.serverConfig) return false;
- return (
- browserOverrides[index] !== browserOverride ||
- (browserOverrides[index] ?? settings.enableAgentBrowserAccess) !==
- (browserOverride ?? projectSettings.enableAgentBrowserAccess)
- );
- });
- const setBooleanOverride = async (
- key: "projectAgentBrowserAccessOverrides" | "projectAutoPullOverrides",
- enabled: boolean | undefined,
- ) => {
- if (savingBrowserAccessRef.current) return;
- savingBrowserAccessRef.current = true;
- setSavingBrowserAccess(true);
- try {
- const environmentIds = new Set(group.memberProjects.map((member) => member.environmentId));
- for (const environmentId of environmentIds) {
- const environment = environmentById.get(environmentId);
- if (!environment?.serverConfig || environment.connection.phase !== "connected") {
- toastManager.add({
- type: "warning",
- title: "Setting not saved",
- description: `Connect ${environment?.label ?? "this machine"} and try again.`,
- });
- return;
- }
- }
- if (key === "projectAutoPullOverrides" && enabled === undefined) {
- const result = await updateAllMembers(
- { autoPull: false },
- "Failed to reset automatic pull",
- );
- if (result._tag === "Failure") return;
- }
- for (const environmentId of environmentIds) {
- const overrides = Object.fromEntries(
- group.memberProjects
- .filter((member) => member.environmentId === environmentId)
- .map((member) => [member.id, enabled ?? null]),
- );
- const result = await updateServerSettings({
- environmentId,
- input: { patch: { [key]: overrides } },
- });
- if (result._tag === "Failure") {
- reportFailure(
- `Failed to save project setting on ${environmentById.get(environmentId)?.label ?? "this machine"}`,
- mapAtomCommandResult(result, () => undefined),
- );
- return;
- }
- }
- } finally {
- savingBrowserAccessRef.current = false;
- setSavingBrowserAccess(false);
- }
- };
- const setBrowserAccess = (enabled: boolean | undefined) =>
- setBooleanOverride("projectAgentBrowserAccessOverrides", enabled);
const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
const projectNameEditedRef = useRef(false);
- const mergeMethodOverrides = useClientSettings(
- (settings) => settings.pullRequestMergeMethodOverrides,
- );
- const projectMergeMethod = mergeMethodOverrides[group.projectKey];
- const setProjectMergeMethod = (method: PullRequestMergeMethod | null) => {
- const nextOverrides = { ...mergeMethodOverrides };
- if (method === null) {
- delete nextOverrides[group.projectKey];
- } else {
- nextOverrides[group.projectKey] = method;
- }
- updateClientSettings({ pullRequestMergeMethodOverrides: nextOverrides });
- };
const faviconPath = representative.faviconPath ?? null;
const projectIcon = representative.projectIcon ?? null;
@@ -516,14 +207,23 @@ function ProjectDetail({
async (
input: Partial<{
title: string;
- defaultModelSelection: ModelSelection | null;
- defaultThreadEnvMode: ThreadEnvMode | null;
- autoPull: boolean;
faviconPath: string | null;
projectIcon: ProjectIconOverride | null;
}>,
failureTitle: string,
): Promise<AtomCommandResult<void, unknown>> => {
+ const unavailable = group.memberProjects.find((member) => {
+ const environment = environmentById.get(member.environmentId);
+ return environment?.connection.phase !== "connected" || !environment.serverConfig;
+ });
+ if (unavailable) {
+ const error = new Error(
+ `Connect ${unavailable.environmentLabel ?? "the selected environment"} and try again.`,
+ );
+ const result: AtomCommandResult<void, unknown> = AsyncResult.failure(Cause.fail(error));
+ reportFailure(failureTitle, result);
+ return result;
+ }
for (const member of group.memberProjects) {
const result = mapAtomCommandResult(
await updateProject({
@@ -546,7 +246,7 @@ function ProjectDetail({
}
return AsyncResult.success(undefined);
},
- [group.memberProjects, reportFailure, updateProject],
+ [environmentById, group.memberProjects, reportFailure, updateProject],
);
const renameGroup = useCallback(
@@ -570,117 +270,6 @@ function ProjectDetail({
[group.memberProjects, updateAllMembers],
);
- // ----- default model -----
- const storedSelection = representative.defaultModelSelection;
- const resolvedSelection = resolveDefaultProviderModelSelection(
- serverProviders,
- storedSelection ?? projectSettings.defaultModelSelection,
- );
- const mixedModel = group.memberProjects.some((member) => {
- const config = environmentById.get(member.environmentId)?.serverConfig;
- return (
- !Equal.equals(member.defaultModelSelection, storedSelection) ||
- (config !== null &&
- config !== undefined &&
- environmentById.get(representative.environmentId)?.serverConfig != null &&
- JSON.stringify(
- resolveDefaultProviderModelSelection(
- config.providers,
- member.defaultModelSelection ?? config.settings.defaultModelSelection,
- ),
- ) !== JSON.stringify(resolvedSelection))
- );
- });
- const resolvedInstanceId = resolvedSelection?.instanceId ?? null;
- const resolvedModel = resolvedSelection?.model ?? null;
- const instanceEntries = useMemo(
- () =>
- sortProviderInstanceEntries(
- applyProviderInstanceSettings(
- deriveProviderInstanceEntries(serverProviders),
- projectSettings,
- ),
- ),
- [serverProviders, projectSettings],
- );
- const modelOptionsByInstance = useMemo(
- () =>
- getCustomModelOptionsByInstance(
- projectSettings,
- serverProviders,
- resolvedInstanceId,
- resolvedModel,
- ),
- [resolvedInstanceId, resolvedModel, serverProviders, projectSettings],
- );
- const activeEntry = instanceEntries.find((entry) => entry.instanceId === resolvedInstanceId);
- const setDefaultModel = (selection: ModelSelection | null) => {
- if (selection !== null) {
- for (const member of group.memberProjects) {
- const environment = environmentById.get(member.environmentId);
- const config = environment?.serverConfig;
- const entry = config
- ? applyProviderInstanceSettings(
- deriveProviderInstanceEntries(config.providers),
- config.settings,
- ).find((candidate) => candidate.instanceId === selection.instanceId)
- : undefined;
- const options = config
- ? getCustomModelOptionsByInstance(
- { ...projectSettings, ...config.settings },
- config.providers,
- ).get(selection.instanceId)
- : undefined;
- if (
- !entry?.enabled ||
- !entry.isAvailable ||
- !options?.some((model) => model.slug === selection.model && !model.isUnavailable)
- ) {
- toastManager.add({
- type: "warning",
- title: "Project model not saved",
- description: `This model is unavailable on ${environment?.label ?? "a selected machine"}. Select a machine to choose its model separately.`,
- });
- return;
- }
- }
- }
- void updateAllMembers({ defaultModelSelection: selection }, "Failed to update default model");
- };
-
- // ----- new-thread workspace mode -----
- const storedEnvMode = representative.defaultThreadEnvMode ?? null;
- const mixedWorkspace = group.memberProjects.some(
- (member) => member.defaultThreadEnvMode !== storedEnvMode,
- );
- const setDefaultThreadEnvMode = useCallback(
- (mode: ThreadEnvMode | null) =>
- void updateAllMembers(
- { defaultThreadEnvMode: mode },
- "Failed to update new-thread workspace",
- ),
- [updateAllMembers],
- );
-
- const autoPull = resolveProjectAutoPull(
- projectSettings,
- representative.id,
- representative.autoPull,
- );
- const autoPullOverridden = group.memberProjects.some(
- (member) =>
- member.autoPull ||
- environmentById.get(member.environmentId)?.serverConfig?.settings.projectAutoPullOverrides[
- member.id
- ] !== undefined,
- );
- const mixedAutoPull = group.memberProjects.some((member) => {
- const settings = environmentById.get(member.environmentId)?.serverConfig?.settings;
- return settings && resolveProjectAutoPull(settings, member.id, member.autoPull) !== autoPull;
- });
- const setAutoPull = (enabled: boolean | undefined) =>
- setBooleanOverride("projectAutoPullOverrides", enabled);
-
// ----- project icon -----
const [faviconPickerOpen, setFaviconPickerOpen] = useState(false);
const [iconPickerOpen, setIconPickerOpen] = useState(false);
@@ -701,99 +290,7 @@ function ProjectDetail({
[updateAllMembers],
);
- // ----- checkout selection and scripts -----
const hasMultipleCheckouts = group.memberProjects.length > 1;
- const [selectedCheckoutKey, setSelectedCheckoutKey] = useState<string | null>(null);
- const selectedCheckoutMatch = group.memberProjects.find(
- (member) => member.physicalProjectKey === selectedCheckoutKey,
- );
- const selectedCheckout = selectedCheckoutMatch ?? representative;
- const selectedServerConfig = useAtomValue(
- serverEnvironment.configValueAtom(selectedCheckout.environmentId),
- );
- const keybindings = selectedServerConfig?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS;
- const scriptSettings = useEnvironmentSettings(selectedCheckout.environmentId);
- const scripts = resolveProjectScripts(scriptSettings, selectedCheckout);
- const scriptsInherited = projectScriptsInheritDefaults(scriptSettings, selectedCheckout);
- const [editorRequest, setEditorRequest] = useState<ProjectScriptEditorRequest | null>(null);
- const {
- saving: isSavingScripts,
- persist: persistScripts,
- submit: submitScript,
- } = useProjectScriptSettings([
- {
- environmentId: selectedCheckout.environmentId,
- settings: scriptSettings,
- keybindings,
- project: selectedCheckout,
- },
- ]);
- const t3File = useT3ProjectFileState(
- selectedCheckout.environmentId,
- selectedCheckout.workspaceRoot,
- );
- // What the "Default" option resolves to while no override is set: the
- // repo's t3.json value when present, otherwise the global setting.
- const inheritedEnvMode = t3File.file?.defaultThreadEnvMode ?? scriptSettings.defaultThreadEnvMode;
- const inheritedEnvModeSource = t3File.file?.defaultThreadEnvMode != null ? "t3.json" : "global";
- const importableScripts = useMemo(
- () =>
- t3File.scripts.filter(
- (fileScript) =>
- !scripts.some(
- (script) =>
- script.command === fileScript.command ||
- script.name.toLowerCase() === fileScript.name.toLowerCase(),
- ),
- ),
- [scripts, t3File.scripts],
- );
-
- const deleteScript = (scriptId: string) =>
- void persistScripts(
- (current) => current.filter((script) => script.id !== scriptId),
- scriptId,
- null,
- );
-
- const importFileScript = useCallback(
- async (fileScript: T3ProjectFileScript) => {
- const payload: NewProjectScriptInput = {
- name: fileScript.name,
- command: fileScript.command,
- icon: fileScript.icon ?? "play",
- runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
- keybinding: null,
- previewUrl: fileScript.previewUrl ?? null,
- autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
- };
- const result = await submitScript(null, payload);
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- setEditorRequest({
- scriptId: null,
- initial: payload,
- error: error instanceof Error ? error.message : "Failed to import action.",
- });
- }
- },
- [submitScript, setEditorRequest],
- );
-
- // ----- checkouts -----
- const updateGroupingPreference = useCallback(
- (member: SidebarProjectGroupMember, selection: SidebarProjectGroupingMode | "inherit") => {
- const overrideKey = deriveProjectGroupingOverrideKey(member);
- const nextOverrides = { ...projectGroupingSettings.sidebarProjectGroupingOverrides };
- if (selection === "inherit") {
- delete nextOverrides[overrideKey];
- } else {
- nextOverrides[overrideKey] = selection;
- }
- updateClientSettings({ sidebarProjectGroupingOverrides: nextOverrides });
- },
- [projectGroupingSettings.sidebarProjectGroupingOverrides, updateClientSettings],
- );
const removeMembers = useCallback(
async (members: ReadonlyArray<SidebarProjectGroupMember>) => {
@@ -884,26 +381,32 @@ function ProjectDetail({
],
);
- const selectedCheckoutGrouping =
- projectGroupingSettings.sidebarProjectGroupingOverrides?.[
- deriveProjectGroupingOverrideKey(selectedCheckout)
- ] ?? "inherit";
- const checkoutLabel = (member: SidebarProjectGroupMember) => {
- const label = member.environmentLabel ?? "This machine";
- return group.memberProjects.some(
- (other) =>
- other.physicalProjectKey !== member.physicalProjectKey &&
- (other.environmentLabel ?? "This machine") === label,
- )
- ? `${label} · ${member.workspaceRoot}`
- : label;
- };
- const selectedCheckoutLabel = checkoutLabel(selectedCheckout);
+ const checkoutChoices = (
+ <SettingsSection title="Checkouts">
+ {group.memberProjects.map((member) => (
+ <SettingsRow
+ key={member.physicalProjectKey}
+ title={member.environmentLabel ?? "Environment"}
+ description={member.workspaceRoot}
+ control={
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void removeMembers([member])}
+ aria-label={`Remove checkout ${member.workspaceRoot}`}
+ >
+ Remove
+ </Button>
+ }
+ />
+ ))}
+ </SettingsSection>
+ );
return (
<>
<SettingsPageContainer className="gap-6">
- <SettingsSection title="Project" hideTitle>
+ <SettingsSection id="project-overview" title="Project" hideTitle>
<SettingsRow
title="Name"
description="The shared name for this project group in the sidebar and thread lists."
@@ -938,7 +441,9 @@ function ProjectDetail({
: (faviconPath ?? "Automatic")
}
resetAction={
- faviconPath !== null || projectIcon !== null ? (
+ group.memberProjects.some(
+ (member) => member.faviconPath != null || member.projectIcon != null,
+ ) ? (
<SettingResetButton
label="project icon"
disabled={isSavingFavicon}
@@ -972,430 +477,9 @@ function ProjectDetail({
</div>
}
/>
- <SettingsRow
- title="Default merge method"
- description="Pull requests in this project start with this method. It overrides the last method selected."
- resetAction={
- projectMergeMethod !== undefined ? (
- <SettingResetButton
- label="project merge method"
- onClick={() => setProjectMergeMethod(null)}
- />
- ) : null
- }
- control={
- <Select
- value={projectMergeMethod ?? "inherit"}
- onValueChange={(value) =>
- setProjectMergeMethod(
- value === "inherit" ? null : (value as PullRequestMergeMethod),
- )
- }
- >
- <SelectTrigger aria-label="Default pull request merge method">
- <SelectValue>
- {projectMergeMethod === undefined
- ? "Last selected"
- : PULL_REQUEST_MERGE_METHOD_LABELS[projectMergeMethod]}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- <SelectItem value="inherit">Last selected</SelectItem>
- <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
- <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
- <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
- </SelectPopup>
- </Select>
- }
- />
- <SettingsRow
- title="Model"
- status={
- mixedModel
- ? "Mixed defaults or overrides. Choosing a model updates all selected checkouts."
- : storedSelection === null
- ? "Inherited"
- : "Overridden"
- }
- description={
- storedSelection === null
- ? "Inherited from machine defaults. New threads use the default model."
- : "Overridden for this project. Reset to use the default model."
- }
- resetAction={
- group.memberProjects.some((member) => member.defaultModelSelection !== null) ? (
- <SettingResetButton
- label="project default model"
- tooltip="Reset to inherited model"
- onClick={() => setDefaultModel(null)}
- />
- ) : null
- }
- control={
- resolvedSelection && activeEntry ? (
- <div className="flex flex-wrap items-center justify-end gap-1.5">
- <ProviderModelPicker
- activeInstanceId={resolvedSelection.instanceId}
- model={resolvedSelection.model}
- lockedProvider={null}
- instanceEntries={instanceEntries}
- modelOptionsByInstance={modelOptionsByInstance}
- triggerVariant="outline"
- triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
- onOpenProviderSetup={(instanceId) => {
- void navigate({
- to: "/settings/providers",
- search: { environmentId: representative.environmentId, instanceId },
- });
- }}
- onInstanceModelChange={(instanceId, model) => {
- setDefaultModel(createModelSelection(instanceId, model));
- }}
- />
- <TraitsPicker
- provider={activeEntry.driverKind as ProviderDriverKind}
- models={activeEntry.models}
- model={resolvedSelection.model}
- prompt=""
- onPromptChange={() => {}}
- modelOptions={resolvedSelection.options ?? []}
- allowPromptInjectedEffort={false}
- planModeEnabled={projectSettings.planModeEnabled}
- triggerVariant="outline"
- triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
- onModelOptionsChange={(nextOptions) => {
- setDefaultModel(
- createModelSelection(
- resolvedSelection.instanceId,
- resolvedSelection.model,
- nextOptions,
- ),
- );
- }}
- />
- </div>
- ) : (
- <span className="text-sm text-muted-foreground">No providers available</span>
- )
- }
- />
- <SettingsRow
- title="Workspace"
- status={
- mixedWorkspace
- ? "Mixed overrides. Choosing a workspace updates all selected checkouts."
- : storedEnvMode === null
- ? "Inherited"
- : "Overridden"
- }
- description={
- storedEnvMode === null
- ? "Inherited from t3.json or machine defaults."
- : "Overridden for this project. Reset to inherit its workspace default."
- }
- resetAction={
- group.memberProjects.some((member) => member.defaultThreadEnvMode !== null) ? (
- <SettingResetButton
- label="project workspace default"
- tooltip="Reset to inherited workspace"
- onClick={() => setDefaultThreadEnvMode(null)}
- />
- ) : null
- }
- control={
- <Select
- value={storedEnvMode ?? "inherit"}
- onValueChange={(value) => {
- if (value === "worktree" || value === "local") {
- setDefaultThreadEnvMode(value);
- } else if (value === "inherit") {
- setDefaultThreadEnvMode(null);
- }
- }}
- >
- <SelectTrigger size="sm" aria-label="New-thread workspace">
- <SelectValue>
- {storedEnvMode === null
- ? group.memberProjects.length > 1
- ? "Default (per checkout)"
- : `Default (${resolveEnvModeLabel(inheritedEnvMode).toLowerCase()})`
- : resolveEnvModeLabel(storedEnvMode)}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- <SelectItem value="inherit">
- {group.memberProjects.length > 1
- ? "Default (each checkout's t3.json or global setting)"
- : `Default (${inheritedEnvModeSource}: ${resolveEnvModeLabel(inheritedEnvMode).toLowerCase()})`}
- </SelectItem>
- <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
- <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
- </SelectPopup>
- </Select>
- }
- />
- <SettingsRow
- title="Automatically pull"
- description="Keeps the default branch current in the background when the checkout has no local changes or commits."
- status={
- mixedAutoPull
- ? "Mixed"
- : autoPullOverridden
- ? "Overridden"
- : `Inherited (${autoPull ? "on" : "off"})`
- }
- resetAction={
- autoPullOverridden ? (
- <SettingResetButton
- label="automatic pull"
- tooltip="Reset to inherited automatic pull setting"
- disabled={savingBrowserAccess}
- onClick={() => void setAutoPull(undefined)}
- />
- ) : null
- }
- control={
- <Switch
- checked={autoPull}
- disabled={savingBrowserAccess}
- aria-label="Automatically pull the default branch"
- onCheckedChange={(enabled) => void setAutoPull(enabled)}
- />
- }
- />
- <SettingsRow
- title="Agent browser access"
- description={
- browserMixed
- ? "Mixed defaults or overrides across selected checkouts."
- : browserOverride === undefined
- ? "Inherited from machine defaults. Controls agent access to the preview browser."
- : "Overridden for this project. Applies when the agent session next starts."
- }
- resetAction={
- browserOverrides.some((value) => value !== undefined) ? (
- <SettingResetButton
- label="project browser access"
- tooltip="Reset to inherited browser access"
- disabled={savingBrowserAccess}
- onClick={() => void setBrowserAccess(undefined)}
- />
- ) : null
- }
- control={
- <Select
- value={
- browserMixed
- ? "mixed"
- : browserOverride === undefined
- ? "inherit"
- : browserOverride
- ? "enabled"
- : "disabled"
- }
- disabled={savingBrowserAccess}
- onValueChange={(value) => {
- if (value === "inherit") void setBrowserAccess(undefined);
- else if (value === "enabled" || value === "disabled")
- void setBrowserAccess(value === "enabled");
- }}
- >
- <SelectTrigger size="sm" aria-label="Project agent browser access">
- <SelectValue>
- {browserMixed
- ? "Mixed"
- : browserOverride === undefined
- ? `Inherit (${projectSettings.enableAgentBrowserAccess ? "on" : "off"})`
- : browserOverride
- ? "On"
- : "Off"}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- <SelectItem value="inherit">Inherit defaults</SelectItem>
- <SelectItem value="enabled">On</SelectItem>
- <SelectItem value="disabled">Off</SelectItem>
- </SelectPopup>
- </Select>
- }
- />
</SettingsSection>
-
- <SettingsSection title="Checkout">
- {hasMultipleCheckouts ? (
- <SettingsRow
- title="Checkout"
- description="Actions and grouping belong to this checkout."
- control={
- <Select
- value={selectedCheckout.physicalProjectKey}
- onValueChange={(value) => {
- if (value) setSelectedCheckoutKey(value);
- }}
- >
- <SelectTrigger size="sm" aria-label="Checkout">
- <SelectValue className="max-w-96 truncate">{selectedCheckoutLabel}</SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- {group.memberProjects.map((member) => (
- <SelectItem key={member.physicalProjectKey} value={member.physicalProjectKey}>
- <span className="max-w-96 whitespace-normal break-all">
- {checkoutLabel(member)}
- </span>
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- }
- />
- ) : null}
- <SettingsRow
- title="Project grouping"
- description="How this checkout joins project groups in the sidebar. Changing it can move you to a different project group."
- resetAction={
- selectedCheckoutGrouping !== "inherit" ? (
- <SettingResetButton
- label="project grouping"
- tooltip="Reset to inherited project grouping"
- onClick={() => updateGroupingPreference(selectedCheckout, "inherit")}
- />
- ) : null
- }
- control={
- <Select
- value={selectedCheckoutGrouping}
- onValueChange={(value) => {
- if (
- value === "inherit" ||
- value === "repository" ||
- value === "repository_path" ||
- value === "separate"
- ) {
- updateGroupingPreference(selectedCheckout, value);
- }
- }}
- >
- <SelectTrigger size="sm" aria-label={`Grouping rule for ${selectedCheckoutLabel}`}>
- <SelectValue>
- {selectedCheckoutGrouping === "inherit"
- ? `Default (${PROJECT_GROUPING_MODE_LABELS[projectGroupingSettings.sidebarProjectGroupingMode]})`
- : PROJECT_GROUPING_MODE_LABELS[selectedCheckoutGrouping]}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- <SelectItem hideIndicator value="inherit">
- Use global default
- </SelectItem>
- <SelectItem hideIndicator value="repository">
- {PROJECT_GROUPING_MODE_LABELS.repository}
- </SelectItem>
- <SelectItem hideIndicator value="repository_path">
- {PROJECT_GROUPING_MODE_LABELS.repository_path}
- </SelectItem>
- <SelectItem hideIndicator value="separate">
- {PROJECT_GROUPING_MODE_LABELS.separate}
- </SelectItem>
- </SelectPopup>
- </Select>
- }
- />
- {group.memberProjects.length > 1 ? (
- <SettingsRow
- title="Remove checkout"
- description="Removes this checkout and its threads from the project group. Files on disk are not touched."
- control={
- <Button
- size="sm"
- variant="destructive-outline"
- onClick={() => void removeMembers([selectedCheckout])}
- >
- <Trash2Icon className="size-3.5" />
- Remove checkout
- </Button>
- }
- />
- ) : null}
- <div className="flex min-h-8 flex-col items-start gap-3 px-3 py-4 sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:px-4">
- <div className="min-w-0">
- <h3 className="text-base font-semibold text-foreground">Actions</h3>
- <p className="text-pretty text-sm text-muted-foreground">
- {scriptsInherited
- ? "Inherited from machine defaults."
- : `Overridden for ${selectedCheckoutLabel}.`}
- </p>
- </div>
- <div className="flex w-full flex-wrap gap-1.5 sm:w-auto sm:shrink-0 sm:justify-end">
- {!scriptsInherited ? (
- <SettingResetButton
- label="project actions"
- tooltip="Reset to inherited actions"
- disabled={isSavingScripts}
- onClick={() => void persistScripts(() => null)}
- />
- ) : null}
- {importableScripts.length > 0 ? (
- <Menu>
- <MenuTrigger
- render={
- <Button size="xs" variant="ghost" disabled={isSavingScripts} type="button" />
- }
- >
- Import scripts
- <ChevronDownIcon className="size-3.5" />
- </MenuTrigger>
- <MenuPopup align="end" className="w-72">
- <MenuGroup>
- <MenuGroupLabel>Import from t3.json</MenuGroupLabel>
- <p className="px-2 pb-2 text-pretty text-sm text-muted-foreground">
- Add actions declared by this checkout without editing them first.
- </p>
- </MenuGroup>
- <MenuSeparator />
- {importableScripts.map((fileScript) => (
- <MenuItem
- key={`${fileScript.name} ${fileScript.command}`}
- onClick={() => void importFileScript(fileScript)}
- >
- <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4 shrink-0" />
- <div className="min-w-0 flex-1">
- <div className="truncate font-medium">{fileScript.name}</div>
- <div className="truncate font-mono text-muted-foreground">
- {fileScript.command}
- </div>
- </div>
- </MenuItem>
- ))}
- </MenuPopup>
- </Menu>
- ) : null}
- <Button
- size="xs"
- variant="outline"
- disabled={isSavingScripts}
- onClick={() =>
- setEditorRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT })
- }
- >
- <PlusIcon className="size-3.5" />
- Add action
- </Button>
- </div>
- </div>
- <ProjectActionsList
- scripts={scripts}
- keybindings={keybindings}
- disabled={isSavingScripts}
- onEdit={(script) => setEditorRequest(editorRequestForScript(script, keybindings))}
- />
- {t3File.status === "invalid" ? (
- <SettingsRow
- title="t3.json is invalid"
- description="A t3.json exists in this checkout but fails to parse, so every action and icon it declares is ignored. Check the JSON syntax and icon values."
- className="text-warning"
- />
- ) : null}
- </SettingsSection>
-
+ <ProjectActionsSettings />
+ {hasMultipleCheckouts ? checkoutChoices : null}
<SettingsSection title="Danger">
<SettingsRow
title={
@@ -1430,13 +514,6 @@ function ProjectDetail({
</SettingsSection>
</SettingsPageContainer>
- <ProjectScriptEditorDialog
- request={editorRequest}
- scripts={scripts}
- onSubmit={submitScript}
- onDelete={deleteScript}
- onClose={() => setEditorRequest(null)}
- />
<ProjectFaviconPickerDialog
key={`${representative.environmentId}:${representative.workspaceRoot}:${faviconPickerOpen}`}
cwd={representative.workspaceRoot}
diff --git a/apps/web/src/components/settings/ProjectsSettings.tsx b/apps/web/src/components/settings/ProjectsSettings.tsx
index a0ff91f0301..995b1119117 100644
--- a/apps/web/src/components/settings/ProjectsSettings.tsx
+++ b/apps/web/src/components/settings/ProjectsSettings.tsx
@@ -1,21 +1,12 @@
-import { WorkspacePageContainer } from "../WorkspacePageContainer";
-import { useEnvironments } from "../../state/environments";
+import { EnvironmentId } from "@t3tools/contracts";
+
import { ProjectSettingsPanel } from "./ProjectSettingsPanel";
-import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
-import { SettingsScopeSelects } from "./SettingsScopeSelects";
-import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
-import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
+import { useSettingsScope } from "./SettingsScopeContext";
+import { SettingsScopeNotice } from "./SettingsScopeNotice";
-export function ProjectsSettings({
- value,
- onScopeChange,
-}: {
- value: SettingsScopeSearch;
- onScopeChange: (scope: SettingsScopeSearch) => void;
-}) {
- const groups = useSettingsProjectGroups();
- const { environments } = useEnvironments();
- const scope = resolveSettingsScope(value, groups, environments);
+/** Project identity and checkout management for the selected project. */
+export function ProjectsSettings() {
+ const { search: value, scope } = useSettingsScope();
// The panel follows remembered members when grouping replaces a project key.
const projectScope =
scope.kind === "project" ||
@@ -24,16 +15,6 @@ export function ProjectsSettings({
(scope.reason === "project-missing" || scope.reason === "checkout-missing"));
return (
<div className="flex min-h-0 flex-1 flex-col">
- <div className="scrollbar-gutter-both shrink-0 overflow-y-auto">
- <WorkspacePageContainer className="items-end pb-0">
- <SettingsScopeSelects
- value={value}
- groups={groups}
- environments={environments}
- onChange={onScopeChange}
- />
- </WorkspacePageContainer>
- </div>
{value.project && projectScope ? (
<ProjectSettingsPanel
projectKey={value.project}
@@ -43,11 +24,10 @@ export function ProjectsSettings({
) : scope.kind === "unavailable" ? (
<p className="p-8 text-sm text-muted-foreground">{scope.message}</p>
) : (
- <ProjectDefaultsSettings
- environmentId={scope.kind === "environment" ? scope.environmentId : null}
- />
+ <SettingsScopeNotice target="project">
+ Choose a project to manage its name, icon, checkouts and actions.
+ </SettingsScopeNotice>
)}
</div>
);
}
-import { EnvironmentId } from "@t3tools/contracts";
diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx
index 7b386e062c1..f1f1fe1a518 100644
--- a/apps/web/src/components/settings/ProviderInstanceCard.tsx
+++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx
@@ -896,6 +896,10 @@ export function ProviderInstanceCard({
className={readOnly ? "opacity-50 select-none" : undefined}
>
<div className="px-3 py-3 sm:px-4">
+ <p className="mb-3 text-xs text-muted-foreground">
+ Favorites, visibility, and ordering are saved on this device. Custom models are saved
+ on the selected environment.
+ </p>
<ProviderModelsSection
instanceId={instanceId}
driverKind={driverKind}
diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx
index 9cbac447972..90d84d1c1ef 100644
--- a/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx
@@ -29,6 +29,7 @@ const settingsState = vi.hoisted(() => ({
readEnvironmentIds: [] as EnvironmentId[],
updateEnvironmentIds: [] as EnvironmentId[],
updateSettings: vi.fn(),
+ updateClientSettings: vi.fn(),
}));
const settingsSearchState = vi.hoisted(() => ({
@@ -81,14 +82,12 @@ vi.mock("../../state/use-atom-command", () => ({
}));
vi.mock("../../hooks/useSettings", () => ({
+ useUpdateClientSettings: () => settingsState.updateClientSettings,
useEnvironmentSettings: (environmentId: EnvironmentId) => {
settingsState.readEnvironmentIds.push(environmentId);
return settingsState.value;
},
- useUpdateEnvironmentSettings: (environmentId: EnvironmentId) => {
- settingsState.updateEnvironmentIds.push(environmentId);
- return settingsState.updateSettings;
- },
+ useUpdateEnvironmentSettings: () => settingsState.updateSettings,
}));
vi.mock("../../environments/primary", () => ({
@@ -177,6 +176,7 @@ describe("EnvironmentProviderSettings routing", () => {
settingsState.readEnvironmentIds = [];
settingsState.updateEnvironmentIds = [];
settingsState.updateSettings.mockReset();
+ settingsState.updateClientSettings.mockReset();
settingsSearchState.targetId = null;
settingsSearchState.effects = [];
commands.refresh.mockReset().mockResolvedValue({ _tag: "Success" });
@@ -186,7 +186,6 @@ describe("EnvironmentProviderSettings routing", () => {
it("coalesces a nullable provider snapshot before rendering array-backed UI", () => {
expect(() => renderPanel()).not.toThrow();
expect(settingsState.readEnvironmentIds).toEqual([environmentId]);
- expect(settingsState.updateEnvironmentIds).toEqual([environmentId]);
});
it("routes refresh and provider update commands to the selected environment", async () => {
@@ -230,6 +229,30 @@ describe("EnvironmentProviderSettings routing", () => {
expect(editor?.props.instanceId).toBe(customId);
});
+ it.each([
+ ["onFavoriteModelsChange", { favorites: [{ provider: codexId, model: "chosen" }] }],
+ [
+ "onHiddenModelsChange",
+ { providerModelPreferences: { [codexId]: { hiddenModels: ["chosen"], modelOrder: [] } } },
+ ],
+ [
+ "onModelOrderChange",
+ { providerModelPreferences: { [codexId]: { hiddenModels: [], modelOrder: ["chosen"] } } },
+ ],
+ ])("saves %s on this device without changing the selected server", (action, expected) => {
+ atoms.providers = [provider()];
+ const panel = renderPanel();
+ const editor = visitElements(
+ panel,
+ (element) => element.props.instanceId === codexId && element.props.mode === "editor",
+ );
+ expect(editor).not.toBeNull();
+ if (!editor) throw new Error("Provider editor was not rendered");
+ (editor.props[action] as (models: string[]) => void)(["chosen"]);
+ expect(settingsState.updateClientSettings).toHaveBeenCalledExactlyOnceWith(expected);
+ expect(settingsState.updateSettings).not.toHaveBeenCalled();
+ });
+
it("does not substitute another account when the requested instance was removed", () => {
atoms.providers = [provider()];
const panel = renderPanel({ targetInstanceId: customId });
diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx
index 74676e3ff16..f1966fe4547 100644
--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx
@@ -31,7 +31,11 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
import { isElectron } from "../../env";
import { usePrimarySessionState } from "../../environments/primary";
-import { useEnvironmentSettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
+import {
+ useEnvironmentSettings,
+ useUpdateClientSettings,
+ useUpdateEnvironmentSettings,
+} from "../../hooks/useSettings";
import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
import { cn } from "../../lib/utils";
import { resolveAppModelSelectionState } from "../../modelSelection";
@@ -262,6 +266,7 @@ function EnvironmentUnavailablePlaceholder({
interface ProviderSettingsTarget {
readonly environmentId?: EnvironmentId;
readonly instanceId?: ProviderInstanceId;
+ readonly scoped?: boolean;
}
export function ProviderSettingsPanel(target: ProviderSettingsTarget) {
@@ -293,9 +298,10 @@ function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
target.environmentId !== undefined &&
selectedEnvironmentId === target.environmentId &&
!options.some((environment) => environment.environmentId === target.environmentId);
- const effectiveEnvironmentId = targetEnvironmentMissing
- ? target.environmentId
- : resolveSelectedProviderEnvironmentId(options, selectedEnvironmentId, primaryEnvironmentId);
+ const effectiveEnvironmentId =
+ target.scoped || targetEnvironmentMissing
+ ? target.environmentId
+ : resolveSelectedProviderEnvironmentId(options, selectedEnvironmentId, primaryEnvironmentId);
const selectedEnvironment =
options.find((environment) => environment.environmentId === effectiveEnvironmentId) ?? null;
const selectedEnvironmentCanRenderSettings =
@@ -312,6 +318,7 @@ function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
)?.environmentId;
useEffect(() => {
if (
+ !target.scoped &&
(searchTargetId === searchableSetting("provider-health-check-interval").id ||
searchTargetId === searchableSetting("usage-providers").id) &&
!selectedEnvironmentCanRenderSettings &&
@@ -319,11 +326,16 @@ function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
) {
setSelectedEnvironmentId(searchableEnvironmentId);
}
- }, [searchTargetId, searchableEnvironmentId, selectedEnvironmentCanRenderSettings]);
+ }, [
+ searchTargetId,
+ searchableEnvironmentId,
+ selectedEnvironmentCanRenderSettings,
+ target.scoped,
+ ]);
const onlyPrimaryDevice =
options.length === 1 && options[0]?.entry.target._tag === "PrimaryConnectionTarget";
const deviceTabs =
- !onlyPrimaryDevice && options.length > 0 ? (
+ !target.scoped && !onlyPrimaryDevice && options.length > 0 ? (
<ScrollArea hideScrollbars scrollFade className="h-11 min-w-0 flex-1 rounded-none">
<ToggleGroup
aria-label="Devices"
@@ -559,7 +571,10 @@ export function EnvironmentProviderSettings({
readonly readOnly?: boolean;
}) {
const settings = useEnvironmentSettings(environmentId);
+ // Provider instances hold per-machine credentials and binaries, so this
+ // page always edits exactly the environment it displays.
const updateSettings = useUpdateEnvironmentSettings(environmentId);
+ const updateClientSettings = useUpdateClientSettings();
const serverProviders =
useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
@@ -815,7 +830,7 @@ export function EnvironmentProviderSettings({
const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
- updateSettings({
+ updateClientSettings({
providerModelPreferences:
hiddenModels.length === 0 && modelOrder.length === 0
? rest
@@ -841,7 +856,7 @@ export function EnvironmentProviderSettings({
}),
),
];
- updateSettings({
+ updateClientSettings({
favorites: [
...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
...favoriteModels.map((model) => ({ provider: instanceId, model })),
diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx
index 003e46869a9..b52e54bb5f7 100644
--- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx
+++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx
@@ -13,6 +13,7 @@ import {
} from "lucide-react";
import type {
BackgroundBooleanState,
+ EnvironmentId,
ResourceAttributionEntry,
ResourceTelemetryAggregate,
ResourceTelemetryHistoryBucket,
@@ -26,7 +27,7 @@ import type {
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
-import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -38,7 +39,6 @@ import {
} from "../../lib/resourceTelemetryState";
import { cn } from "../../lib/utils";
import { ensureLocalApi } from "../../localApi";
-import { usePrimaryEnvironment } from "../../state/environments";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { formatRelativeTime } from "../../timestampFormat";
@@ -831,31 +831,43 @@ function AttributionTable({ entries }: { entries: ReadonlyArray<ResourceAttribut
);
}
-export function ResourceTelemetryDiagnostics() {
+export function ResourceTelemetryDiagnostics({
+ environmentId,
+}: {
+ environmentId: EnvironmentId | null;
+}) {
const [windowMs, setWindowMs] = useState(15 * 60_000);
const selectedWindow =
HISTORY_WINDOWS.find((option) => option.windowMs === windowMs) ?? HISTORY_WINDOWS[1];
- const telemetry = useResourceTelemetry();
+ const telemetry = useResourceTelemetry(environmentId);
const retryTelemetry = telemetry.retry;
- const history = useResourceTelemetryHistory({
- windowMs: selectedWindow.windowMs,
- bucketMs: selectedWindow.bucketMs,
- });
- const primaryEnvironment = usePrimaryEnvironment();
+ const history = useResourceTelemetryHistory(
+ {
+ windowMs: selectedWindow.windowMs,
+ bucketMs: selectedWindow.bucketMs,
+ },
+ environmentId,
+ );
const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {
reportFailure: false,
});
const [signalingKeys, setSignalingKeys] = useState<ReadonlySet<string>>(() => new Set());
const signalingKeysRef = useRef<ReadonlySet<string>>(new Set());
- signalingKeysRef.current = signalingKeys;
- const primaryEnvironmentIdRef = useRef(primaryEnvironment?.environmentId);
- primaryEnvironmentIdRef.current = primaryEnvironment?.environmentId;
+ const environmentIdRef = useRef(environmentId);
+ useEffect(() => {
+ environmentIdRef.current = environmentId;
+ return () => {
+ environmentIdRef.current = null;
+ };
+ }, [environmentId]);
const [isRetrying, setIsRetrying] = useState(false);
const snapshot = telemetry.data;
const allT3 = snapshot?.groups.allT3;
const signalProcess = useCallback(
async (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => {
+ const targetEnvironmentId = environmentIdRef.current;
+ if (targetEnvironmentId === null) return;
const identityKey = processIdentityKey(process);
if (signalingKeysRef.current.has(identityKey)) return;
const nextSignalingKeys = new Set(signalingKeysRef.current).add(identityKey);
@@ -889,13 +901,12 @@ export function ResourceTelemetryDiagnostics() {
return;
}
}
- const environmentId = primaryEnvironmentIdRef.current;
- if (environmentId === undefined) {
+ if (environmentIdRef.current !== targetEnvironmentId) {
clearSignaling();
return;
}
void signalServerProcess({
- environmentId,
+ environmentId: targetEnvironmentId,
input: {
pid: process.identity.pid,
startTimeMs: process.identity.startTimeMs,
diff --git a/apps/web/src/components/settings/ScopedSwitch.tsx b/apps/web/src/components/settings/ScopedSwitch.tsx
new file mode 100644
index 00000000000..06c798f89dd
--- /dev/null
+++ b/apps/web/src/components/settings/ScopedSwitch.tsx
@@ -0,0 +1,19 @@
+import type { ServerSettings } from "@t3tools/contracts";
+import type { ComponentProps } from "react";
+
+import { Switch } from "../ui/switch";
+import { useScopedSettingsMixed } from "./useScopedSettings";
+
+/**
+ * A switch for a server setting that renders the mixed state when the
+ * selected targets disagree on `settingKeys`. Clicking a mixed switch turns
+ * it on everywhere, the macOS mixed-checkbox convention.
+ */
+export function ScopedSwitch({
+ settingKeys,
+ checked,
+ ...props
+}: ComponentProps<typeof Switch> & { settingKeys: readonly (keyof ServerSettings)[] }) {
+ const mixed = useScopedSettingsMixed(settingKeys);
+ return <Switch {...props} mixed={mixed} checked={mixed ? false : checked} />;
+}
diff --git a/apps/web/src/components/settings/SettingInheritance.test.ts b/apps/web/src/components/settings/SettingInheritance.test.ts
new file mode 100644
index 00000000000..384dc353cb9
--- /dev/null
+++ b/apps/web/src/components/settings/SettingInheritance.test.ts
@@ -0,0 +1,57 @@
+import { DEFAULT_SERVER_SETTINGS, EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
+import { describe, expect, it } from "vite-plus/test";
+
+import { settingInheritanceLayers } from "./SettingInheritance";
+
+const environmentId = EnvironmentId.make("laptop");
+const projectId = ProjectId.make("project");
+
+describe("settingInheritanceLayers", () => {
+ it("marks the built-in default effective when nothing is set", () => {
+ const resolved = resolveProjectSettings(DEFAULT_SERVER_SETTINGS, null);
+ const layers = settingInheritanceLayers(
+ { environmentId, label: "Laptop", projectId: null, ...resolved },
+ DEFAULT_SERVER_SETTINGS,
+ "defaultAutoPull",
+ );
+ expect(layers.map((layer) => [layer.label, layer.value, layer.effective])).toEqual([
+ ["Laptop", "Inherits", false],
+ ["Default", "Off", true],
+ ]);
+ });
+
+ it("walks project override, environment value, then built-in default", () => {
+ const settings = {
+ ...DEFAULT_SERVER_SETTINGS,
+ defaultAutoPull: true,
+ projectSettingsOverrides: { [projectId]: { defaultAutoPull: false } },
+ };
+ const resolved = resolveProjectSettings(settings, projectId);
+ const layers = settingInheritanceLayers(
+ { environmentId, label: "Laptop", projectId, ...resolved },
+ settings,
+ "defaultAutoPull",
+ );
+ expect(layers.map((layer) => [layer.label, layer.value, layer.effective])).toEqual([
+ ["Project", "Off", true],
+ ["Laptop", "On", false],
+ ["Default", "Off", false],
+ ]);
+ const inherited = settingInheritanceLayers(
+ {
+ environmentId,
+ label: "Laptop",
+ projectId,
+ ...resolveProjectSettings(settings, ProjectId.make("other")),
+ },
+ settings,
+ "defaultAutoPull",
+ );
+ expect(inherited.map((layer) => [layer.value, layer.effective])).toEqual([
+ ["Inherits", false],
+ ["On", true],
+ ["Off", false],
+ ]);
+ });
+});
diff --git a/apps/web/src/components/settings/SettingInheritance.tsx b/apps/web/src/components/settings/SettingInheritance.tsx
new file mode 100644
index 00000000000..4bec97f9132
--- /dev/null
+++ b/apps/web/src/components/settings/SettingInheritance.tsx
@@ -0,0 +1,303 @@
+import {
+ DEFAULT_SERVER_SETTINGS,
+ resolveEnvironmentMachineKind,
+ type ServerSettings,
+} from "@t3tools/contracts";
+import { CheckIcon, LayersIcon } from "lucide-react";
+import * as Equal from "effect/Equal";
+
+import { cn } from "../../lib/utils";
+import type { EnvironmentPresentation } from "../../state/environments";
+import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
+import { resolveEnvModeLabel } from "../BranchToolbar.logic";
+import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDetail.logic";
+import { Button } from "../ui/button";
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import type { ProjectOverrideEntry, ScopedSettingsTarget } from "./scopedSettings";
+import { isProjectScopedSettingKey } from "./scopedSettings";
+
+interface InheritanceLayer {
+ readonly key: "project" | "environment" | "built-in";
+ readonly label: string;
+ readonly value: string;
+ readonly effective: boolean;
+ readonly set: boolean;
+}
+
+const WRITING_STYLE_LABELS: Record<string, string> = {
+ repo_conventions: "Repository conventions",
+ conventional_commits: "Conventional Commits",
+ custom: "Custom instructions",
+};
+
+/** Human labels for the values the chain can show; falls back to a type summary. */
+function formatValue(key: keyof ServerSettings, value: unknown): string {
+ if (value === null || value === undefined) {
+ return key === "pullRequestMergeMethod"
+ ? "Last selected"
+ : key === "sidebarAutoSettleAfterDays"
+ ? "Never"
+ : key === "defaultModelSelection"
+ ? "Automatic"
+ : key === "sourceControlWriterModelSelection"
+ ? "Text generation model"
+ : "Not set";
+ }
+ if (typeof value === "boolean") return value ? "On" : "Off";
+ if (typeof value === "number") {
+ return key === "sidebarAutoSettleAfterDays"
+ ? `${value} ${value === 1 ? "day" : "days"}`
+ : String(value);
+ }
+ if (typeof value === "string") {
+ if (key === "defaultThreadEnvMode" && (value === "local" || value === "worktree")) {
+ return resolveEnvModeLabel(value);
+ }
+ if (key === "pullRequestMergeMethod" && value in PULL_REQUEST_MERGE_METHOD_LABELS) {
+ return PULL_REQUEST_MERGE_METHOD_LABELS[
+ value as keyof typeof PULL_REQUEST_MERGE_METHOD_LABELS
+ ];
+ }
+ return value === "" ? "Empty" : value;
+ }
+ if (Array.isArray(value)) return `${value.length} ${value.length === 1 ? "item" : "items"}`;
+ if (typeof value === "object") {
+ if ("model" in value && typeof value.model === "string") return value.model;
+ if ("mode" in value && typeof value.mode === "string") {
+ return WRITING_STYLE_LABELS[value.mode] ?? value.mode;
+ }
+ }
+ return "Custom";
+}
+
+/**
+ * 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.
+ */
+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 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",
+ });
+ }
+ layers.push({
+ key: "environment",
+ label: target.label,
+ value: environmentSet ? formatValue(key, environmentValue) : "Inherits",
+ effective: projectSource !== "project" && environmentSet,
+ set: environmentSet,
+ });
+ layers.push({
+ key: "built-in",
+ label: "Default",
+ value: formatValue(key, builtIn),
+ effective: projectSource !== "project" && !environmentSet,
+ set: true,
+ });
+ return layers;
+}
+
+export type SettingInheritanceState =
+ | "default"
+ | "environment"
+ | "inherited"
+ | "overridden"
+ | "mixed";
+
+/**
+ * A small indicator beside a row's title that opens a top-down view of where
+ * the setting's value comes from on each selected target. It sits inline so
+ * narrowing to a project does not add a caption line to every row.
+ */
+export interface SettingOverridingProject extends ProjectOverrideEntry {
+ readonly label: string;
+ /** Jumps the breadcrumb to this project so its override can be edited. */
+ readonly open: () => void;
+}
+
+export function SettingInheritance({
+ state,
+ summary,
+ targets,
+ environments,
+ keys,
+ overridingProjects = [],
+ onClearOverrides,
+}: {
+ state: SettingInheritanceState;
+ summary: string;
+ targets: readonly ScopedSettingsTarget[];
+ environments: readonly Pick<EnvironmentPresentation, "environmentId" | "serverConfig">[];
+ keys: readonly (keyof ServerSettings)[];
+ /** At environment scope: projects whose own value hides the environment's. */
+ overridingProjects?: readonly SettingOverridingProject[];
+ onClearOverrides?: (entries: readonly ProjectOverrideEntry[]) => void;
+}) {
+ const key = keys[0];
+ if (!key || targets.length === 0) return null;
+ const overrideSummary =
+ overridingProjects.length > 0
+ ? `${summary} · ${overridingProjects.length} project ${overridingProjects.length === 1 ? "override" : "overrides"}`
+ : summary;
+ const chains = targets.flatMap((target) => {
+ const environment = environments.find(
+ (candidate) => candidate.environmentId === target.environmentId,
+ );
+ if (!environment?.serverConfig) return [];
+ return [
+ {
+ target,
+ environment: { ...environment, serverConfig: environment.serverConfig },
+ machine: resolveEnvironmentMachineKind(environment.serverConfig),
+ layers: settingInheritanceLayers(target, environment.serverConfig.settings, key),
+ },
+ ];
+ });
+ return (
+ <Popover>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <PopoverTrigger
+ render={
+ <Button
+ size="icon-micro"
+ variant="ghost-muted"
+ aria-label={`${overrideSummary}. Show where this value comes from`}
+ className={cn(
+ "[--control-icon-color:currentColor]",
+ state === "overridden"
+ ? "text-primary hover:text-primary"
+ : state === "mixed"
+ ? "text-warning hover:text-warning"
+ : state === "environment"
+ ? "text-foreground/70 hover:text-foreground"
+ : "text-muted-foreground/60 hover:text-foreground",
+ )}
+ />
+ }
+ />
+ }
+ >
+ <LayersIcon className="size-3" />
+ </TooltipTrigger>
+ <TooltipPopup side="top">{overrideSummary}</TooltipPopup>
+ </Tooltip>
+ <PopoverPopup
+ align="start"
+ className="w-72 max-w-[calc(100vw-2rem)]"
+ viewportClassName="p-0 [--viewport-inline-padding:0px]"
+ >
+ <div className="divide-y divide-border/60">
+ {chains.map(({ target, environment, machine, layers }) => (
+ <section
+ key={`${target.environmentId}:${target.projectId ?? ""}`}
+ className="px-3 py-2.5"
+ >
+ <h4 className="flex items-center gap-1.5 pb-1.5 text-xs font-medium text-muted-foreground">
+ <EnvironmentMachineIcon aria-hidden kind={machine} className="size-3.5 shrink-0" />
+ <span className="min-w-0 truncate">{target.label}</span>
+ </h4>
+ <ol role="list" className="text-sm">
+ {layers.map((layer) => (
+ <li
+ key={layer.key}
+ className={cn(
+ "grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 rounded-md px-2 py-1",
+ layer.effective && "bg-foreground/[0.06]",
+ )}
+ >
+ <span
+ className={cn(
+ "min-w-0 truncate",
+ layer.effective ? "font-medium text-foreground" : "text-muted-foreground",
+ )}
+ >
+ {layer.key === "environment" ? "Environment" : layer.label}
+ </span>
+ <span
+ className={cn(
+ "flex items-center gap-1.5 tabular-nums",
+ layer.effective
+ ? "text-foreground"
+ : layer.set
+ ? "text-muted-foreground"
+ : "text-muted-foreground/60",
+ )}
+ >
+ <span className="max-w-32 truncate">{layer.value}</span>
+ {layer.effective ? (
+ <CheckIcon aria-hidden className="size-3.5 shrink-0 text-primary" />
+ ) : (
+ <span aria-hidden className="size-3.5 shrink-0" />
+ )}
+ </span>
+ </li>
+ ))}
+ </ol>
+ {(() => {
+ const overriding = overridingProjects.filter(
+ (project) => project.environmentId === target.environmentId,
+ );
+ if (overriding.length === 0) return null;
+ const overrides = environment.serverConfig.settings.projectSettingsOverrides;
+ return (
+ <div className="mt-2 border-t border-border/60 pt-2">
+ <div className="flex items-center justify-between gap-3 px-2 text-xs text-muted-foreground">
+ <span>Overridden by</span>
+ {onClearOverrides ? (
+ <button
+ type="button"
+ className="cursor-pointer font-medium text-foreground underline-offset-2 hover:underline focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => onClearOverrides(overriding)}
+ >
+ Reset {overriding.length === 1 ? "it" : "all"}
+ </button>
+ ) : null}
+ </div>
+ <ul role="list" className="mt-0.5 text-sm">
+ {overriding.map((project) => (
+ <li
+ key={project.projectId}
+ className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 px-2 py-1"
+ >
+ <button
+ type="button"
+ className="min-w-0 cursor-pointer truncate text-left text-foreground underline-offset-2 hover:underline focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={project.open}
+ >
+ {project.label}
+ </button>
+ <span className="max-w-32 truncate text-muted-foreground tabular-nums">
+ {isProjectScopedSettingKey(key)
+ ? formatValue(key, overrides[project.projectId]?.[key])
+ : null}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+ })()}
+ </section>
+ ))}
+ </div>
+ </PopoverPopup>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsBreadcrumb.tsx b/apps/web/src/components/settings/SettingsBreadcrumb.tsx
index bb631187cb1..5c1cf73f70d 100644
--- a/apps/web/src/components/settings/SettingsBreadcrumb.tsx
+++ b/apps/web/src/components/settings/SettingsBreadcrumb.tsx
@@ -1,9 +1,37 @@
+import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
+import { LayersIcon } from "lucide-react";
+import type { ReactNode } from "react";
+
+import { cn } from "../../lib/utils";
+import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
+import type { EnvironmentPresentation } from "../../state/environments";
+import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
+import { ProjectFavicon } from "../ProjectFavicon";
+import {
+ Menu,
+ MenuPopup,
+ MenuRadioGroup,
+ MenuRadioItem,
+ MenuRadioItemIndicator,
+ MenuSeparator,
+ MenuTrigger,
+} from "../ui/menu";
import {
WorkspaceBreadcrumb,
WorkspaceBreadcrumbItem,
WorkspaceBreadcrumbSeparator,
} from "../WorkspaceBreadcrumb";
import { SETTINGS_SECTION_LABELS } from "./settingsSearch";
+import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
+import {
+ ALL_ENVIRONMENTS_VALUE,
+ ALL_PROJECTS_VALUE,
+ environmentAxisValue,
+ projectAxisValue,
+ selectEnvironmentAxis,
+ selectProjectAxis,
+ settingsScopeEnvironmentLabel,
+} from "./settingsScopeAxis";
const SETTINGS_BREADCRUMB_LABELS: Readonly<Record<string, string>> = {
...SETTINGS_SECTION_LABELS,
@@ -15,7 +43,27 @@ function settingsBreadcrumbLabel(pathname: string): string | null {
return SETTINGS_BREADCRUMB_LABELS[normalizedPathname] ?? null;
}
-export function SettingsBreadcrumb({ pathname }: { pathname: string }) {
+export interface SettingsScopeBreadcrumbProps {
+ readonly value: SettingsScopeSearch;
+ readonly groups: readonly SidebarProjectSnapshot[];
+ readonly environments: readonly EnvironmentPresentation[];
+ readonly onChange: (next: SettingsScopeSearch) => void;
+}
+
+/**
+ * `Settings / Section / Environment / Project`. The last two crumbs are the
+ * targets a change applies to and read like the usage page's filter: muted at
+ * "all", foreground once narrowed. A project is the same project on every
+ * environment, so the environment crumb alone decides where a project
+ * override is written.
+ */
+export function SettingsBreadcrumb({
+ pathname,
+ scope,
+}: {
+ pathname: string;
+ scope?: SettingsScopeBreadcrumbProps | undefined;
+}) {
const sectionLabel = settingsBreadcrumbLabel(pathname);
return (
@@ -29,6 +77,158 @@ export function SettingsBreadcrumb({ pathname }: { pathname: string }) {
<WorkspaceBreadcrumbItem current className="truncate">
{sectionLabel ?? "Settings"}
</WorkspaceBreadcrumbItem>
+ {scope ? (
+ <>
+ <WorkspaceBreadcrumbSeparator />
+ <WorkspaceBreadcrumbItem className="min-w-0 shrink">
+ <EnvironmentScopeMenu {...scope} />
+ </WorkspaceBreadcrumbItem>
+ <WorkspaceBreadcrumbSeparator />
+ <WorkspaceBreadcrumbItem className="min-w-0 shrink">
+ <ProjectScopeMenu {...scope} />
+ </WorkspaceBreadcrumbItem>
+ </>
+ ) : null}
</WorkspaceBreadcrumb>
);
}
+
+function ScopeMenu({
+ ariaLabel,
+ icon,
+ label,
+ narrowed,
+ children,
+}: {
+ ariaLabel: string;
+ icon: ReactNode;
+ label: string;
+ narrowed: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <Menu>
+ <MenuTrigger
+ aria-label={ariaLabel}
+ className={cn(
+ "inline-flex min-w-0 max-w-56 cursor-pointer items-center gap-1.5 rounded-sm text-left transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring",
+ narrowed ? "text-foreground" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {icon}
+ <span className="min-w-0 truncate">{label}</span>
+ </MenuTrigger>
+ <MenuPopup align="start" className="w-64 max-w-[calc(100vw-2rem)]">
+ {children}
+ </MenuPopup>
+ </Menu>
+ );
+}
+
+function EnvironmentScopeMenu({
+ value,
+ groups,
+ environments,
+ onChange,
+}: SettingsScopeBreadcrumbProps) {
+ const resolved = resolveSettingsScope(value, groups, environments);
+ const environmentValue = environmentAxisValue(
+ value,
+ resolved.kind === "checkout" ? resolved.environmentId : null,
+ );
+ const selected = environments.find(
+ (environment) => environment.environmentId === environmentValue,
+ );
+ return (
+ <ScopeMenu
+ ariaLabel="Environment scope"
+ narrowed={environmentValue !== ALL_ENVIRONMENTS_VALUE}
+ icon={
+ selected ? (
+ <EnvironmentMachineIcon
+ aria-hidden
+ kind={resolveEnvironmentMachineKind(selected.serverConfig)}
+ className="size-3.5 shrink-0"
+ />
+ ) : null
+ }
+ label={
+ selected
+ ? settingsScopeEnvironmentLabel(selected, environments)
+ : environmentValue !== ALL_ENVIRONMENTS_VALUE
+ ? "Unavailable environment"
+ : "All environments"
+ }
+ >
+ <MenuRadioGroup
+ value={environmentValue}
+ onValueChange={(next) => {
+ if (typeof next === "string") onChange(selectEnvironmentAxis(value, next));
+ }}
+ >
+ <MenuRadioItem value={ALL_ENVIRONMENTS_VALUE}>
+ <span className="flex min-w-0 items-center gap-2">
+ <LayersIcon aria-hidden className="size-3.5" />
+ <span className="min-w-0 flex-1 truncate">All environments</span>
+ <MenuRadioItemIndicator />
+ </span>
+ </MenuRadioItem>
+ <MenuSeparator />
+ {environments.map((environment) => (
+ <MenuRadioItem key={environment.environmentId} value={environment.environmentId}>
+ <span className="flex min-w-0 items-center gap-2">
+ <EnvironmentMachineIcon
+ aria-hidden
+ kind={resolveEnvironmentMachineKind(environment.serverConfig)}
+ className="size-3.5"
+ />
+ <span className="min-w-0 flex-1 truncate">
+ {settingsScopeEnvironmentLabel(environment, environments)}
+ </span>
+ {environment.connection.phase === "connected" ? null : (
+ <span className="shrink-0 text-xs text-muted-foreground">Offline</span>
+ )}
+ <MenuRadioItemIndicator />
+ </span>
+ </MenuRadioItem>
+ ))}
+ </MenuRadioGroup>
+ </ScopeMenu>
+ );
+}
+
+function ProjectScopeMenu({ value, groups, onChange }: SettingsScopeBreadcrumbProps) {
+ const selected = groups.find((group) => group.projectKey === value.project);
+ return (
+ <ScopeMenu
+ ariaLabel="Project scope"
+ narrowed={value.project !== undefined}
+ icon={selected ? <ProjectFavicon project={selected} className="size-3.5 shrink-0" /> : null}
+ label={selected?.displayName ?? (value.project ? "Unavailable project" : "All projects")}
+ >
+ <MenuRadioGroup
+ value={projectAxisValue(value)}
+ onValueChange={(next) => {
+ if (typeof next === "string") onChange(selectProjectAxis(value, next));
+ }}
+ >
+ <MenuRadioItem value={ALL_PROJECTS_VALUE}>
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="min-w-0 flex-1 truncate">All projects</span>
+ <MenuRadioItemIndicator />
+ </span>
+ </MenuRadioItem>
+ <MenuSeparator />
+ {groups.map((group) => (
+ <MenuRadioItem key={group.projectKey} value={group.projectKey}>
+ <span className="flex min-w-0 items-center gap-2">
+ <ProjectFavicon project={group} className="size-3.5" />
+ <span className="min-w-0 flex-1 truncate">{group.displayName}</span>
+ <MenuRadioItemIndicator />
+ </span>
+ </MenuRadioItem>
+ ))}
+ </MenuRadioGroup>
+ </ScopeMenu>
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 14368050954..17af7cc9a11 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -3,7 +3,6 @@ import { ArchiveIcon, ArchiveX, ChevronRightIcon, SettingsIcon } from "lucide-re
import { Link, useNavigate } from "@tanstack/react-router";
import type { CSSProperties, ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { useAtomValue } from "@effect/atom-react";
import {
type BackgroundActivityProfile,
type DesktopUpdateChannel,
@@ -70,13 +69,19 @@ import {
useTheme,
} from "../../hooks/useTheme";
import { useLocalStorage } from "../../hooks/useLocalStorage";
-import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
+import {
+ useScopedSettings,
+ useScopedSettingsMixed,
+ useUpdateScopedSettings,
+} from "./useScopedSettings";
+import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
+import { useSettingsScope } from "./SettingsScopeContext";
+import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
import { useThreadActions } from "../../hooks/useThreadActions";
import { useDesktopUpdateState } from "../../state/desktopUpdate";
import {
getCustomModelOptionsByInstance,
resolveAppModelSelectionState,
- withoutPlanAgentSelection,
} from "../../modelSelection";
import {
applyProviderInstanceSettings,
@@ -85,13 +90,7 @@ import {
} from "../../providerInstances";
import { ensureLocalApi, readLocalApi } from "../../localApi";
import { isMacPlatform } from "../../lib/utils";
-import {
- primaryServerConfigAtom,
- primaryServerObservabilityAtom,
- primaryServerProvidersAtom,
-} from "../../state/server";
-import { useProjects } from "../../state/entities";
-import { usePrimaryEnvironmentId } from "../../state/environments";
+import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import { formatRelativeTimeLabel } from "../../timestampFormat";
import { Button } from "../ui/button";
@@ -118,7 +117,6 @@ import {
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
} from "../../appearanceFonts";
import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
-import { SharedSettingsMismatchAlert } from "./SharedSettingsMismatchAlert";
import { discoverInstalledFonts, FontFamilyPicker, useFontEnumeration } from "./FontFamilyPicker";
import {
NumberField,
@@ -129,6 +127,7 @@ import {
} from "../ui/number-field";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
+import { ScopedSwitch } from "./ScopedSwitch";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { ThemeLibrary } from "./ThemeSettings";
@@ -136,7 +135,6 @@ import {
backgroundActivityOverrideSettings,
backgroundActivitySharedPolicySettings,
durationToSeconds,
- formatDiagnosticsDescription,
getChangedBrowserSettingLabels,
getChangedTypographySettingLabels,
normalizeIntervalSeconds,
@@ -488,8 +486,8 @@ export function useSettingsRestore(onRestored?: () => void) {
clearThemeHalves,
themeHalves,
} = useTheme();
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const isTextGenerationModelDirty = !Equal.equals(
settings.textGenerationModelSelection ?? null,
@@ -781,8 +779,8 @@ function BackgroundActivityAdvancedDialog({
readonly open: boolean;
readonly onOpenChange: (open: boolean) => void;
}) {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
const activeProfile = resolvedBackgroundActivity.profile;
const automaticGitFetchIntervalSeconds = durationToSeconds(
@@ -1059,8 +1057,8 @@ export function AppearanceSettingsPanel() {
} = useTheme();
const customThemes = useCustomThemes();
const [isImportThemeOpen, setIsImportThemeOpen] = useState(false);
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const environmentStageLabel = useEnvironmentStageLabel();
const showEnvironmentIdentification =
resolveEnvironmentIdentificationPillLabel(environmentStageLabel) !== null;
@@ -1353,7 +1351,7 @@ export function AppearanceSettingsPanel() {
}
function useFontDefaultFamilies() {
- const settings = usePrimarySettings();
+ const settings = useScopedSettings();
// An unset preference shows the font it resolves to on this machine; the
// default stacks are the platform's own faces, so the name is probed, not
// hardcoded.
@@ -1373,8 +1371,8 @@ function useFontDefaultFamilies() {
}
function InterfaceFontRow({ preview }: { preview?: ReactNode }) {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const defaults = useFontDefaultFamilies();
return (
<FontFamilySettingsRow
@@ -1404,8 +1402,8 @@ function InterfaceFontRow({ preview }: { preview?: ReactNode }) {
}
function PromptFontRow() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const defaults = useFontDefaultFamilies();
return (
<FontFamilySettingsRow
@@ -1443,8 +1441,8 @@ function CodeFontRow({
description?: string;
preview?: ReactNode;
}) {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const defaults = useFontDefaultFamilies();
return (
<FontFamilySettingsRow
@@ -1476,8 +1474,8 @@ function CodeFontRow({
}
function TerminalFontRow() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const defaults = useFontDefaultFamilies();
return (
<FontFamilySettingsRow
@@ -1517,8 +1515,8 @@ function TerminalFontRow() {
}
function FontSmoothingRow() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
if (!isMacPlatform(navigator.platform)) return null;
return (
<SettingsRow
@@ -1546,8 +1544,8 @@ function FontSmoothingRow() {
}
function WordWrapRow() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
return (
<SettingsRow
{...searchableSetting("word-wrap")}
@@ -1589,7 +1587,7 @@ function FontSettingsGroup() {
* under each row show every surface the choice reaches.
*/
function SimpleFontRows() {
- const settings = usePrimarySettings();
+ const settings = useScopedSettings();
return (
<>
<InterfaceFontRow preview={<PromptFontPreview />} />
@@ -1930,8 +1928,8 @@ const LEGACY_FEATURE_TARGET_IDS: ReadonlySet<string> = new Set([
* jump to one of the rows unfolds the section.
*/
function LegacyFeaturesSection() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const [open, setOpen] = useState(false);
const searchTargetId = useSettingsSearchTargetId();
const targetRef = useSettingsSearchTarget<HTMLElement>("legacy-features");
@@ -1969,29 +1967,7 @@ function LegacyFeaturesSection() {
<Switch
checked={settings.planModeEnabled}
onCheckedChange={(checked) => {
- const planModeEnabled = Boolean(checked);
- const textGenerationModelSelection = withoutPlanAgentSelection(
- settings.textGenerationModelSelection,
- );
- const sourceControlWriterModelSelection = withoutPlanAgentSelection(
- settings.sourceControlWriterModelSelection,
- );
- updateSettings({
- planModeEnabled,
- ...(planModeEnabled
- ? {}
- : {
- ...(textGenerationModelSelection &&
- textGenerationModelSelection !== settings.textGenerationModelSelection
- ? { textGenerationModelSelection }
- : {}),
- ...(sourceControlWriterModelSelection &&
- sourceControlWriterModelSelection !==
- settings.sourceControlWriterModelSelection
- ? { sourceControlWriterModelSelection }
- : {}),
- }),
- });
+ updateSettings({ planModeEnabled: Boolean(checked) });
}}
aria-label="Plan mode (legacy)"
/>
@@ -2012,10 +1988,12 @@ function LegacyFeaturesSection() {
/>
<SettingsRow
serverScoped
+ settingKeys={["enableLegacyTokenStreaming"]}
{...searchableSetting("legacy-token-streaming")}
description="Stream output token by token. This legacy mode is slower and harder to follow."
control={
- <Switch
+ <ScopedSwitch
+ settingKeys={["enableLegacyTokenStreaming"]}
checked={settings.enableLegacyTokenStreaming}
onCheckedChange={(checked) => {
if (!checked) {
@@ -2058,25 +2036,32 @@ function LegacyFeaturesSection() {
}
export function GeneralSettingsPanel() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const navigate = useNavigate();
- const environmentId = usePrimaryEnvironmentId();
+ const { scope, environment, connectedEnvironments } = useSettingsScope();
+ // The representative environment supplies the provider list for pickers;
+ // a fanned-out model choice is validated against every target before it
+ // is written. Per-machine tuning (background activity overrides) still
+ // needs exactly one environment.
+ const environmentId = environment?.environmentId ?? null;
+ const isEnvironmentScope = scope.environmentIds.length === 1 && environmentId !== null;
+ const hasServerTargets = connectedEnvironments.length > 0;
const [backgroundActivityDialogOpen, setBackgroundActivityDialogOpen] = useState(false);
const lastEnabledProjectGroupingMode = useRef<SidebarProjectGroupingMode>(
readLastEnabledProjectGroupingMode(),
);
- const observability = useAtomValue(primaryServerObservabilityAtom);
- const serverProviders = useAtomValue(primaryServerProvidersAtom);
+ const serverProviders = environment?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
const supportsAutoSettlement =
- useAtomValue(primaryServerConfigAtom)?.environment.capabilities.threadAutoSettlement === true;
- const diagnosticsDescription = formatDiagnosticsDescription({
- localTracingEnabled: observability?.localTracingEnabled ?? false,
- otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
- otlpTracesUrl: observability?.otlpTracesUrl,
- otlpMetricsEnabled: observability?.otlpMetricsEnabled ?? false,
- otlpMetricsUrl: observability?.otlpMetricsUrl,
- });
+ connectedEnvironments.length > 0 &&
+ connectedEnvironments.every(
+ (target) => target.serverConfig?.environment.capabilities.threadAutoSettlement === true,
+ );
+ const supportsRestartContinuation =
+ connectedEnvironments.length > 0 &&
+ connectedEnvironments.every(
+ (target) => target.serverConfig?.environment.capabilities.threadRestartContinuation === true,
+ );
const textGenerationProviders = serverProviders.filter(
(provider) => provider.supportsTextGeneration !== false,
@@ -2109,9 +2094,16 @@ export function GeneralSettingsPanel() {
settings.textGenerationModelSelection ?? null,
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
);
+ const textGenerationModelDisabledReason = useScopedModelDisabledReason(
+ settings,
+ textGenerationModelInstanceEntries,
+ );
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
const activeBackgroundActivityProfile = resolvedBackgroundActivity.profile;
const backgroundActivityProfileOption = resolveBackgroundActivityProfileOption(settings);
+ const mixedBackgroundActivity = useScopedSettingsMixed(["backgroundActivity"]);
+ const mixedAddProjectBaseDirectory = useScopedSettingsMixed(["addProjectBaseDirectory"]);
+ const mixedTextGenerationModel = useScopedSettingsMixed(["textGenerationModelSelection"]);
const backgroundActivityDescription =
backgroundActivityProfileOption === "advanced"
? `${ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION} Shared policy: ${
@@ -2125,7 +2117,7 @@ export function GeneralSettingsPanel() {
return (
<SettingsPageContainer>
- <SharedSettingsMismatchAlert />
+ <ProjectDefaultsSettings category="general" />
<SettingsSection id="organization" title="Organization">
<SettingsRow
{...searchableSetting("project-grouping")}
@@ -2167,6 +2159,7 @@ export function GeneralSettingsPanel() {
<>
<SettingsRow
serverScoped
+ settingKeys={["sidebarAutoSettleOnMerge"]}
{...searchableSetting("auto-settle-merged-threads")}
description="Settle a thread when its pull request merges. Closed pull requests still settle automatically."
resetAction={
@@ -2183,7 +2176,8 @@ export function GeneralSettingsPanel() {
) : null
}
control={
- <Switch
+ <ScopedSwitch
+ settingKeys={["sidebarAutoSettleOnMerge"]}
checked={settings.sidebarAutoSettleOnMerge}
onCheckedChange={(checked) =>
updateSettings({ sidebarAutoSettleOnMerge: Boolean(checked) })
@@ -2195,6 +2189,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
serverScoped
+ settingKeys={["sidebarAutoSettleAfterDays"]}
{...searchableSetting("auto-settle-inactive-threads")}
description="Sidebar threads with no activity for this long settle automatically."
resetAction={
@@ -2212,7 +2207,8 @@ export function GeneralSettingsPanel() {
) : null
}
control={
- <Switch
+ <ScopedSwitch
+ settingKeys={["sidebarAutoSettleAfterDays"]}
checked={settings.sidebarAutoSettleAfterDays !== null}
onCheckedChange={(checked) =>
updateSettings({
@@ -2226,6 +2222,7 @@ export function GeneralSettingsPanel() {
{settings.sidebarAutoSettleAfterDays !== null ? (
<SettingsRow
serverScoped
+ settingKeys={["sidebarAutoSettleAfterDays"]}
title={searchableSetting("days-before-auto-settle").title}
description="Any new activity un-settles a thread automatically."
control={
@@ -2423,6 +2420,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
serverScoped
+ settingKeys={["enableProviderUpdateChecks"]}
{...searchableSetting("provider-update-checks")}
description="Check installed provider CLIs for newer available versions."
resetAction={
@@ -2439,7 +2437,8 @@ export function GeneralSettingsPanel() {
) : null
}
control={
- <Switch
+ <ScopedSwitch
+ settingKeys={["enableProviderUpdateChecks"]}
checked={settings.enableProviderUpdateChecks}
onCheckedChange={(checked) =>
updateSettings({ enableProviderUpdateChecks: Boolean(checked) })
@@ -2452,10 +2451,17 @@ export function GeneralSettingsPanel() {
<SettingsRow
{...searchableSetting("continue-threads-after-server-update")}
serverScoped
- description="Automatically resume interrupted threads after an update, crash, or machine restart. Applies to this environment and all connected environments that support it. Update older servers first."
+ settingKeys={["continueThreadsAfterServerUpdate"]}
+ description="Automatically resume interrupted threads after an update, crash, or machine restart on the selected environments. Update older servers first."
+ status={
+ !supportsRestartContinuation
+ ? "All selected connected environments must support restart continuation."
+ : undefined
+ }
resetAction={
+ supportsRestartContinuation &&
settings.continueThreadsAfterServerUpdate !==
- DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate ? (
+ DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate ? (
<SettingResetButton
label="continue threads after restarts"
onClick={() =>
@@ -2468,8 +2474,10 @@ export function GeneralSettingsPanel() {
) : null
}
control={
- <Switch
+ <ScopedSwitch
+ settingKeys={["continueThreadsAfterServerUpdate"]}
checked={settings.continueThreadsAfterServerUpdate}
+ disabled={!supportsRestartContinuation}
onCheckedChange={(checked) =>
updateSettings({ continueThreadsAfterServerUpdate: Boolean(checked) })
}
@@ -2480,6 +2488,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
serverScoped
+ settingKeys={["backgroundActivity"]}
id={searchableSetting("background-activity").id}
title={
<span className="inline-flex items-center gap-1.5">
@@ -2502,10 +2511,10 @@ export function GeneralSettingsPanel() {
control={
<>
<Select
- value={backgroundActivityProfileOption}
+ value={mixedBackgroundActivity ? null : backgroundActivityProfileOption}
onValueChange={(value) => {
if (value === "advanced") {
- setBackgroundActivityDialogOpen(true);
+ if (isEnvironmentScope) setBackgroundActivityDialogOpen(true);
return;
}
if (
@@ -2523,7 +2532,9 @@ export function GeneralSettingsPanel() {
aria-label="Background activity profile"
>
<SelectValue>
- {BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS[backgroundActivityProfileOption]}
+ {(value: BackgroundActivityProfileOption | null) =>
+ value === null ? "Mixed" : BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS[value]
+ }
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
@@ -2536,12 +2547,14 @@ export function GeneralSettingsPanel() {
<SelectItem hideIndicator value="battery-saver">
{BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
</SelectItem>
- <SelectItem hideIndicator value="advanced">
- {BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced}
+ <SelectItem hideIndicator value="advanced" disabled={!isEnvironmentScope}>
+ {isEnvironmentScope
+ ? BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced
+ : `${BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced} (one environment)`}
</SelectItem>
</SelectPopup>
</Select>
- {backgroundActivityProfileOption === "advanced" ? (
+ {backgroundActivityProfileOption === "advanced" && isEnvironmentScope ? (
<Tooltip>
<TooltipTrigger
render={
@@ -2559,7 +2572,7 @@ export function GeneralSettingsPanel() {
</Tooltip>
) : null}
<BackgroundActivityAdvancedDialog
- open={backgroundActivityDialogOpen}
+ open={backgroundActivityDialogOpen && isEnvironmentScope}
onOpenChange={setBackgroundActivityDialogOpen}
/>
</>
@@ -2568,24 +2581,9 @@ export function GeneralSettingsPanel() {
</SettingsSection>
<SettingsSection id="projects-and-threads" title="Projects & threads">
- <SettingsRow
- {...searchableSetting("new-threads")}
- description="Choose the default model and workspace for all projects or a specific project."
- control={
- <Button
- render={
- <Link to="/settings/projects" search={{ project: undefined, machine: undefined }} />
- }
- size="sm"
- variant="outline"
- >
- Project settings
- </Button>
- }
- />
-
<SettingsRow
serverScoped
+ settingKeys={["newWorktreesStartFromOrigin"]}
{...searchableSetting("start-from-origin")}
description="Creates the worktree from the latest matching branch on origin instead of your local branch."
resetAction={
@@ -2603,7 +2601,8 @@ export function GeneralSettingsPanel() {
) : null
}
control={
- <Switch
+ <ScopedSwitch
+ settingKeys={["newWorktreesStartFromOrigin"]}
checked={settings.newWorktreesStartFromOrigin}
onCheckedChange={(checked) =>
updateSettings({ newWorktreesStartFromOrigin: Boolean(checked) })
@@ -2614,6 +2613,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
serverScoped
+ settingKeys={["addProjectBaseDirectory"]}
{...searchableSetting("add-project-starts-in")}
description='Leave empty to use "~/" when the Add Project browser opens.'
resetAction={
@@ -2633,9 +2633,9 @@ export function GeneralSettingsPanel() {
<DraftInput
size="sm"
className="w-full sm:w-72"
- value={settings.addProjectBaseDirectory}
+ value={mixedAddProjectBaseDirectory ? "" : settings.addProjectBaseDirectory}
onCommit={(next) => updateSettings({ addProjectBaseDirectory: next })}
- placeholder="~/"
+ placeholder={mixedAddProjectBaseDirectory ? "Mixed" : "~/"}
spellCheck={false}
aria-label="Add project base directory"
/>
@@ -2768,10 +2768,11 @@ export function GeneralSettingsPanel() {
<SettingsSection id="text-generation" title="Text generation">
<SettingsRow
serverScoped
+ settingKeys={["textGenerationModelSelection"]}
{...searchableSetting("text-generation-model")}
description="Used for thread titles and other generated text on connected devices with this provider. Source control can override it."
resetAction={
- isTextGenerationModelDirty ? (
+ hasServerTargets && isTextGenerationModelDirty ? (
<SettingResetButton
label="text generation model"
onClick={() =>
@@ -2784,7 +2785,11 @@ export function GeneralSettingsPanel() {
) : null
}
control={
- !hasTextGenerationProvider ? (
+ !hasServerTargets ? (
+ <span className="text-sm text-muted-foreground">
+ Connect an environment to choose its text generation model.
+ </span>
+ ) : !hasTextGenerationProvider ? (
<span className="text-sm text-muted-foreground">
No text generation providers available.
</span>
@@ -2798,6 +2803,8 @@ export function GeneralSettingsPanel() {
modelOptionsByInstance={textGenerationModelOptionsByInstance}
triggerVariant="outline"
triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
+ {...(mixedTextGenerationModel ? { triggerLabel: "Mixed" } : {})}
+ getModelDisabledReason={textGenerationModelDisabledReason}
{...(environmentId
? {
onOpenProviderSetup: (instanceId: ProviderInstanceId) => {
@@ -2809,6 +2816,15 @@ export function GeneralSettingsPanel() {
}
: {})}
onInstanceModelChange={(instanceId, model) => {
+ const reason = textGenerationModelDisabledReason(instanceId, model);
+ if (reason) {
+ toastManager.add({
+ type: "error",
+ title: "Text generation model not saved",
+ description: reason,
+ });
+ return;
+ }
updateSettings({
textGenerationModelSelection: resolveAppModelSelectionState(
{
@@ -2870,11 +2886,23 @@ export function GeneralSettingsPanel() {
description="Current version of the application."
/>
)}
+ </SettingsSection>
+ <SettingsSection title="Diagnostics">
<SettingsRow
{...searchableSetting("diagnostics")}
- description={diagnosticsDescription}
+ description={
+ isEnvironmentScope
+ ? "Inspect processes, resource use, and logs on this environment."
+ : "Inspect processes, resource use, and logs on one environment at a time."
+ }
control={
- <Button render={<Link to="/settings/diagnostics" />} size="sm" variant="outline">
+ <Button
+ render={
+ <Link to="/settings/diagnostics" search={{ machine: environmentId ?? undefined }} />
+ }
+ size="sm"
+ variant="outline"
+ >
View diagnostics
</Button>
}
@@ -2887,25 +2915,31 @@ export function GeneralSettingsPanel() {
}
export function ArchivedThreadsPanel() {
- const projects = useProjects();
+ const { scope } = useSettingsScope();
const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
- const environmentIds = useMemo(
- () => [...new Set(projects.map((project) => project.environmentId))],
- [projects],
- );
const {
snapshots: archivedSnapshots,
error: archiveError,
isLoading: isLoadingArchive,
refresh: refreshArchivedThreads,
- } = useArchivedThreadSnapshots(environmentIds);
+ } = useArchivedThreadSnapshots(scope.environmentIds);
const archivedGroups = useMemo(() => {
+ const selectedProjectKeys =
+ scope.kind === "project" || scope.kind === "checkout"
+ ? new Set(scope.members.map((member) => `${member.environmentId}:${member.id}`))
+ : null;
const projectsByEnvironmentAndId = new Map(
archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
- snapshot.projects.map(
- (project) => [`${environmentId}:${project.id}`, { ...project, environmentId }] as const,
- ),
+ snapshot.projects
+ .filter(
+ (project) =>
+ selectedProjectKeys === null ||
+ selectedProjectKeys.has(`${environmentId}:${project.id}`),
+ )
+ .map(
+ (project) => [`${environmentId}:${project.id}`, { ...project, environmentId }] as const,
+ ),
),
);
const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
@@ -2939,7 +2973,7 @@ export function ArchivedThreadsPanel() {
}
}
return groups;
- }, [archivedSnapshots]);
+ }, [archivedSnapshots, scope]);
const handleArchivedThreadContextMenu = useCallback(
async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
@@ -3021,7 +3055,7 @@ export function ArchivedThreadsPanel() {
) : (
archivedGroups.map(({ project, threads: projectThreads }, index) => (
<SettingsSection
- key={project.id}
+ key={`${project.environmentId}:${project.id}`}
id={index === 0 ? searchableSetting("archive").id : undefined}
title={project.title}
icon={<ProjectFavicon project={project} />}
diff --git a/apps/web/src/components/settings/SettingsScopeContext.tsx b/apps/web/src/components/settings/SettingsScopeContext.tsx
new file mode 100644
index 00000000000..c758b29272d
--- /dev/null
+++ b/apps/web/src/components/settings/SettingsScopeContext.tsx
@@ -0,0 +1,65 @@
+import { createContext, type ReactNode, useContext, useMemo } from "react";
+
+import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
+import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
+import { resolveScopedSettingsTargets, selectScopedSettingsEnvironments } from "./scopedSettings";
+import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
+
+function useResolvedSettingsScope(search: SettingsScopeSearch) {
+ const groups = useSettingsProjectGroups();
+ const { environments: availableEnvironments } = useEnvironments();
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+ return useMemo(() => {
+ const scope = resolveSettingsScope(search, groups, availableEnvironments);
+ const selected = selectScopedSettingsEnvironments(
+ scope,
+ availableEnvironments,
+ primaryEnvironmentId,
+ );
+ const targets = resolveScopedSettingsTargets(scope, selected.connectedEnvironments);
+ // The representative target supplies display values; project scopes
+ // prefer the member on the primary environment, like environments do.
+ const target =
+ targets.find(
+ (candidate) => candidate.environmentId === selected.environment?.environmentId,
+ ) ??
+ targets[0] ??
+ null;
+ return { scope, groups, ...selected, targets, target };
+ }, [availableEnvironments, groups, primaryEnvironmentId, search]);
+}
+
+const SettingsScopeContext = createContext<
+ | (ReturnType<typeof useResolvedSettingsScope> & {
+ search: SettingsScopeSearch;
+ selectScope: (next: SettingsScopeSearch) => void;
+ })
+ | null
+>(null);
+
+export function SettingsScopeProvider({
+ search,
+ onChange,
+ children,
+}: {
+ search: SettingsScopeSearch;
+ onChange: (next: SettingsScopeSearch) => void;
+ children: ReactNode;
+}) {
+ const resolved = useResolvedSettingsScope(search);
+ const value = useMemo(
+ () => ({ ...resolved, search, selectScope: onChange }),
+ [onChange, resolved, search],
+ );
+ return <SettingsScopeContext value={value}>{children}</SettingsScopeContext>;
+}
+
+export function useOptionalSettingsScope() {
+ return useContext(SettingsScopeContext);
+}
+
+export function useSettingsScope() {
+ const scope = useOptionalSettingsScope();
+ if (scope === null) throw new Error("Settings scope must be read inside SettingsScopeProvider.");
+ return scope;
+}
diff --git a/apps/web/src/components/settings/SettingsScopeNotice.tsx b/apps/web/src/components/settings/SettingsScopeNotice.tsx
new file mode 100644
index 00000000000..1bf365b729e
--- /dev/null
+++ b/apps/web/src/components/settings/SettingsScopeNotice.tsx
@@ -0,0 +1,90 @@
+import { Button } from "../ui/button";
+import { Alert, AlertAction, AlertDescription } from "../ui/alert";
+import { SettingsPageContainer } from "./settingsLayout";
+import { useSettingsScope } from "./SettingsScopeContext";
+import { useEnvironments } from "../../state/environments";
+import type { SettingsScopeSearch } from "./settingsScope";
+import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
+import { useLocation, useNavigate } from "@tanstack/react-router";
+import type { EnvironmentId } from "@t3tools/contracts";
+
+/** Offer an explicit target change when a category has no settings at this scope. */
+export function SettingsScopeNotice({
+ children,
+ target,
+ targetId,
+ eligibleEnvironmentIds,
+}: {
+ children: string;
+ target: "environment" | "all" | "project" | "checkout";
+ targetId?: string;
+ eligibleEnvironmentIds?: readonly EnvironmentId[];
+}) {
+ const { selectScope, search } = useSettingsScope();
+ const navigate = useNavigate({ from: "/settings" });
+ const pathname = useLocation({ select: (location) => location.pathname });
+ const { environments } = useEnvironments();
+ const groups = useSettingsProjectGroups();
+ const choices: { label: string; search: SettingsScopeSearch }[] =
+ target === "checkout"
+ ? groups
+ .filter((group) => !search.project || group.projectKey === search.project)
+ .flatMap((group) =>
+ group.memberProjects.map((member) => ({
+ label: `${group.displayName} · ${member.environmentLabel ?? "Environment"} · ${member.workspaceRoot}`,
+ search: {
+ project: group.projectKey,
+ machine: member.environmentId,
+ checkout: member.physicalProjectKey,
+ },
+ })),
+ )
+ : target === "project"
+ ? groups.map((group) => ({
+ label: group.displayName,
+ search: { project: group.projectKey },
+ }))
+ : target === "environment"
+ ? environments
+ .filter(
+ (entry) =>
+ eligibleEnvironmentIds === undefined ||
+ eligibleEnvironmentIds.includes(entry.environmentId),
+ )
+ .map((entry) => ({
+ label: environments.some(
+ (other) =>
+ other.environmentId !== entry.environmentId && other.label === entry.label,
+ )
+ ? `${entry.label} · ${entry.displayUrl || entry.environmentId}`
+ : entry.label,
+ search: { machine: entry.environmentId },
+ }))
+ : [{ label: "Open all environments", search: {} }];
+ return (
+ <SettingsPageContainer>
+ <Alert role="status">
+ <AlertDescription>
+ <p>{children}</p>
+ <AlertAction className="flex-wrap gap-2">
+ {choices.map((choice) => (
+ <Button
+ key={JSON.stringify(choice.search)}
+ size="sm-multiline"
+ variant="outline"
+ className="max-w-full break-all text-left"
+ onClick={() => {
+ if (targetId)
+ void navigate({ to: pathname, search: () => choice.search, hash: targetId });
+ else selectScope(choice.search);
+ }}
+ >
+ {choice.label}
+ </Button>
+ ))}
+ </AlertAction>
+ </AlertDescription>
+ </Alert>
+ </SettingsPageContainer>
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsScopeSelects.tsx b/apps/web/src/components/settings/SettingsScopeSelects.tsx
deleted file mode 100644
index 6271a7313c2..00000000000
--- a/apps/web/src/components/settings/SettingsScopeSelects.tsx
+++ /dev/null
@@ -1,154 +0,0 @@
-import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
-import { LayersIcon } from "lucide-react";
-
-import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
-import type { EnvironmentPresentation } from "../../state/environments";
-import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
-import { ProjectFavicon } from "../ProjectFavicon";
-import {
- Select,
- SelectGroup,
- SelectGroupLabel,
- SelectItem,
- SelectPopup,
- SelectTrigger,
- SelectValue,
-} from "../ui/select";
-import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
-import {
- ALL_ENVIRONMENTS_VALUE,
- ALL_PROJECTS_VALUE,
- environmentAxisValue,
- projectAxisValue,
- selectEnvironmentAxis,
- selectProjectAxis,
- settingsScopeEnvironmentLabel,
-} from "./SettingsScopeSelects.logic";
-
-const TRIGGER_CLASSNAME = "w-auto min-w-0 max-w-56 justify-start";
-
-/**
- * Two independent targets: which environments a change applies to, and
- * which project it overrides. A project is the same project on every
- * environment; the environment select alone decides where the override is
- * written. Each axis defaults to "all".
- */
-export function SettingsScopeSelects({
- value,
- groups,
- environments,
- onChange,
-}: {
- value: SettingsScopeSearch;
- groups: readonly SidebarProjectSnapshot[];
- environments: readonly EnvironmentPresentation[];
- onChange: (next: SettingsScopeSearch) => void;
-}) {
- const resolved = resolveSettingsScope(value, groups, environments);
- const environmentValue = environmentAxisValue(
- value,
- resolved.kind === "checkout" ? resolved.environmentId : null,
- );
- const projectValue = projectAxisValue(value);
- const selectedEnvironment = environments.find(
- (environment) => environment.environmentId === environmentValue,
- );
- const selectedGroup = groups.find((group) => group.projectKey === value.project);
-
- return (
- <div className="flex min-w-0 items-center gap-1.5" role="group" aria-label="Settings scope">
- <Select
- value={environmentValue}
- onValueChange={(next) => {
- if (typeof next === "string") onChange(selectEnvironmentAxis(value, next));
- }}
- >
- <SelectTrigger size="compact" aria-label="Environment scope" className={TRIGGER_CLASSNAME}>
- <SelectValue>
- <span className="flex min-w-0 items-center gap-1.5">
- {selectedEnvironment ? (
- <EnvironmentMachineIcon
- aria-hidden
- kind={resolveEnvironmentMachineKind(selectedEnvironment.serverConfig)}
- className="size-3.5"
- />
- ) : (
- <LayersIcon aria-hidden className="size-3.5" />
- )}
- <span className="truncate">
- {selectedEnvironment
- ? settingsScopeEnvironmentLabel(selectedEnvironment, environments)
- : environmentValue !== ALL_ENVIRONMENTS_VALUE
- ? "Unavailable environment"
- : "All environments"}
- </span>
- </span>
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false} className="min-w-56">
- <SelectItem value={ALL_ENVIRONMENTS_VALUE}>
- <span className="flex items-center gap-2">
- <LayersIcon aria-hidden className="size-3.5" />
- All environments
- </span>
- </SelectItem>
- <SelectGroup>
- <SelectGroupLabel>Environments</SelectGroupLabel>
- {environments.map((environment) => (
- <SelectItem key={environment.environmentId} value={environment.environmentId}>
- <span className="flex w-full min-w-0 items-center gap-2">
- <EnvironmentMachineIcon
- aria-hidden
- kind={resolveEnvironmentMachineKind(environment.serverConfig)}
- className="size-3.5"
- />
- <span className="min-w-0 flex-1 truncate">
- {settingsScopeEnvironmentLabel(environment, environments)}
- </span>
- {environment.connection.phase === "connected" ? null : (
- <span className="text-xs text-muted-foreground">Offline</span>
- )}
- </span>
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectPopup>
- </Select>
-
- <Select
- value={projectValue}
- onValueChange={(next) => {
- if (typeof next === "string") onChange(selectProjectAxis(value, next));
- }}
- >
- <SelectTrigger size="compact" aria-label="Project scope" className={TRIGGER_CLASSNAME}>
- <SelectValue>
- <span className="flex min-w-0 items-center gap-1.5">
- {selectedGroup ? (
- <ProjectFavicon project={selectedGroup} className="size-3.5" />
- ) : null}
- <span className="truncate">
- {selectedGroup?.displayName ??
- (value.project ? "Unavailable project" : "All projects")}
- </span>
- </span>
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false} className="min-w-56">
- <SelectItem value={ALL_PROJECTS_VALUE}>All projects</SelectItem>
- {groups.map((group) => (
- <SelectItem key={group.projectKey} value={group.projectKey}>
- <span className="flex w-full min-w-0 items-center gap-2">
- <ProjectFavicon project={group} className="size-3.5" />
- <span className="min-w-0 flex-1 truncate">{group.displayName}</span>
- </span>
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- {resolved.kind === "unavailable" ? (
- <span className="truncate text-xs text-muted-foreground">{resolved.message}</span>
- ) : null}
- </div>
- );
-}
diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx
index 75624792c5d..1893a59acb4 100644
--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx
+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx
@@ -41,11 +41,13 @@ import { SidebarUtilityMenu } from "../sidebar/SidebarChrome";
import { scrollToSettingsTarget } from "./settingsLayout";
import {
searchSettings,
+ isSettingsOverviewVisible,
SETTINGS_SECTION_LABELS,
type SettingsPath,
type SettingsSearchItem,
} from "./settingsSearch";
import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems";
+import { validateSettingsScopeSearch } from "./settingsScope";
const SnapShotIcon = createLucideIcon("snap-shot", [
[
@@ -103,6 +105,11 @@ function SettingsSectionIcon({ to }: { to: SettingsPath }) {
export function SettingsSidebarNav({ pathname }: { pathname: string }) {
const navigate = useNavigate();
const currentHash = useLocation({ select: (location) => location.hash });
+ const currentSearch = useLocation({ select: (location) => location.search });
+ const scopeSearch = useMemo(() => validateSettingsScopeSearch(currentSearch), [currentSearch]);
+ const navItems = SETTINGS_NAV_ITEMS.filter(
+ (item) => item.to !== "/settings/projects" || isSettingsOverviewVisible(scopeSearch),
+ );
const { isMobile, setOpenMobile, open, setOpen } = useSidebar();
const searchInputRef = useRef<HTMLInputElement>(null);
const [query, setQuery] = useState("");
@@ -181,18 +188,12 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
setOpenMobile(false);
}
const targetId = item.targetId ?? item.id;
- if (
- item.to !== "/settings/projects" &&
- pathname === item.to &&
- currentHash.replace(/^#/, "") === targetId
- ) {
+ if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
scrollToSettingsTarget(targetId);
return;
}
void navigate({
to: item.to,
- search: (previous) =>
- item.to === "/settings/projects" ? { ...previous, project: undefined } : previous,
hash: targetId,
replace: true,
hashScrollIntoView: false,
@@ -319,7 +320,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
</SidebarMenu>
) : (
<SidebarMenu className="ps-px">
- {SETTINGS_NAV_ITEMS.map((item) => {
+ {navItems.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.to || pathname.startsWith(`${item.to}/`);
return (
diff --git a/apps/web/src/components/settings/SharedSettingsMismatchAlert.tsx b/apps/web/src/components/settings/SharedSettingsMismatchAlert.tsx
deleted file mode 100644
index 2a804cf9aeb..00000000000
--- a/apps/web/src/components/settings/SharedSettingsMismatchAlert.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { TriangleAlertIcon } from "lucide-react";
-
-import { useSharedSettingsSync } from "../../hooks/useSettings";
-import { Alert, AlertAction, AlertDescription } from "../ui/alert";
-import { Button } from "../ui/button";
-
-/**
- * Warns when a connected environment holds different shared settings than
- * the primary one, and offers to write the primary's values everywhere.
- * Renders nothing when every connected environment agrees.
- */
-export function SharedSettingsMismatchAlert() {
- const { mismatches, applyToAll } = useSharedSettingsSync();
- if (mismatches.length === 0) {
- return null;
- }
- const labels = mismatches.map((mismatch) => mismatch.label).join(", ");
- return (
- <Alert variant="warning" className="mx-3 sm:mx-4">
- <TriangleAlertIcon />
- <AlertDescription>
- Settings differ on {labels}. Thread and source control preferences are meant to match on
- every environment.
- </AlertDescription>
- <AlertAction>
- <Button variant="outline" size="xs" onClick={applyToAll}>
- Apply to all
- </Button>
- </AlertAction>
- </Alert>
- );
-}
diff --git a/apps/web/src/components/settings/SnapShotSettings.test.tsx b/apps/web/src/components/settings/SnapShotSettings.test.tsx
index 8d34af17a05..584c224493d 100644
--- a/apps/web/src/components/settings/SnapShotSettings.test.tsx
+++ b/apps/web/src/components/settings/SnapShotSettings.test.tsx
@@ -26,6 +26,7 @@ vi.mock("react/compiler-runtime", async () => {
});
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));
vi.mock("../../state/server", () => ({ primaryServerKeybindingsAtom: {} }));
+vi.mock("./SettingsScopeContext", () => ({ useOptionalSettingsScope: () => null }));
const bridge = vi.hoisted(() => ({
getSnapShotState: vi.fn<() => Promise<DesktopSnapShotState>>(),
setSnapShotShortcutSuppressed: vi.fn(),
diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsx
index 6d9d2010522..2a4858ded4a 100644
--- a/apps/web/src/components/settings/SourceControlSettings.tsx
+++ b/apps/web/src/components/settings/SourceControlSettings.tsx
@@ -18,10 +18,10 @@ import {
resolveServerBackgroundActivitySettings,
} from "@t3tools/shared/backgroundActivitySettings";
-import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
-import { SharedSettingsMismatchAlert } from "./SharedSettingsMismatchAlert";
+import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
+import { useSettingsScope } from "./SettingsScopeContext";
+import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
import { cn } from "../../lib/utils";
-import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
import { useEnvironmentQuery } from "../../state/query";
import { sourceControlEnvironment } from "../../state/sourceControl";
import { Badge } from "../ui/badge";
@@ -343,8 +343,8 @@ function DiscoveryItemRow({
}
function GitFetchIntervalSettings() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
const automaticGitFetchIntervalSeconds = durationToSeconds(
resolvedBackgroundActivity.automaticGitFetchInterval,
@@ -498,15 +498,14 @@ function EmptySourceControlDiscovery({
}
export function SourceControlSettingsPanel() {
- const { environments } = useEnvironments();
- const primaryEnvironment = usePrimaryEnvironment();
- const fallbackEnvironment =
- environments.find((environment) => environment.connection.phase === "connected") ??
- environments[0] ??
- null;
+ const { scope, environment, connectedEnvironments } = useSettingsScope();
+ // Discovery scans one machine's tools, so it shows the representative
+ // environment (named in the section title when several are selected);
+ // the settings rows above it fan out like everywhere else.
const environmentId =
- primaryEnvironment?.environmentId ?? fallbackEnvironment?.environmentId ?? null;
- const isPrimaryEnvironment = environmentId === primaryEnvironment?.environmentId;
+ environment?.connection.phase === "connected" ? environment.environmentId : null;
+ const aggregate = scope.environmentIds.length !== 1 && connectedEnvironments.length > 1;
+ const environmentSuffix = aggregate && environment ? ` · ${environment.label}` : "";
const discovery = useEnvironmentQuery(
environmentId === null
? null
@@ -543,10 +542,19 @@ export function SourceControlSettingsPanel() {
return (
<SettingsPageContainer>
- <SharedSettingsMismatchAlert />
- {isInitialScanPending ? (
+ <ProjectDefaultsSettings category="source-control" />
+ {environmentId === null ? (
+ <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
+ <p className="px-4 py-3 text-sm text-muted-foreground">
+ Connect an environment to inspect its version control tools and hosting integrations.
+ </p>
+ </SettingsSection>
+ ) : isInitialScanPending ? (
<>
- <SourceControlSectionSkeleton title="Version Control" headerAction={scanButton} />
+ <SourceControlSectionSkeleton
+ title={`Version Control${environmentSuffix}`}
+ headerAction={scanButton}
+ />
<SourceControlSectionSkeleton title="Source Control Providers" />
</>
) : hasDiscoveryItems ? (
@@ -554,14 +562,12 @@ export function SourceControlSettingsPanel() {
{hasVersionControlSystems ? (
<SettingsSection
id={searchableSetting("source-control").id}
- title="Version Control"
+ title={`Version Control${environmentSuffix}`}
headerAction={scanButton}
>
{result.versionControlSystems.map((item) => (
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
- {item.kind === "git" && isPrimaryEnvironment ? (
- <GitFetchIntervalSettings />
- ) : undefined}
+ {item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
</DiscoveryItemRow>
))}
</SettingsSection>
@@ -570,7 +576,11 @@ export function SourceControlSettingsPanel() {
{result.sourceControlProviders.length > 0 ? (
<SettingsSection
id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
- title="Source Control Providers"
+ title={
+ hasVersionControlSystems
+ ? "Source Control Providers"
+ : `Source Control Providers${environmentSuffix}`
+ }
headerAction={hasVersionControlSystems ? null : scanButton}
>
{result.sourceControlProviders.map((item) => (
@@ -587,8 +597,6 @@ export function SourceControlSettingsPanel() {
/>
)}
- {/* Its rows are serverScoped: without a primary they render inert with
- an explanation, which beats disappearing. */}
<SourceControlWritingSettingsSection />
</SettingsPageContainer>
);
diff --git a/apps/web/src/components/settings/SourceControlWritingSettings.test.tsx b/apps/web/src/components/settings/SourceControlWritingSettings.test.tsx
new file mode 100644
index 00000000000..bfc75e083cf
--- /dev/null
+++ b/apps/web/src/components/settings/SourceControlWritingSettings.test.tsx
@@ -0,0 +1,221 @@
+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
+import { act, StrictMode, type ReactNode } from "react";
+import { create, type ReactTestRenderer } from "react-test-renderer";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import type { ScopedSettingsPatch } from "./scopedSettings";
+
+type WritingStyle = typeof DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
+const state = vi.hoisted(() => ({
+ styles: [] as WritingStyle[],
+ updateSettings: vi.fn<(patch: ScopedSettingsPatch) => void>(),
+}));
+
+vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));
+vi.mock("./useScopedSettings", () => ({
+ useScopedSettings: () => ({
+ ...DEFAULT_UNIFIED_SETTINGS,
+ sourceControlWritingStyle: state.styles[0],
+ }),
+ useScopedSettingsMixed: () => JSON.stringify(state.styles[0]) !== JSON.stringify(state.styles[1]),
+ useUpdateScopedSettings: () => state.updateSettings,
+}));
+vi.mock("./SettingsScopeContext", () => ({
+ useSettingsScope: () => ({
+ scope: { kind: "all", environmentIds: [] },
+ environment: null,
+ connectedEnvironments: [],
+ targets: state.styles.map((style) => ({
+ settings: { ...DEFAULT_UNIFIED_SETTINGS, sourceControlWritingStyle: style },
+ })),
+ }),
+}));
+vi.mock("./useScopedModelAvailability", () => ({
+ useScopedModelDisabledReason: () => () => null,
+}));
+vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
+vi.mock("../../state/server", () => ({ EMPTY_SERVER_PROVIDERS: [] }));
+vi.mock("../chat/ProviderModelPicker", () => ({ ProviderModelPicker: () => null }));
+vi.mock("./settingsSearch", () => ({ searchableSetting: (id: string) => ({ id, title: id }) }));
+vi.mock("./settingsLayout", () => ({
+ SETTINGS_PICKER_TRIGGER_CLASSNAME: "",
+ SettingResetButton: ({ label, onClick }: { label: string; onClick: () => void }) => (
+ <button onClick={onClick}>{`Reset ${label}`}</button>
+ ),
+ SettingsSection: ({ children }: { children: ReactNode }) => children,
+ SettingsRow: ({
+ children,
+ control,
+ resetAction,
+ }: {
+ children: ReactNode;
+ control: ReactNode;
+ resetAction: ReactNode;
+ }) => (
+ <div>
+ {control}
+ {resetAction}
+ {children}
+ </div>
+ ),
+}));
+vi.mock("../ui/select", () => ({
+ Select: ({ children }: { children: ReactNode }) => children,
+ SelectItem: "span",
+ SelectPopup: "div",
+ SelectTrigger: "div",
+ SelectValue: "span",
+}));
+vi.mock("../ui/switch", () => ({ Switch: "input" }));
+vi.mock("../ui/textarea", () => ({ Textarea: "textarea" }));
+vi.mock("../ui/button", () => ({ Button: "button" }));
+
+import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
+
+let renderer: ReactTestRenderer | null;
+
+function button(label: string) {
+ return renderer!.root.findAllByType("button").find((item) => item.children.includes(label))!;
+}
+
+function openEditor() {
+ act(() => button("Write custom instructions for all").props.onClick());
+}
+
+function editInstructions(value: string) {
+ act(() => renderer!.root.findByType("textarea").props.onChange({ target: { value } }));
+}
+
+function applyInstructions() {
+ act(() => button("Apply instructions to all").props.onClick());
+}
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ state.styles = [
+ {
+ ...DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle,
+ mode: "custom",
+ customInstructions: "First environment instructions",
+ followChangeRequestTemplates: true,
+ },
+ {
+ ...DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle,
+ mode: "custom",
+ customInstructions: "Second environment instructions",
+ followChangeRequestTemplates: false,
+ },
+ ];
+ state.updateSettings.mockReset().mockImplementation((patch) => {
+ state.styles = state.styles.map((style) => ({ ...style, ...patch.sourceControlWritingStyle }));
+ });
+ act(() => {
+ renderer = create(
+ <StrictMode>
+ <SourceControlWritingSettingsSection />
+ </StrictMode>,
+ );
+ });
+});
+
+afterEach(async () => {
+ await act(async () => renderer?.unmount());
+ renderer = null;
+ vi.unstubAllGlobals();
+});
+
+describe("mixed source control instructions", () => {
+ it("resets mixed template preferences without replacing each environment's instructions", () => {
+ const initialInstructions = state.styles.map(({ mode, customInstructions }) => ({
+ mode,
+ customInstructions,
+ }));
+
+ act(() => button("Reset change request templates").props.onClick());
+
+ expect(state.updateSettings).toHaveBeenCalledTimes(1);
+ expect(state.styles.map((style) => style.followChangeRequestTemplates)).toEqual([
+ DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle.followChangeRequestTemplates,
+ DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle.followChangeRequestTemplates,
+ ]);
+ expect(
+ state.styles.map(({ mode, customInstructions }) => ({ mode, customInstructions })),
+ ).toEqual(initialInstructions);
+ });
+
+ it("resets every environment even when the representative already has default instructions", () => {
+ state.styles[0] = { ...DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle };
+ act(() => {
+ renderer!.update(
+ <StrictMode>
+ <SourceControlWritingSettingsSection />
+ </StrictMode>,
+ );
+ });
+
+ act(() => button("Reset source control writing style").props.onClick());
+
+ expect(state.updateSettings).toHaveBeenCalledTimes(1);
+ expect(
+ state.styles.map(({ mode, customInstructions }) => ({ mode, customInstructions })),
+ ).toEqual(
+ [0, 1].map(() => ({
+ mode: DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle.mode,
+ customInstructions: DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle.customInstructions,
+ })),
+ );
+ expect(state.styles[1]!.followChangeRequestTemplates).toBe(false);
+ });
+
+ it("does not write an untouched bulk draft", () => {
+ const initialStyles = state.styles;
+ openEditor();
+ expect(renderer!.root.findByType("textarea").props.value).toBe("");
+ expect(button("Apply instructions to all").props.disabled).toBe(true);
+
+ applyInstructions();
+ expect(state.updateSettings).not.toHaveBeenCalled();
+ expect(state.styles).toEqual(initialStyles);
+ });
+
+ it("applies edited instructions to every selected environment", () => {
+ openEditor();
+ editInstructions(" Keep titles concise. ");
+ expect(button("Apply instructions to all").props.disabled).toBe(false);
+ applyInstructions();
+
+ expect(state.updateSettings).toHaveBeenCalledTimes(1);
+ expect(state.styles.map((style) => style.customInstructions)).toEqual([
+ "Keep titles concise.",
+ "Keep titles concise.",
+ ]);
+ expect(state.styles.map((style) => style.followChangeRequestTemplates)).toEqual([true, false]);
+ });
+
+ it("allows an intentional clear after editing", () => {
+ openEditor();
+ editInstructions("Temporary instructions");
+ editInstructions("");
+ expect(button("Apply instructions to all").props.disabled).toBe(false);
+ applyInstructions();
+
+ expect(state.updateSettings).toHaveBeenCalledTimes(1);
+ expect(state.styles.map((style) => style.customInstructions)).toEqual(["", ""]);
+ });
+
+ it("shows the plain editor once instructions agree, even while templates differ", () => {
+ openEditor();
+ editInstructions("Shared instructions");
+ applyInstructions();
+
+ expect(state.updateSettings).toHaveBeenCalledTimes(1);
+ expect(state.styles.map((style) => style.customInstructions)).toEqual([
+ "Shared instructions",
+ "Shared instructions",
+ ]);
+ // Template preferences still differ, but that is the templates row's
+ // concern: the instructions editor is no longer a bulk draft.
+ expect(button("Write custom instructions for all")).toBeUndefined();
+ expect(renderer!.root.findByType("textarea").props.defaultValue).toBe("Shared instructions");
+ });
+});
diff --git a/apps/web/src/components/settings/SourceControlWritingSettings.tsx b/apps/web/src/components/settings/SourceControlWritingSettings.tsx
index 448c6c623ea..a4d4e1f950c 100644
--- a/apps/web/src/components/settings/SourceControlWritingSettings.tsx
+++ b/apps/web/src/components/settings/SourceControlWritingSettings.tsx
@@ -1,12 +1,21 @@
-import { useAtomValue } from "@effect/atom-react";
import { useNavigate } from "@tanstack/react-router";
-import { useRef } from "react";
-import type { ProviderInstanceId, SourceControlWritingStyleMode } from "@t3tools/contracts";
+import { useRef, useState } from "react";
+import type {
+ ProviderInstanceId,
+ ServerSettings,
+ SourceControlWritingStyleMode,
+} from "@t3tools/contracts";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { createModelSelection } from "@t3tools/shared/model";
import { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
-import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
+import {
+ useScopedSettings,
+ useScopedSettingsMixed,
+ useUpdateScopedSettings,
+} from "./useScopedSettings";
+import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
+import { useSettingsScope } from "./SettingsScopeContext";
import {
applyProviderInstanceSettings,
deriveProviderInstanceEntries,
@@ -16,12 +25,13 @@ import {
getCustomModelOptionsByInstance,
resolveAppModelSelectionState,
} from "../../modelSelection";
-import { primaryServerProvidersAtom } from "../../state/server";
-import { usePrimaryEnvironmentId } from "../../state/environments";
+import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import { Textarea } from "../ui/textarea";
+import { toastManager } from "../ui/toast";
+import { Button } from "../ui/button";
import {
SETTINGS_PICKER_TRIGGER_CLASSNAME,
SettingResetButton,
@@ -48,16 +58,41 @@ const MODE_OPTIONS: Record<SourceControlWritingStyleMode, { label: string; descr
};
export function SourceControlWritingSettingsSection() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
const navigate = useNavigate();
- const environmentId = usePrimaryEnvironmentId();
- const serverProviders = useAtomValue(primaryServerProvidersAtom);
+ const { environment, connectedEnvironments, targets } = useSettingsScope();
+ // The representative supplies the provider list; a model choice is checked
+ // against every target before it fans out.
+ const environmentId = environment?.environmentId ?? null;
+ const hasServerTargets = connectedEnvironments.length > 0;
+ const serverProviders = environment?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
+ // The writing style is one object; each control only cares about its own field.
+ const styleFieldMixed = (field: keyof ServerSettings["sourceControlWritingStyle"]) => {
+ const first = targets[0];
+ return (
+ first !== undefined &&
+ targets.some(
+ (candidate) =>
+ candidate.settings.sourceControlWritingStyle[field] !==
+ first.settings.sourceControlWritingStyle[field],
+ )
+ );
+ };
+ const modeMixed = styleFieldMixed("mode");
+ const instructionsMixed = styleFieldMixed("customInstructions");
+ const templatesMixed = styleFieldMixed("followChangeRequestTemplates");
+ const writingStyleMixed = modeMixed || instructionsMixed;
+ const mixedWriterModel = useScopedSettingsMixed(["sourceControlWriterModelSelection"]);
const customInstructionsRef = useRef<HTMLTextAreaElement>(null);
+ const [editingAllInstructions, setEditingAllInstructions] = useState(false);
+ const [allInstructions, setAllInstructions] = useState<string | null>(null);
const style = settings.sourceControlWritingStyle;
const defaults = DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
const isSourceControlWritingStyleDirty =
- style.mode !== defaults.mode || style.customInstructions !== defaults.customInstructions;
+ writingStyleMixed ||
+ style.mode !== defaults.mode ||
+ style.customInstructions !== defaults.customInstructions;
const textGenerationProviders = serverProviders.filter(
(provider) => provider.supportsTextGeneration !== false,
@@ -87,11 +122,14 @@ export function SourceControlWritingSettingsSection() {
activeSelection.instanceId,
activeSelection.model,
);
+ const writerModelDisabledReason = useScopedModelDisabledReason(settings, instanceEntries);
return (
<SettingsSection id="source-control-text-generation" title="Text generation">
<SettingsRow
serverScoped
+ settingKeys={["sourceControlWritingStyle"]}
+ mixed={writingStyleMixed}
{...searchableSetting("source-control-writing-style")}
description={MODE_OPTIONS[style.mode].description}
resetAction={
@@ -111,7 +149,7 @@ export function SourceControlWritingSettingsSection() {
}
control={
<Select
- value={style.mode}
+ value={modeMixed ? null : style.mode}
onValueChange={(value) => {
const customInstructions = customInstructionsRef.current?.value.trim();
updateSettings({
@@ -127,7 +165,11 @@ export function SourceControlWritingSettingsSection() {
className="w-full sm:w-56"
aria-label="Source control writing style"
>
- <SelectValue>{MODE_OPTIONS[style.mode].label}</SelectValue>
+ <SelectValue>
+ {(value: SourceControlWritingStyleMode | null) =>
+ value === null ? "Mixed" : MODE_OPTIONS[value].label
+ }
+ </SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{(Object.keys(MODE_OPTIONS) as SourceControlWritingStyleMode[]).map((mode) => (
@@ -139,7 +181,49 @@ export function SourceControlWritingSettingsSection() {
</Select>
}
>
- {style.mode === "custom" ? (
+ {writingStyleMixed ? (
+ <div className="mt-3 max-w-2xl space-y-2 pb-3.5">
+ {editingAllInstructions ? (
+ <>
+ <Textarea
+ value={allInstructions ?? ""}
+ onChange={(event) => setAllInstructions(event.target.value)}
+ rows={4}
+ aria-label="Custom source control instructions for all selected environments"
+ placeholder="Write the instructions each selected environment should use."
+ />
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={allInstructions === null}
+ onClick={() => {
+ if (allInstructions === null) return;
+ updateSettings({
+ sourceControlWritingStyle: {
+ mode: "custom",
+ customInstructions: allInstructions.trim(),
+ },
+ });
+ setEditingAllInstructions(false);
+ }}
+ >
+ Apply instructions to all
+ </Button>
+ </>
+ ) : (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ setAllInstructions(null);
+ setEditingAllInstructions(true);
+ }}
+ >
+ Write custom instructions for all
+ </Button>
+ )}
+ </div>
+ ) : style.mode === "custom" ? (
<div className="mt-3 max-w-2xl pb-3.5">
<Textarea
key={style.customInstructions}
@@ -161,9 +245,12 @@ export function SourceControlWritingSettingsSection() {
<SettingsRow
serverScoped
+ settingKeys={["sourceControlWritingStyle"]}
+ mixed={templatesMixed}
{...searchableSetting("follow-change-request-templates")}
description="Use the repository's template for change request descriptions when available."
resetAction={
+ templatesMixed ||
style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
<SettingResetButton
label="change request templates"
@@ -179,7 +266,8 @@ export function SourceControlWritingSettingsSection() {
}
control={
<Switch
- checked={style.followChangeRequestTemplates}
+ mixed={templatesMixed}
+ checked={templatesMixed ? false : style.followChangeRequestTemplates}
onCheckedChange={(checked) =>
updateSettings({
sourceControlWritingStyle: {
@@ -194,59 +282,77 @@ export function SourceControlWritingSettingsSection() {
<SettingsRow
serverScoped
+ settingKeys={["sourceControlWriterModelSelection"]}
{...searchableSetting("source-control-writer-model")}
- description="Model for source control text and branch or bookmark names. Off uses the global default."
+ description="Model for source control text and branch or bookmark names. Off uses the environment's text generation model."
control={
- <div className="flex flex-wrap items-center justify-end gap-2">
- {usesDedicatedModel && !canEnableDedicatedModel ? (
- <span className="text-sm text-muted-foreground">
- No text generation providers available.
- </span>
- ) : null}
- {usesDedicatedModel && canEnableDedicatedModel ? (
- <ProviderModelPicker
- activeInstanceId={activeSelection.instanceId}
- model={activeSelection.model}
- lockedProvider={null}
- instanceEntries={instanceEntries}
- modelOptionsByInstance={modelOptionsByInstance}
- triggerVariant="outline"
- triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
- triggerAriaLabel="Source control writer model"
- {...(environmentId
- ? {
- onOpenProviderSetup: (instanceId: ProviderInstanceId) => {
- void navigate({
- to: "/settings/providers",
- search: { environmentId, instanceId },
- });
- },
+ !hasServerTargets ? (
+ <span className="text-sm text-muted-foreground">
+ Connect an environment to choose its source control writer model.
+ </span>
+ ) : (
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ {usesDedicatedModel && !canEnableDedicatedModel ? (
+ <span className="text-sm text-muted-foreground">
+ No text generation providers available.
+ </span>
+ ) : null}
+ {usesDedicatedModel && canEnableDedicatedModel ? (
+ <ProviderModelPicker
+ activeInstanceId={activeSelection.instanceId}
+ model={activeSelection.model}
+ lockedProvider={null}
+ instanceEntries={instanceEntries}
+ modelOptionsByInstance={modelOptionsByInstance}
+ triggerVariant="outline"
+ triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
+ triggerAriaLabel="Source control writer model"
+ {...(mixedWriterModel ? { triggerLabel: "Mixed" } : {})}
+ {...(environmentId
+ ? {
+ onOpenProviderSetup: (instanceId: ProviderInstanceId) => {
+ void navigate({
+ to: "/settings/providers",
+ search: { environmentId, instanceId },
+ });
+ },
+ }
+ : {})}
+ getModelDisabledReason={writerModelDisabledReason}
+ onInstanceModelChange={(instanceId, model) => {
+ const reason = writerModelDisabledReason(instanceId, model);
+ if (reason) {
+ toastManager.add({
+ type: "error",
+ title: "Source control writer model not saved",
+ description: reason,
+ });
+ return;
}
- : {})}
- onInstanceModelChange={(instanceId, model) => {
+ updateSettings({
+ sourceControlWriterModelSelection: createModelSelection(instanceId, model),
+ });
+ }}
+ />
+ ) : null}
+ <Switch
+ checked={usesDedicatedModel}
+ disabled={!usesDedicatedModel && !canEnableDedicatedModel}
+ onCheckedChange={(checked) =>
updateSettings({
- sourceControlWriterModelSelection: createModelSelection(instanceId, model),
- });
- }}
+ sourceControlWriterModelSelection: checked
+ ? createModelSelection(
+ defaultModelSelection.instanceId,
+ defaultModelSelection.model,
+ defaultModelSelection.options,
+ )
+ : null,
+ })
+ }
+ aria-label="Use a separate source control writer model"
/>
- ) : null}
- <Switch
- checked={usesDedicatedModel}
- disabled={!usesDedicatedModel && !canEnableDedicatedModel}
- onCheckedChange={(checked) =>
- updateSettings({
- sourceControlWriterModelSelection: checked
- ? createModelSelection(
- defaultModelSelection.instanceId,
- defaultModelSelection.model,
- defaultModelSelection.options,
- )
- : null,
- })
- }
- aria-label="Use a separate source control writer model"
- />
- </div>
+ </div>
+ )
}
/>
</SettingsSection>
diff --git a/apps/web/src/components/settings/scopedSettings.test.ts b/apps/web/src/components/settings/scopedSettings.test.ts
new file mode 100644
index 00000000000..707c82c81ec
--- /dev/null
+++ b/apps/web/src/components/settings/scopedSettings.test.ts
@@ -0,0 +1,450 @@
+import {
+ DEFAULT_SERVER_SETTINGS,
+ EnvironmentId,
+ ProjectId,
+ type ServerSettings,
+} from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
+import {
+ listProjectOverrides,
+ persistScopedSettingsPatch,
+ planProjectOverridesClear,
+ planScopedSettingsClear,
+ planScopedSettingsPatch,
+ resolveScopedSettingsTargets,
+ scopedSettingsAreMixed,
+ scopedSettingsSource,
+ selectScopedSettingsEnvironments,
+} from "./scopedSettings";
+import { resolveSettingsScope } from "./settingsScope";
+
+function environment(
+ id: string,
+ options: {
+ connected?: boolean;
+ loaded?: boolean;
+ settings?: Partial<ServerSettings>;
+ projectOverrides?: boolean;
+ } = {},
+) {
+ return {
+ environmentId: EnvironmentId.make(id),
+ label: id,
+ connection: {
+ phase: options.connected === false ? ("offline" as const) : ("connected" as const),
+ },
+ serverConfig:
+ options.loaded === false
+ ? null
+ : {
+ settings: { ...DEFAULT_SERVER_SETTINGS, ...options.settings },
+ environment: {
+ capabilities: { projectSettingsOverrides: options.projectOverrides !== false },
+ },
+ },
+ };
+}
+
+const laptop = environment("Laptop");
+const server = environment("Server");
+const offline = environment("Offline", { connected: false });
+const loading = environment("Loading", { loaded: false });
+const environments = [laptop, server, offline, loading];
+const all = resolveSettingsScope({}, [], environments);
+const named = resolveSettingsScope({ machine: server.environmentId }, [], environments);
+
+const projectId = ProjectId.make("project");
+const laptopProjectId = ProjectId.make("laptop-project");
+const member = {
+ id: projectId,
+ environmentId: server.environmentId,
+ title: "Project",
+ workspaceRoot: "/repo",
+ physicalProjectKey: `${server.environmentId}:/repo`,
+ environmentLabel: server.label,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-09-07T00:00:00.000Z",
+ updatedAt: "2026-09-07T00:00:00.000Z",
+};
+const laptopMember = {
+ ...member,
+ id: laptopProjectId,
+ environmentId: laptop.environmentId,
+ physicalProjectKey: `${laptop.environmentId}:/repo`,
+ environmentLabel: laptop.label,
+};
+const group: SidebarProjectSnapshot = {
+ ...member,
+ projectKey: "project-group",
+ displayName: "Project",
+ memberProjects: [member, laptopMember],
+ memberProjectRefs: [
+ { environmentId: server.environmentId, projectId },
+ { environmentId: laptop.environmentId, projectId: laptopProjectId },
+ ],
+ groupedProjectCount: 2,
+ environmentPresence: "remote-only",
+ allRemoteMembersAreDesktopLocal: false,
+ allRemoteMembersAreWsl: false,
+ remoteEnvironmentLabels: [server.label, laptop.label],
+};
+const project = resolveSettingsScope({ project: group.projectKey }, [group], environments);
+const checkout = resolveSettingsScope(
+ { project: group.projectKey, machine: server.environmentId, checkout: member.physicalProjectKey },
+ [group],
+ environments,
+);
+
+describe("scoped settings targets", () => {
+ it("uses the named environment even when a different primary is available", () => {
+ const selected = selectScopedSettingsEnvironments(named, environments, laptop.environmentId);
+ expect(selected.environments).toEqual([server]);
+ expect(selected.environment).toBe(server);
+ });
+
+ it("keeps an offline named environment selected without falling back to primary", () => {
+ const scope = resolveSettingsScope({ machine: offline.environmentId }, [], environments);
+ const selected = selectScopedSettingsEnvironments(scope, environments, laptop.environmentId);
+ expect(selected.environments).toEqual([offline]);
+ expect(selected.connectedEnvironments).toEqual([]);
+ expect(selected.environment).toBeNull();
+ expect(
+ planScopedSettingsPatch(scope, environments, { enableProviderUpdateChecks: false }),
+ ).toMatchObject({
+ serverWrites: [],
+ unavailableReason: "Connect Offline to save this setting.",
+ });
+ });
+
+ it("prefers the selected primary as the aggregate representative without including disconnected targets", () => {
+ const selected = selectScopedSettingsEnvironments(all, environments, server.environmentId);
+ expect(selected.environment).toBe(server);
+ expect(selected.environments).toEqual(environments);
+ expect(selected.connectedEnvironments).toEqual([laptop, server]);
+ });
+
+ it("resolves each member's effective settings and source at project scope", () => {
+ const overridden = environment("Server", {
+ settings: {
+ defaultAutoPull: false,
+ projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
+ },
+ });
+ const targets = resolveScopedSettingsTargets(project, [laptop, overridden]);
+ expect(targets.map((target) => [target.projectId, target.settings.defaultAutoPull])).toEqual([
+ [projectId, true],
+ [laptopProjectId, false],
+ ]);
+ expect(scopedSettingsSource(targets, ["defaultAutoPull"])).toBe("mixed");
+ expect(scopedSettingsSource([targets[0]!], ["defaultAutoPull"])).toBe("project");
+ expect(scopedSettingsSource(targets, ["enableProviderUpdateChecks"])).toBe("environment");
+ expect(scopedSettingsAreMixed(targets, ["defaultAutoPull"])).toBe(true);
+ });
+});
+
+describe("scoped settings writes", () => {
+ it("isolates a formerly shared server preference to the named environment", async () => {
+ const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
+ const persistClient = vi.fn();
+ await persistScopedSettingsPatch(
+ planScopedSettingsPatch(named, environments, { sidebarAutoSettleOnMerge: false }),
+ persistServer,
+ persistClient,
+ );
+ expect(persistServer.mock.calls).toEqual([
+ [
+ {
+ environmentId: server.environmentId,
+ input: { patch: { sidebarAutoSettleOnMerge: false } },
+ },
+ ],
+ ]);
+ expect(persistClient).not.toHaveBeenCalled();
+ });
+
+ it("writes an aggregate preference only to connected environments with loaded configuration", async () => {
+ const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
+ const persistClient = vi.fn();
+ await persistScopedSettingsPatch(
+ planScopedSettingsPatch(all, environments, { enableProviderUpdateChecks: false }),
+ persistServer,
+ persistClient,
+ );
+ expect(persistServer.mock.calls.map(([input]) => input.environmentId)).toEqual([
+ laptop.environmentId,
+ server.environmentId,
+ ]);
+ expect(persistClient).not.toHaveBeenCalled();
+ });
+
+ it("persists client keys locally at any scope alongside server keys", async () => {
+ const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
+ const persistClient = vi.fn();
+ await persistScopedSettingsPatch(
+ planScopedSettingsPatch(named, environments, {
+ diffIgnoreWhitespace: false,
+ enableProviderUpdateChecks: false,
+ }),
+ persistServer,
+ persistClient,
+ );
+ expect(persistClient).toHaveBeenCalledExactlyOnceWith({ diffIgnoreWhitespace: false });
+ expect(persistServer).toHaveBeenCalledExactlyOnceWith({
+ environmentId: server.environmentId,
+ input: { patch: { enableProviderUpdateChecks: false } },
+ });
+ });
+
+ it("writes project overrides into each member's entry on its environment", () => {
+ const withExisting = environment("Server", {
+ settings: {
+ projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } },
+ },
+ });
+ const plan = planScopedSettingsPatch(project, [laptop, withExisting], {
+ defaultAutoPull: true,
+ });
+ expect(plan.unavailableReason).toBeNull();
+ expect(plan.serverWrites).toEqual([
+ {
+ environmentId: server.environmentId,
+ label: server.label,
+ patch: {
+ projectSettingsOverrides: {
+ [projectId]: { enableAgentBrowserAccess: false, defaultAutoPull: true },
+ },
+ },
+ },
+ {
+ environmentId: laptop.environmentId,
+ label: laptop.label,
+ patch: { projectSettingsOverrides: { [laptopProjectId]: { defaultAutoPull: true } } },
+ },
+ ]);
+ expect(
+ planScopedSettingsPatch(checkout, [laptop, server], { defaultAutoPull: true }),
+ ).toMatchObject({
+ serverWrites: [{ environmentId: server.environmentId }],
+ });
+ });
+
+ it("refuses environment-wide keys and older servers at project scope", () => {
+ expect(
+ planScopedSettingsPatch(project, environments, { enableProviderUpdateChecks: false }),
+ ).toMatchObject({
+ serverWrites: [],
+ unavailableReason: "This setting is environment-wide and cannot be overridden by a project.",
+ });
+ const legacy = environment("Server", { projectOverrides: false });
+ expect(
+ planScopedSettingsPatch(checkout, [laptop, legacy], { defaultAutoPull: true }),
+ ).toMatchObject({ serverWrites: [], unavailableReason: expect.stringContaining("update") });
+ });
+
+ it("clears overrides per member and removes an emptied entry", () => {
+ const withOverrides = environment("Server", {
+ settings: {
+ projectSettingsOverrides: {
+ [projectId]: { defaultAutoPull: true, enableAgentBrowserAccess: false },
+ },
+ },
+ });
+ const plan = planScopedSettingsClear(checkout, [laptop, withOverrides], ["defaultAutoPull"]);
+ expect(plan.serverWrites).toEqual([
+ {
+ environmentId: server.environmentId,
+ label: server.label,
+ patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } },
+ },
+ ]);
+ expect(
+ planScopedSettingsClear(
+ checkout,
+ [laptop, withOverrides],
+ ["defaultAutoPull", "enableAgentBrowserAccess"],
+ ).serverWrites[0]?.patch,
+ ).toEqual({ projectSettingsOverrides: { [projectId]: null } });
+ });
+
+ it("never substitutes an environment-default write for an invalid scope", () => {
+ const scope = resolveSettingsScope({ machine: "removed" }, [group], environments);
+ const plan = planScopedSettingsPatch(scope, environments, { enableAgentBrowserAccess: false });
+ expect(plan.serverWrites).toEqual([]);
+ expect(plan.hasClientWrite).toBe(false);
+ expect(plan.unavailableReason).not.toBeNull();
+ });
+
+ it("waits for every target and identifies both RPC failures and rejected writes", async () => {
+ const third = environment("Third");
+ const fourth = environment("Fourth");
+ const selected = [...environments, third, fourth];
+ const scope = resolveSettingsScope({}, [], selected);
+ const persistServer = vi
+ .fn()
+ .mockResolvedValueOnce({ _tag: "Success" })
+ .mockResolvedValueOnce({ _tag: "Failure" })
+ .mockRejectedValueOnce(new Error("Disconnected during save"))
+ .mockResolvedValueOnce({ _tag: "Success" });
+ const result = await persistScopedSettingsPatch(
+ planScopedSettingsPatch(scope, selected, { enableAgentBrowserAccess: false }),
+ persistServer,
+ vi.fn(),
+ );
+ expect(result.savedEnvironmentCount).toBe(2);
+ expect(result.failedEnvironments.map(({ label }) => label)).toEqual([
+ server.label,
+ third.label,
+ ]);
+ expect(persistServer).toHaveBeenCalledTimes(4);
+ });
+});
+
+describe("scoped settings mixed values", () => {
+ it("compares only requested settings across connected targets", () => {
+ const changed = environment("Changed", { settings: { enableAgentBrowserAccess: false } });
+ const targets = resolveScopedSettingsTargets(all, [laptop, changed]);
+ expect(scopedSettingsAreMixed(targets, ["enableAgentBrowserAccess"])).toBe(true);
+ expect(scopedSettingsAreMixed(targets, ["enableProviderUpdateChecks"])).toBe(false);
+ expect(scopedSettingsAreMixed([], ["enableAgentBrowserAccess"])).toBe(false);
+ });
+
+ it("treats independently decoded equal nested settings as the same value", () => {
+ const style = {
+ ...DEFAULT_SERVER_SETTINGS.sourceControlWritingStyle,
+ mode: "custom" as const,
+ customInstructions: "Use plain language",
+ };
+ const first = environment("First", { settings: { sourceControlWritingStyle: { ...style } } });
+ const second = environment("Second", { settings: { sourceControlWritingStyle: { ...style } } });
+ const targets = resolveScopedSettingsTargets(all, [first, second]);
+ expect(scopedSettingsAreMixed(targets, ["sourceControlWritingStyle"])).toBe(false);
+ });
+});
+
+describe("project overrides at environment scope", () => {
+ const laptop = EnvironmentId.make("laptop");
+ const desk = EnvironmentId.make("desk");
+ const fleet = ProjectId.make("fleet");
+ const t3 = ProjectId.make("t3");
+ const environment = (
+ environmentId: EnvironmentId,
+ overrides: ServerSettings["projectSettingsOverrides"],
+ ) => ({
+ environmentId,
+ label: environmentId,
+ connection: { phase: "connected" as const },
+ serverConfig: {
+ settings: { ...DEFAULT_SERVER_SETTINGS, projectSettingsOverrides: overrides },
+ environment: { capabilities: { projectSettingsOverrides: true } },
+ },
+ });
+
+ it("lists only the projects that override the keys", () => {
+ const entries = listProjectOverrides(
+ [
+ environment(laptop, {
+ [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
+ [t3]: { defaultThreadEnvMode: "local" },
+ }),
+ environment(desk, { [fleet]: { defaultAutoPull: false } }),
+ ],
+ ["defaultAutoPull"],
+ );
+ expect(entries).toEqual([
+ { environmentId: laptop, projectId: fleet },
+ { environmentId: desk, projectId: fleet },
+ ]);
+ });
+
+ it("clears only those keys and drops entries that become empty", () => {
+ const plan = planProjectOverridesClear(
+ [
+ environment(laptop, {
+ [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
+ [t3]: { defaultAutoPull: true },
+ }),
+ ],
+ [
+ { environmentId: laptop, projectId: fleet },
+ { environmentId: laptop, projectId: t3 },
+ ],
+ ["defaultAutoPull"],
+ );
+ expect(plan.serverWrites).toEqual([
+ {
+ environmentId: laptop,
+ label: laptop,
+ patch: {
+ projectSettingsOverrides: { [fleet]: { defaultThreadEnvMode: "local" }, [t3]: 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");
+ const projectId = ProjectId.make("fleet");
+ const member = {
+ id: projectId,
+ environmentId,
+ physicalProjectKey: "laptop:/repo",
+ environmentLabel: "Laptop",
+ title: "fleet",
+ workspaceRoot: "/repo",
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ };
+ const settings = {
+ ...DEFAULT_SERVER_SETTINGS,
+ projectSettingsOverrides: {
+ [projectId]: {
+ sourceControlWritingStyle: {
+ mode: "custom" as const,
+ customInstructions: "Keep it short.",
+ followChangeRequestTemplates: false,
+ },
+ },
+ },
+ };
+ const plan = planScopedSettingsPatch(
+ {
+ kind: "project",
+ group: {} as never,
+ environmentId: null,
+ label: "fleet",
+ members: [member as never],
+ environmentIds: [environmentId],
+ },
+ [
+ {
+ environmentId,
+ label: "Laptop",
+ connection: { phase: "connected" },
+ serverConfig: {
+ settings,
+ environment: { capabilities: { projectSettingsOverrides: true } },
+ },
+ },
+ ],
+ { sourceControlWritingStyle: { customInstructions: "Be terse." } },
+ );
+ expect(plan.serverWrites[0]?.patch).toEqual({
+ projectSettingsOverrides: {
+ [projectId]: {
+ sourceControlWritingStyle: {
+ mode: "custom",
+ customInstructions: "Be terse.",
+ followChangeRequestTemplates: false,
+ },
+ },
+ },
+ });
+ });
+});
diff --git a/apps/web/src/components/settings/scopedSettings.ts b/apps/web/src/components/settings/scopedSettings.ts
new file mode 100644
index 00000000000..1e2d41f473e
--- /dev/null
+++ b/apps/web/src/components/settings/scopedSettings.ts
@@ -0,0 +1,361 @@
+import {
+ ClientSettingsSchema,
+ type ClientSettingsPatch,
+ type EnvironmentId,
+ PROJECT_SCOPED_SERVER_SETTING_KEYS,
+ type ProjectId,
+ type ProjectScopedServerSettingKey,
+ type ProjectSettingsOverrides,
+ ServerSettings,
+ type ServerSettingsPatch,
+} from "@t3tools/contracts";
+import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
+import {
+ clearProjectSettingsOverrides,
+ resolveProjectSettings,
+ type ProjectSettingSource,
+} from "@t3tools/shared/projectSettings";
+import * as Equal from "effect/Equal";
+
+import type { ResolvedSettingsScope } from "./settingsScope";
+
+export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
+
+interface ScopedSettingsEnvironment {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly connection: { readonly phase: EnvironmentConnectionPhase };
+ readonly serverConfig: {
+ readonly settings: ServerSettings;
+ readonly environment?: {
+ readonly capabilities: { readonly projectSettingsOverrides?: boolean | undefined };
+ };
+ } | null;
+}
+
+const SERVER_KEYS = new Set<string>(Object.keys(ServerSettings.fields));
+const CLIENT_KEYS = new Set<string>(Object.keys(ClientSettingsSchema.fields));
+const PROJECT_SCOPED_KEYS = new Set<string>(PROJECT_SCOPED_SERVER_SETTING_KEYS);
+
+export function isProjectScopedSettingKey(key: string): key is ProjectScopedServerSettingKey {
+ return PROJECT_SCOPED_KEYS.has(key);
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/** The representative supplies display values, never the set of write targets. */
+export function selectScopedSettingsEnvironments<T extends ScopedSettingsEnvironment>(
+ scope: ResolvedSettingsScope,
+ available: readonly T[],
+ primaryEnvironmentId: EnvironmentId | null,
+) {
+ const selectedIds = new Set(scope.environmentIds);
+ const environments = available.filter((environment) =>
+ selectedIds.has(environment.environmentId),
+ );
+ const connectedEnvironments = environments.filter(
+ (environment) =>
+ environment.connection.phase === "connected" && environment.serverConfig !== null,
+ );
+ const environment =
+ connectedEnvironments.find((candidate) => candidate.environmentId === primaryEnvironmentId) ??
+ connectedEnvironments[0] ??
+ null;
+ return { environments, connectedEnvironments, environment };
+}
+
+/**
+ * One (environment, project) pair the scope writes to, with that project's
+ * effective settings. Environment scopes have no member and read the
+ * environment settings directly.
+ */
+export interface ScopedSettingsTarget {
+ readonly environmentId: EnvironmentId;
+ /** The environment's label; a project is the same project on every environment. */
+ readonly label: string;
+ readonly projectId: ProjectId | null;
+ readonly settings: ServerSettings;
+ readonly sources: Readonly<Record<ProjectScopedServerSettingKey, ProjectSettingSource>>;
+}
+
+/** Effective settings per connected target: members at project scope, environments otherwise. */
+export function resolveScopedSettingsTargets(
+ scope: ResolvedSettingsScope,
+ connectedEnvironments: readonly ScopedSettingsEnvironment[],
+): readonly ScopedSettingsTarget[] {
+ const byId = new Map(
+ connectedEnvironments.map((environment) => [environment.environmentId, environment]),
+ );
+ if (scope.kind === "project" || scope.kind === "checkout") {
+ return scope.members.flatMap((member) => {
+ const environment = byId.get(member.environmentId);
+ if (!environment?.serverConfig) return [];
+ const resolved = resolveProjectSettings(environment.serverConfig.settings, member.id);
+ return [
+ {
+ environmentId: member.environmentId,
+ label: environment.label,
+ projectId: member.id,
+ settings: resolved.settings,
+ sources: resolved.sources,
+ },
+ ];
+ });
+ }
+ return connectedEnvironments.flatMap((environment) =>
+ environment.serverConfig
+ ? [
+ {
+ environmentId: environment.environmentId,
+ label: environment.label,
+ projectId: null,
+ settings: environment.serverConfig.settings,
+ sources: resolveProjectSettings(environment.serverConfig.settings, null).sources,
+ },
+ ]
+ : [],
+ );
+}
+
+export function scopedSettingsAreMixed(
+ targets: readonly Pick<ScopedSettingsTarget, "settings">[],
+ keys: readonly (keyof ServerSettings)[],
+): boolean {
+ const first = targets[0];
+ return (
+ first !== undefined &&
+ targets.some((candidate) =>
+ keys.some((key) => !Equal.equals(first.settings[key], candidate.settings[key])),
+ )
+ );
+}
+
+export type ScopedSettingSource = ProjectSettingSource | "mixed";
+
+/** Whether the keys are overridden on every target, inherited on every target, or split. */
+export function scopedSettingsSource(
+ targets: readonly Pick<ScopedSettingsTarget, "sources">[],
+ keys: readonly (keyof ServerSettings)[],
+): ScopedSettingSource {
+ 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";
+}
+
+interface ScopedServerWrite {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly patch: ServerSettingsPatch;
+}
+
+function projectOverrideWrites(
+ scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
+ environments: readonly ScopedSettingsEnvironment[],
+ update: (
+ current: ProjectSettingsOverrides,
+ settings: ServerSettings,
+ projectId: ProjectId,
+ ) => ProjectSettingsOverrides | null,
+): ScopedServerWrite[] {
+ const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
+ const writes = new Map<EnvironmentId, ScopedServerWrite>();
+ for (const member of scope.members) {
+ const environment = byId.get(member.environmentId);
+ if (
+ !environment?.serverConfig ||
+ environment.connection.phase !== "connected" ||
+ environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
+ ) {
+ continue;
+ }
+ const settings = environment.serverConfig.settings;
+ const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
+ const existing = writes.get(member.environmentId);
+ writes.set(member.environmentId, {
+ environmentId: member.environmentId,
+ label: environment.label,
+ patch: {
+ projectSettingsOverrides: {
+ ...existing?.patch.projectSettingsOverrides,
+ [member.id]: entry,
+ },
+ },
+ });
+ }
+ return [...writes.values()];
+}
+
+/**
+ * Environment scopes write the patch to every connected environment; project
+ * and checkout scopes write the scopable keys into each member's override
+ * entry on its environment. Client keys always persist locally.
+ */
+export function planScopedSettingsPatch(
+ scope: ResolvedSettingsScope,
+ environments: readonly ScopedSettingsEnvironment[],
+ patch: ScopedSettingsPatch,
+) {
+ const clientPatch = Object.fromEntries(
+ Object.entries(patch).filter(([key]) => CLIENT_KEYS.has(key)),
+ ) as ClientSettingsPatch;
+ const serverPatch = Object.fromEntries(
+ Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
+ ) as ServerSettingsPatch;
+ const serverKeys = Object.keys(serverPatch);
+ const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
+ const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
+ const unscopableKeys = isProjectScope
+ ? serverKeys.filter((key) => !isProjectScopedSettingKey(key))
+ : [];
+ const serverWrites: ScopedServerWrite[] =
+ serverKeys.length === 0
+ ? []
+ : isProjectScope
+ ? unscopableKeys.length > 0
+ ? []
+ : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
+ // Object-valued keys arrive as partial patches (the writing style
+ // rows send one field); an override entry stores the whole value,
+ // so complete the patch from the target's effective value.
+ const effective = resolveProjectSettings(settings, projectId).settings;
+ const next: Record<string, unknown> = { ...current };
+ for (const [key, value] of Object.entries(serverPatch)) {
+ const base = effective[key as keyof ServerSettings];
+ next[key] =
+ isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
+ }
+ return next as ProjectSettingsOverrides;
+ })
+ : scope.kind === "all" || scope.kind === "environment"
+ ? connectedEnvironments.map((environment) => ({
+ environmentId: environment.environmentId,
+ label: environment.label,
+ patch: serverPatch,
+ }))
+ : [];
+ const hasClientWrite = Object.keys(clientPatch).length > 0;
+ const hasWrite = hasClientWrite || serverWrites.length > 0;
+ const unavailableReason =
+ hasWrite || Object.keys(patch).length === 0
+ ? null
+ : scope.kind === "unavailable"
+ ? scope.message
+ : unscopableKeys.length > 0
+ ? "This setting is environment-wide and cannot be overridden by a project."
+ : isProjectScope
+ ? "Connect the selected checkouts, or update their environments, to save a project override."
+ : `Connect ${scope.kind === "environment" ? scope.label : "an environment"} to save this setting.`;
+ return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
+}
+
+/** Remove the keys' project overrides so each member inherits its environment value again. */
+export function planScopedSettingsClear(
+ scope: ResolvedSettingsScope,
+ environments: readonly ScopedSettingsEnvironment[],
+ keys: readonly ProjectScopedServerSettingKey[],
+) {
+ const serverWrites =
+ scope.kind === "project" || scope.kind === "checkout"
+ ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
+ clearProjectSettingsOverrides(settings, projectId, keys),
+ )
+ : [];
+ return {
+ clientPatch: {} as ClientSettingsPatch,
+ hasClientWrite: false,
+ serverWrites,
+ unavailableReason:
+ serverWrites.length > 0
+ ? null
+ : "Connect the selected checkouts, or update their environments, to reset this override.",
+ };
+}
+
+export interface ProjectOverrideEntry {
+ readonly environmentId: EnvironmentId;
+ readonly projectId: ProjectId;
+}
+
+/**
+ * The projects on the selected environments that override `keys`. An
+ * environment edit leaves these untouched, so the row can name them and
+ * offer to clear them.
+ */
+export function listProjectOverrides(
+ environments: readonly ScopedSettingsEnvironment[],
+ keys: readonly (keyof ServerSettings)[],
+): readonly ProjectOverrideEntry[] {
+ const scoped = keys.filter(isProjectScopedSettingKey);
+ if (scoped.length === 0) return [];
+ return environments.flatMap((environment) => {
+ const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
+ if (!overrides) return [];
+ return Object.entries(overrides).flatMap(([projectId, entry]) =>
+ scoped.some((key) => Object.hasOwn(entry, key))
+ ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
+ : [],
+ );
+ });
+}
+
+/** Drop `keys` from the named project entries so they follow the environment again. */
+export function planProjectOverridesClear(
+ environments: readonly ScopedSettingsEnvironment[],
+ entries: readonly ProjectOverrideEntry[],
+ keys: readonly ProjectScopedServerSettingKey[],
+) {
+ const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
+ const writes = new Map<EnvironmentId, ScopedServerWrite>();
+ for (const { environmentId, projectId } of entries) {
+ const environment = byId.get(environmentId);
+ if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
+ const settings = environment.serverConfig.settings;
+ const existing = writes.get(environmentId);
+ writes.set(environmentId, {
+ environmentId,
+ label: environment.label,
+ patch: {
+ projectSettingsOverrides: {
+ ...existing?.patch.projectSettingsOverrides,
+ [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
+ },
+ },
+ });
+ }
+ const serverWrites = [...writes.values()];
+ return {
+ clientPatch: {} as ClientSettingsPatch,
+ hasClientWrite: false,
+ serverWrites,
+ unavailableReason:
+ serverWrites.length > 0 ? null : "Connect the environments to reset these overrides.",
+ };
+}
+
+/** Wait for every target so a failed environment does not hide successful or later writes. */
+export async function persistScopedSettingsPatch(
+ plan: ReturnType<typeof planScopedSettingsPatch>,
+ persistServer: (input: {
+ environmentId: EnvironmentId;
+ input: { patch: ServerSettingsPatch };
+ }) => Promise<{ readonly _tag: "Success" | "Failure" }>,
+ persistClient: (patch: ClientSettingsPatch) => void,
+) {
+ if (plan.hasClientWrite) persistClient(plan.clientPatch);
+ const results = await Promise.allSettled(
+ plan.serverWrites.map(({ environmentId, patch }) =>
+ persistServer({ environmentId, input: { patch } }),
+ ),
+ );
+ const failedEnvironments = plan.serverWrites.filter((_, index) => {
+ const result = results[index];
+ return result?.status !== "fulfilled" || result.value._tag === "Failure";
+ });
+ return {
+ failedEnvironments,
+ savedEnvironmentCount: plan.serverWrites.length - failedEnvironments.length,
+ };
+}
diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx
index 540398c3aa4..57f23dd5b94 100644
--- a/apps/web/src/components/settings/settingsLayout.tsx
+++ b/apps/web/src/components/settings/settingsLayout.tsx
@@ -1,4 +1,6 @@
import { InfoIcon, Undo2Icon } from "lucide-react";
+import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
+import * as Equal from "effect/Equal";
import { useLocation, useNavigate } from "@tanstack/react-router";
import {
createContext,
@@ -19,6 +21,21 @@ import { cn } from "../../lib/utils";
import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { useOptionalSettingsScope } from "./SettingsScopeContext";
+import {
+ isProjectScopedSettingKey,
+ listProjectOverrides,
+ scopedSettingsAreMixed,
+ scopedSettingsSource,
+} from "./scopedSettings";
+import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings";
+import {
+ SettingInheritance,
+ type SettingInheritanceState,
+ type SettingOverridingProject,
+} from "./SettingInheritance";
+
+const EMPTY_SETTING_KEYS: readonly (keyof ServerSettings)[] = [];
declare module "@tanstack/react-router" {
interface HistoryState {
@@ -253,8 +270,11 @@ export function SettingsRow({
description,
status,
resetAction,
+ onResetOverride,
control,
serverScoped = false,
+ settingKeys = EMPTY_SETTING_KEYS,
+ mixed: mixedOverride,
children,
className,
...rowProps
@@ -263,37 +283,152 @@ export function SettingsRow({
description?: ReactNode;
status?: ReactNode;
resetAction?: ReactNode;
+ /** Replaces the default override clear for rows with side effects beyond the settings key. */
+ onResetOverride?: () => void;
control?: ReactNode;
serverScoped?: boolean;
+ settingKeys?: readonly (keyof ServerSettings)[];
+ mixed?: boolean;
children?: ReactNode;
}) {
const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
const primarySettingsAvailable = usePrimarySettingsAvailable();
- const unavailable = serverScoped && !primarySettingsAvailable;
- const renderedReset = unavailable ? null : resetAction;
+ const context = useOptionalSettingsScope();
+ const clearOverrides = useClearScopedSettings();
+ const clearProjectOverrides = useClearProjectOverrides();
+ const isProjectScope =
+ context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout");
+ const scopedKeys = settingKeys.filter(isProjectScopedSettingKey);
+ // A project scope can only edit keys that support overrides; the rest stay
+ // visible so the user sees the inherited value, but cannot change it here.
+ const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0;
+ const mixed =
+ mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys));
+ const source =
+ context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;
+ const unavailable =
+ serverScoped &&
+ !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable);
+ const inheritedFrom =
+ source === "environment" && context?.scope.environmentIds.length === 1
+ ? (context.environments.find(
+ (environment) => environment.environmentId === context.scope.environmentIds[0],
+ )?.label ?? "environment")
+ : "environment";
+ const environmentSettingsById = useMemo(
+ () =>
+ new Map(
+ (context?.connectedEnvironments ?? []).flatMap((environment) =>
+ environment.serverConfig
+ ? [[environment.environmentId, environment.serverConfig.settings] as const]
+ : [],
+ ),
+ ),
+ [context?.connectedEnvironments],
+ );
+ // At environment scope, projects with their own value keep it when the
+ // environment default changes; the chain names them and can reset them.
+ const overridingProjects = useMemo((): SettingOverridingProject[] => {
+ if (context === null || isProjectScope || scopedKeys.length === 0) return [];
+ return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => {
+ const group = context.groups.find((candidate) =>
+ candidate.memberProjects.some(
+ (member) => member.environmentId === entry.environmentId && member.id === entry.projectId,
+ ),
+ );
+ if (!group) return [];
+ return [
+ {
+ ...entry,
+ label: group.displayName,
+ open: () =>
+ context.selectScope({
+ project: group.projectKey,
+ ...(context.search.machine ? { machine: context.search.machine } : {}),
+ }),
+ },
+ ];
+ });
+ }, [context, isProjectScope, scopedKeys]);
+ const renderedReset = unavailable ? null : isProjectScope && scopedKeys.length > 0 ? (
+ source === "project" || source === "mixed" ? (
+ <SettingResetButton
+ label={typeof title === "string" ? title : "override"}
+ tooltip="Reset to inherited value"
+ onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
+ />
+ ) : null
+ ) : (
+ resetAction
+ );
+ const inertControl = (message: string) => (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ // Focusable so keyboard users can still reach the explanation.
+ <span
+ tabIndex={0}
+ className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring sm:w-auto"
+ />
+ }
+ >
+ <div inert className="flex w-full items-center gap-2 opacity-50 sm:w-auto">
+ {control}
+ </div>
+ </TooltipTrigger>
+ <TooltipPopup side="top" className="max-w-72">
+ {message}
+ </TooltipPopup>
+ </Tooltip>
+ );
+ // A mixed selection keeps the real control with "Mixed" as its placeholder
+ // (the multi-selection inspector convention): the popover shows who has
+ // what, and picking a value applies it to every target.
const renderedControl =
- unavailable && control ? (
- <Tooltip>
- <TooltipTrigger
- render={
- // Focusable so keyboard users can still reach the explanation.
- <span
- tabIndex={0}
- className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring sm:w-auto"
- />
- }
- >
- <div inert className="flex w-full items-center gap-2 opacity-50 sm:w-auto">
- {control}
- </div>
- </TooltipTrigger>
- <TooltipPopup side="top" className="max-w-72">
- {PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE}
- </TooltipPopup>
- </Tooltip>
- ) : (
- control
+ unavailable && control
+ ? inertControl(
+ context
+ ? "Reconnect the selected environment to change this setting."
+ : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
+ )
+ : environmentWide && control
+ ? inertControl("Environment-wide setting. Select an environment to change it.")
+ : control;
+ // Server rows get an indicator beside the title that opens the resolution
+ // chain per target at every scope; client rows keep a plain status only.
+ const customized =
+ context !== null &&
+ settingKeys.some((key) =>
+ context.targets.some((candidate) => {
+ const environmentSettings = environmentSettingsById.get(candidate.environmentId);
+ return (
+ environmentSettings !== undefined &&
+ !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key])
+ );
+ }),
);
+ const inheritance: { state: SettingInheritanceState; summary: string } = mixed
+ ? { 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" };
+ const renderedInheritance =
+ context && serverScoped && settingKeys.length > 0 ? (
+ <SettingInheritance
+ state={inheritance.state}
+ summary={inheritance.summary}
+ targets={context.targets}
+ environments={context.connectedEnvironments}
+ keys={settingKeys}
+ overridingProjects={overridingProjects}
+ onClearOverrides={(entries) => clearProjectOverrides(entries, scopedKeys)}
+ />
+ ) : null;
+ const renderedStatus = status;
return (
<div
@@ -311,6 +446,11 @@ export function SettingsRow({
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-h-5 items-center gap-1.5">
<h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">{title}</h3>
+ {renderedInheritance ? (
+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
+ {renderedInheritance}
+ </span>
+ ) : null}
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
{renderedReset}
</span>
@@ -320,7 +460,9 @@ export function SettingsRow({
{description}
</p>
) : null}
- {status ? <div className="pt-0.5 text-xs text-muted-foreground">{status}</div> : null}
+ {renderedStatus ? (
+ <div className="pt-0.5 text-xs text-muted-foreground">{renderedStatus}</div>
+ ) : null}
</div>
{renderedControl ? (
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
diff --git a/apps/web/src/components/settings/settingsScope.test.ts b/apps/web/src/components/settings/settingsScope.test.ts
index 166e7121f57..0199f6eb6cb 100644
--- a/apps/web/src/components/settings/settingsScope.test.ts
+++ b/apps/web/src/components/settings/settingsScope.test.ts
@@ -60,19 +60,12 @@ function group(
const groups = [group("t3code", [first, second, third]), group("other", [other])];
describe("settings scope search", () => {
- it.each(["device", "all"] as const)(
- "clears narrower targets for an explicit %s selection",
- (scope) => {
- expect(
- validateSettingsScopeSearch({
- scope,
- project: "t3code",
- machine: laptopId,
- checkout: first.physicalProjectKey,
- }),
- ).toEqual({ scope });
- },
- );
+ it("ignores the retired scope key from older links", () => {
+ expect(validateSettingsScopeSearch({ scope: "device", project: "t3code" })).toEqual({
+ project: "t3code",
+ });
+ expect(validateSettingsScopeSearch({ scope: "all" })).toEqual({});
+ });
it("retains legacy project and machine links without inventing an explicit broad scope", () => {
expect(
@@ -96,15 +89,11 @@ describe("settings scope search", () => {
});
describe("settings scope resolution", () => {
- it("distinguishes this device from the default aggregate target", () => {
+ it("defaults to every environment with no project", () => {
expect(resolveSettingsScope({}, groups, environments)).toMatchObject({
kind: "all",
- environmentIds: [laptopId, serverId],
- });
- expect(resolveSettingsScope({ scope: "device" }, groups, environments)).toMatchObject({
- kind: "device",
members: [],
- environmentIds: [],
+ environmentIds: [laptopId, serverId],
});
});
diff --git a/apps/web/src/components/settings/settingsScope.ts b/apps/web/src/components/settings/settingsScope.ts
index 3d860d08852..efa53d7a337 100644
--- a/apps/web/src/components/settings/settingsScope.ts
+++ b/apps/web/src/components/settings/settingsScope.ts
@@ -6,8 +6,13 @@ import type {
} from "../../sidebarProjectGrouping";
import type { EnvironmentPresentation } from "../../state/environments";
+/**
+ * Two axes. `machine` narrows the environment axis (absent = all
+ * environments); `project` and `checkout` narrow the project axis (absent =
+ * environment defaults). Device-local preferences are not a scope: they
+ * render regardless of the selection because they never touch a server.
+ */
export interface SettingsScopeSearch {
- scope?: "device" | "all" | undefined;
project?: string | undefined;
machine?: string | undefined;
checkout?: string | undefined;
@@ -21,7 +26,7 @@ type ScopeTargets = {
export type ResolvedSettingsScope = ScopeTargets &
(
- | { kind: "device" | "all" }
+ | { kind: "all" }
| { kind: "environment"; environmentId: EnvironmentId }
| {
kind: "project";
@@ -41,9 +46,8 @@ export type ResolvedSettingsScope = ScopeTargets &
}
);
-/** Explicit broad targets replace narrower selections; stale IDs remain visible to the resolver. */
+/** Stale IDs remain visible to the resolver so a removed target reads as unavailable, not as "all". */
export function validateSettingsScopeSearch(raw: Record<string, unknown>): SettingsScopeSearch {
- if (raw.scope === "device" || raw.scope === "all") return { scope: raw.scope };
const stringValue = (value: unknown) =>
typeof value === "string" && value.trim().length > 0 ? value : undefined;
const project = stringValue(raw.project);
@@ -74,17 +78,6 @@ export function resolveSettingsScope(
environmentIds: [],
});
- if (search.scope === "device") {
- return { kind: "device", label: "This device", members: [], environmentIds: [] };
- }
- if (search.scope === "all") {
- return {
- kind: "all",
- label: "All environments",
- members: [],
- environmentIds: environments.map((environment) => environment.environmentId),
- };
- }
if (search.checkout && !search.project) {
return unavailable("project-required", "Select a project to choose one of its checkouts.");
}
diff --git a/apps/web/src/components/settings/SettingsScopeSelects.logic.test.ts b/apps/web/src/components/settings/settingsScopeAxis.test.ts
similarity index 98%
rename from apps/web/src/components/settings/SettingsScopeSelects.logic.test.ts
rename to apps/web/src/components/settings/settingsScopeAxis.test.ts
index d8e123631e6..54a87dc956a 100644
--- a/apps/web/src/components/settings/SettingsScopeSelects.logic.test.ts
+++ b/apps/web/src/components/settings/settingsScopeAxis.test.ts
@@ -7,7 +7,7 @@ import {
selectEnvironmentAxis,
selectProjectAxis,
settingsScopeEnvironmentLabel,
-} from "./SettingsScopeSelects.logic";
+} from "./settingsScopeAxis";
const first = {
environmentId: EnvironmentId.make("first"),
diff --git a/apps/web/src/components/settings/SettingsScopeSelects.logic.ts b/apps/web/src/components/settings/settingsScopeAxis.ts
similarity index 100%
rename from apps/web/src/components/settings/SettingsScopeSelects.logic.ts
rename to apps/web/src/components/settings/settingsScopeAxis.ts
diff --git a/apps/web/src/components/settings/settingsScopeNavigation.test.ts b/apps/web/src/components/settings/settingsScopeNavigation.test.ts
new file mode 100644
index 00000000000..a613f3adf42
--- /dev/null
+++ b/apps/web/src/components/settings/settingsScopeNavigation.test.ts
@@ -0,0 +1,247 @@
+import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
+import {
+ createMemoryHistory,
+ createRootRoute,
+ createRoute,
+ createRouter,
+ redirect,
+} from "@tanstack/react-router";
+import { describe, expect, it } from "vite-plus/test";
+
+import { resolveSettingsScope } from "./settingsScope";
+import { retainSettingsScope, validateSettingsRouteSearch } from "./settingsScopeNavigation";
+
+const checkoutSearch = {
+ project: "repository:t3code",
+ machine: "remote-server",
+ checkout: "remote-server:/home/user/T3 Code",
+};
+
+function createSettingsRouter(initialEntry = "/settings/general") {
+ const root = createRootRoute();
+ const settings = createRoute({
+ getParentRoute: () => root,
+ path: "settings",
+ validateSearch: validateSettingsRouteSearch,
+ search: { middlewares: [retainSettingsScope] },
+ beforeLoad: ({ location }) => {
+ if (location.pathname === "/settings") {
+ throw redirect({ to: "/settings/general", replace: true });
+ }
+ },
+ });
+ const general = createRoute({ getParentRoute: () => settings, path: "general" });
+ const projects = createRoute({ getParentRoute: () => settings, path: "projects" });
+ const integrations = createRoute({ getParentRoute: () => settings, path: "integrations" });
+ const sourceControl = createRoute({ getParentRoute: () => settings, path: "source-control" });
+ const providers = createRoute({
+ getParentRoute: () => settings,
+ path: "providers",
+ validateSearch: (raw: Record<string, unknown>) => ({
+ ...(typeof raw.environmentId === "string" && raw.environmentId.trim()
+ ? { environmentId: EnvironmentId.make(raw.environmentId) }
+ : {}),
+ ...(typeof raw.instanceId === "string" && raw.instanceId.trim()
+ ? { instanceId: ProviderInstanceId.make(raw.instanceId) }
+ : {}),
+ }),
+ });
+ const legacyProject = createRoute({
+ getParentRoute: () => root,
+ path: "projects/$projectKey",
+ beforeLoad: ({ params }) => {
+ throw redirect({
+ to: "/settings/projects",
+ search: { project: params.projectKey, machine: undefined },
+ replace: true,
+ });
+ },
+ });
+ return createRouter({
+ routeTree: root.addChildren([
+ settings.addChildren([general, projects, integrations, sourceControl, providers]),
+ legacyProject,
+ ]),
+ history: createMemoryHistory({ initialEntries: [initialEntry] }),
+ });
+}
+
+describe("settings scope navigation", () => {
+ it("replaces the default scope with an explicit environment, then replaces it with a project", async () => {
+ const router = createSettingsRouter();
+ await router.load();
+ await router.navigate({
+ to: "/settings/general",
+ search: { machine: "remote-server" },
+ hash: "",
+ });
+ expect(router.state.location.search).toEqual({ machine: "remote-server" });
+ await router.navigate({ to: "/settings/projects", search: { project: "another-project" } });
+ expect(router.state.location.search).toEqual({ project: "another-project" });
+ });
+
+ it("clears a checkout when selecting all environments and all projects", async () => {
+ const router = createSettingsRouter();
+ await router.navigate({ to: "/settings/general", search: checkoutSearch, hash: "old-setting" });
+ // The scope selects send every axis explicitly so "all" does not read as "unchanged".
+ await router.navigate({
+ to: "/settings/general",
+ search: { project: undefined, machine: undefined, checkout: undefined },
+ hash: "",
+ });
+ expect(router.state.location.search).toEqual({});
+ expect(router.state.location.hash).toBe("");
+ });
+
+ it("preserves the checkout through category and settings-search navigation", async () => {
+ const router = createSettingsRouter();
+ await router.navigate({ to: "/settings/general", search: checkoutSearch, hash: "new-threads" });
+ await router.navigate({ to: "/settings/integrations", hash: "", replace: true });
+ expect(router.state.location.search).toEqual(checkoutSearch);
+ expect(router.state.location.hash).toBe("");
+ await router.navigate({ to: "/settings/source-control", hash: "source-control-writing-style" });
+ expect(router.state.location.search).toEqual(checkoutSearch);
+ expect(router.state.location.hash).toBe("source-control-writing-style");
+ await router.navigate({ to: "/settings/projects", hash: "project-defaults" });
+ expect(router.state.location.search).toEqual(checkoutSearch);
+ });
+
+ it.each(["/settings/projects", "/settings/integrations", "/settings/source-control"] as const)(
+ "keeps %s when regrouping or selecting a target from the shared settings layout",
+ async (to) => {
+ const router = createSettingsRouter();
+ await router.navigate({ to, search: checkoutSearch });
+
+ const regroupedCheckout = { ...checkoutSearch, project: "separate:t3code" };
+ await router.navigate({
+ from: "/settings",
+ to: router.state.location.pathname,
+ search: () => regroupedCheckout,
+ replace: true,
+ hashScrollIntoView: false,
+ });
+ expect(router.state.location.pathname).toBe(to);
+ expect(router.state.location.search).toEqual(regroupedCheckout);
+ expect(router.state.redirect).toBeUndefined();
+
+ await router.navigate({
+ from: "/settings",
+ to: router.state.location.pathname,
+ search: () => ({ machine: "another-server" }),
+ hash: "",
+ resetScroll: false,
+ });
+ expect(router.state.location.pathname).toBe(to);
+ expect(router.state.location.search).toEqual({ machine: "another-server" });
+ expect(router.state.location.hash).toBe("");
+
+ const selectedCheckout = {
+ project: "another-project",
+ machine: "another-server",
+ checkout: "another-server:/home/user/Another checkout",
+ };
+ await router.navigate({
+ from: "/settings",
+ to: router.state.location.pathname,
+ search: () => selectedCheckout,
+ hash: "requested-setting",
+ });
+ expect(router.state.location.pathname).toBe(to);
+ expect(router.state.location.search).toEqual(selectedCheckout);
+ expect(router.state.location.hash).toBe("requested-setting");
+ },
+ );
+
+ it("honors an explicit provider environment and drops its instance on category navigation", async () => {
+ const router = createSettingsRouter();
+ await router.navigate({ to: "/settings/general", search: checkoutSearch });
+ await router.navigate({
+ to: "/settings/providers",
+ search: {
+ environmentId: EnvironmentId.make("provider-server"),
+ instanceId: ProviderInstanceId.make("codex-work"),
+ },
+ });
+ expect(router.state.location.search).toEqual({
+ machine: "provider-server",
+ environmentId: "provider-server",
+ instanceId: "codex-work",
+ });
+ await router.navigate({ to: "/settings/general", hash: "" });
+ expect(router.state.location.search).toEqual({ machine: "provider-server" });
+ });
+
+ it("preserves the environment from an initially loaded legacy provider URL", async () => {
+ const router = createSettingsRouter(
+ "/settings/providers?environmentId=provider-server&instanceId=codex-work",
+ );
+ await router.load();
+ await router.navigate({ to: "/settings/general" });
+ expect(router.state.location.search).toEqual({ machine: "provider-server" });
+ });
+
+ it("retains an explicit unavailable target rather than reviving the previous environment", async () => {
+ const router = createSettingsRouter();
+ await router.navigate({ to: "/settings/general", search: { machine: "online" } });
+ await router.navigate({ to: "/settings/general", search: { machine: "removed" } });
+ expect(router.state.location.search).toEqual({ machine: "removed" });
+ expect(
+ resolveSettingsScope(
+ router.state.location.search,
+ [],
+ [{ environmentId: EnvironmentId.make("online"), label: "Online" }],
+ ),
+ ).toMatchObject({
+ kind: "unavailable",
+ reason: "environment-missing",
+ environmentIds: [],
+ });
+ });
+
+ it("respects explicit clearing keys instead of restoring the previous checkout", async () => {
+ const router = createSettingsRouter();
+ await router.navigate({ to: "/settings/general", search: checkoutSearch });
+ await router.navigate({
+ to: "/settings/projects",
+ search: { project: "different-project", machine: undefined },
+ });
+ expect(router.state.location.search).toEqual({ project: "different-project" });
+ });
+
+ it("preserves escaped checkout identifiers across reload and browser history", async () => {
+ const router = createSettingsRouter();
+ await router.navigate({ to: "/settings/general", search: checkoutSearch });
+ const checkoutHref = router.state.location.href;
+ await router.navigate({ to: "/settings/general", search: { machine: "another" } });
+ router.history.back();
+ await router.load();
+ expect(router.state.location.search).toEqual(checkoutSearch);
+ const reloaded = createSettingsRouter(checkoutHref);
+ await reloaded.load();
+ expect(reloaded.state.location.search).toEqual(checkoutSearch);
+ await reloaded.navigate({ to: "/settings/integrations", hash: "agent-browser-access" });
+ expect(reloaded.state.location.search).toEqual(checkoutSearch);
+ });
+
+ it("redirects legacy project links without carrying the prior checkout scope", async () => {
+ const router = createSettingsRouter();
+ await router.navigate({ to: "/settings/general", search: checkoutSearch });
+ await router.navigate({
+ to: "/projects/$projectKey",
+ params: { projectKey: "legacy-project" },
+ });
+ expect(router.state.redirect).not.toBeUndefined();
+ await router.navigate(router.state.redirect!.options);
+ expect(router.state.location.pathname).toBe("/settings/projects");
+ expect(router.state.location.search).toEqual({ project: "legacy-project" });
+ });
+
+ it("keeps scope through the settings index redirect", async () => {
+ const router = createSettingsRouter();
+ await router.navigate({ to: "/settings", search: { machine: "remote-server" } });
+ expect(router.state.redirect).not.toBeUndefined();
+ await router.navigate(router.state.redirect!.options);
+ expect(router.state.location.pathname).toBe("/settings/general");
+ expect(router.state.location.search).toEqual({ machine: "remote-server" });
+ });
+});
diff --git a/apps/web/src/components/settings/settingsScopeNavigation.ts b/apps/web/src/components/settings/settingsScopeNavigation.ts
new file mode 100644
index 00000000000..e4f3c70d574
--- /dev/null
+++ b/apps/web/src/components/settings/settingsScopeNavigation.ts
@@ -0,0 +1,32 @@
+import type { SearchMiddleware } from "@tanstack/react-router";
+
+import { validateSettingsScopeSearch, type SettingsScopeSearch } from "./settingsScope";
+
+/** Accept legacy provider links without replacing an explicit settings scope. */
+export function validateSettingsRouteSearch(raw: Record<string, unknown>) {
+ return validateSettingsScopeSearch(
+ typeof raw.environmentId === "string" && raw.machine === undefined && raw.project === undefined
+ ? { ...raw, machine: raw.environmentId }
+ : raw,
+ );
+}
+
+const SCOPE_KEYS = [
+ "project",
+ "machine",
+ "checkout",
+] as const satisfies readonly (keyof SettingsScopeSearch)[];
+const TARGET_INPUT_KEYS = [...SCOPE_KEYS, "environmentId"];
+
+/**
+ * Category links keep the target, while an explicit target replaces the entire
+ * previous selection. `environmentId` is the legacy provider deep-link target.
+ */
+export const retainSettingsScope: SearchMiddleware<SettingsScopeSearch> = ({ search, next }) => {
+ const result = next(search);
+ if (TARGET_INPUT_KEYS.some((key) => Object.hasOwn(result, key))) return result;
+ const previousScope = Object.fromEntries(
+ SCOPE_KEYS.filter((key) => search[key] !== undefined).map((key) => [key, search[key]]),
+ );
+ return { ...previousScope, ...result };
+};
diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts
index e03d624fd2b..6b4a5f9cdd8 100644
--- a/apps/web/src/components/settings/settingsSearch.test.ts
+++ b/apps/web/src/components/settings/settingsSearch.test.ts
@@ -1,7 +1,12 @@
import { describe, expect, it, vi } from "vite-plus/test";
+import { EnvironmentId } from "@t3tools/contracts";
import {
filterAvailableSettingsSearchItems,
+ getSettingsSearchTargetScope,
+ getThreadAutoSettlementSearchAvailability,
+ isSettingsOverviewVisible,
+ isSettingsSearchScopeAvailable,
searchableSetting,
searchSettings,
SETTINGS_SEARCH_ITEMS,
@@ -143,7 +148,7 @@ describe("searchSettings", () => {
it("hides settings whose controls are unavailable", () => {
const available = filterAvailableSettingsSearchItems({
hasCloudPublicConfig: false,
- hasPrimaryEnvironment: false,
+ hasEnvironment: false,
hasProviderSettingsEnvironment: false,
canManageLocalBackend: false,
isWslSettingsRowVisible: false,
@@ -171,7 +176,7 @@ describe("searchSettings", () => {
it("shows automatic settlement settings when the server supports them", () => {
const available = filterAvailableSettingsSearchItems({
hasCloudPublicConfig: false,
- hasPrimaryEnvironment: false,
+ hasEnvironment: false,
hasProviderSettingsEnvironment: false,
canManageLocalBackend: false,
isWslSettingsRowVisible: false,
@@ -256,4 +261,194 @@ describe("searchSettings", () => {
targetId: "browser-profiles",
});
});
+
+ it.each([
+ ["default model", "default-model", "/settings/general"],
+ ["new threads", "new-threads", "/settings/general"],
+ ["agent browser access", "agent-browser-access", "/settings/integrations"],
+ ["automatically pull", "automatic-pull", "/settings/source-control"],
+ ["actions", "project-actions", "/settings/projects"],
+ ["project overview", "project-overview", "/settings/projects"],
+ ])("routes %s to its owning category", (query, id, to) => {
+ expect(searchSettings(query)[0]).toMatchObject({ id, to });
+ });
+
+ it("keeps environment settings discoverable without a primary environment", () => {
+ const available = filterAvailableSettingsSearchItems({
+ hasCloudPublicConfig: false,
+ hasEnvironment: true,
+ hasProviderSettingsEnvironment: true,
+ canManageLocalBackend: false,
+ isWslSettingsRowVisible: false,
+ hasThreadAutoSettlement: true,
+ });
+ expect(searchSettings("writing style", available)[0]?.id).toBe("source-control-writing-style");
+ expect(searchSettings("auto-settle", available)).toHaveLength(3);
+ });
+});
+
+describe("settings search targets", () => {
+ it.each([
+ "auto-settle-inactive-threads",
+ "auto-settle-merged-threads",
+ "days-before-auto-settle",
+ ])("retains the capability requirement for %s", (targetId) => {
+ expect(getSettingsSearchTargetScope(targetId)).toMatchObject({
+ scope: "project-defaults",
+ requiresThreadAutoSettlement: true,
+ });
+ });
+
+ it("treats device-local rows as reachable from every selection", () => {
+ const setting = getSettingsSearchTargetScope("time-format")!;
+ expect(setting).toEqual({ title: "Time format", scope: null });
+ expect(isSettingsSearchScopeAvailable(setting.scope, "project")).toBe(true);
+ expect(isSettingsSearchScopeAvailable(setting.scope, "all")).toBe(true);
+ expect(getSettingsSearchTargetScope("appearance")).toMatchObject({ scope: null });
+ expect(getSettingsSearchTargetScope("missing-setting")).toBeNull();
+ });
+
+ it.each(["all", "environment", "project", "checkout"] as const)(
+ "makes browser access editable at the %s scope",
+ (kind) => {
+ const setting = getSettingsSearchTargetScope("agent-browser-access")!;
+ expect(isSettingsSearchScopeAvailable(setting.scope, kind)).toBe(true);
+ expect(isSettingsSearchScopeAvailable(setting.scope, "unavailable")).toBe(false);
+ },
+ );
+
+ it("lets project-scopable rows resolve at every server-backed scope", () => {
+ const model = getSettingsSearchTargetScope("text-generation-model")!;
+ expect(isSettingsSearchScopeAvailable(model.scope, "all")).toBe(true);
+ expect(isSettingsSearchScopeAvailable(model.scope, "environment")).toBe(true);
+ expect(isSettingsSearchScopeAvailable(model.scope, "project")).toBe(true);
+ });
+
+ it("reaches source control discovery and git fetch interval from the default scope", () => {
+ for (const id of ["source-control", "git-fetch-interval"]) {
+ const item = getSettingsSearchTargetScope(id)!;
+ expect(isSettingsSearchScopeAvailable(item.scope, "all")).toBe(true);
+ expect(isSettingsSearchScopeAvailable(item.scope, "environment")).toBe(true);
+ expect(isSettingsSearchScopeAvailable(item.scope, "project")).toBe(false);
+ }
+ });
+
+ it("keeps environment-wide settings out of project scopes", () => {
+ const updates = getSettingsSearchTargetScope("provider-update-checks")!;
+ expect(updates.scope).toBe("environment-defaults");
+ expect(isSettingsSearchScopeAvailable(updates.scope, "environment")).toBe(true);
+ expect(isSettingsSearchScopeAvailable(updates.scope, "all")).toBe(true);
+ expect(isSettingsSearchScopeAvailable(updates.scope, "project")).toBe(false);
+ const streaming = getSettingsSearchTargetScope("legacy-token-streaming")!;
+ expect(streaming.scope).toBe("project-defaults");
+ expect(isSettingsSearchScopeAvailable(streaming.scope, "project")).toBe(true);
+ for (const id of ["legacy-plan-mode", "legacy-context-window-indicator", "legacy-sidebar"]) {
+ expect(getSettingsSearchTargetScope(id)!.scope).toBeNull();
+ }
+ });
+});
+
+describe("auto-settlement search availability", () => {
+ function environment(id: string, { connected = true, loaded = true, supported = true } = {}) {
+ return {
+ environmentId: EnvironmentId.make(id),
+ connection: { phase: connected ? ("connected" as const) : ("offline" as const) },
+ serverConfig: loaded
+ ? { environment: { capabilities: { threadAutoSettlement: supported } } }
+ : null,
+ };
+ }
+
+ const capable = environment("capable");
+ const unsupported = environment("unsupported", { supported: false });
+ const offline = environment("offline", { connected: false });
+ const loading = environment("loading", { loaded: false });
+ const environments = [capable, unsupported, offline, loading];
+
+ it("keeps results discoverable when one connected environment supports them", () => {
+ const availability = getThreadAutoSettlementSearchAvailability(environments);
+ expect(availability.eligibleEnvironmentIds).toEqual([capable.environmentId]);
+ const items = filterAvailableSettingsSearchItems({
+ hasCloudPublicConfig: false,
+ hasEnvironment: true,
+ hasProviderSettingsEnvironment: true,
+ canManageLocalBackend: false,
+ isWslSettingsRowVisible: false,
+ hasThreadAutoSettlement: availability.eligibleEnvironmentIds.length > 0,
+ });
+ expect(searchSettings("auto-settle", items).map((item) => item.id)).toEqual([
+ "auto-settle-inactive-threads",
+ "auto-settle-merged-threads",
+ "days-before-auto-settle",
+ ]);
+ });
+
+ it("offers only capable environments when an aggregate has mixed capabilities", () => {
+ expect(
+ getThreadAutoSettlementSearchAvailability(environments, {
+ kind: "all",
+ environmentIds: environments.map((entry) => entry.environmentId),
+ }),
+ ).toEqual({ eligibleEnvironmentIds: [capable.environmentId], isTargetAvailable: false });
+ });
+
+ it("allows a capable named environment regardless of other environments' capabilities", () => {
+ expect(
+ getThreadAutoSettlementSearchAvailability(environments, {
+ kind: "environment",
+ environmentIds: [capable.environmentId],
+ }).isTargetAvailable,
+ ).toBe(true);
+ });
+
+ it.each([unsupported, offline, loading])(
+ "does not render the target on $environmentId or silently fall back",
+ (selected) => {
+ expect(
+ getThreadAutoSettlementSearchAvailability(environments, {
+ kind: "environment",
+ environmentIds: [selected.environmentId],
+ }),
+ ).toEqual({ eligibleEnvironmentIds: [capable.environmentId], isTargetAvailable: false });
+ },
+ );
+
+ it("offers a capable environment instead of a dead target at an unavailable scope", () => {
+ expect(
+ getThreadAutoSettlementSearchAvailability(environments, {
+ kind: "unavailable",
+ environmentIds: [capable.environmentId],
+ }),
+ ).toEqual({ eligibleEnvironmentIds: [capable.environmentId], isTargetAvailable: false });
+ });
+
+ it("ignores offline and unloaded targets when all connected targets support the setting", () => {
+ const selected = [capable, offline, loading];
+ expect(
+ getThreadAutoSettlementSearchAvailability(selected, {
+ kind: "all",
+ environmentIds: selected.map((entry) => entry.environmentId),
+ }).isTargetAvailable,
+ ).toBe(true);
+ });
+
+ it("offers no unavailable environments when none can render the setting", () => {
+ const selected = [unsupported, offline, loading];
+ expect(
+ getThreadAutoSettlementSearchAvailability(selected, {
+ kind: "all",
+ environmentIds: selected.map((entry) => entry.environmentId),
+ }),
+ ).toEqual({ eligibleEnvironmentIds: [], isTargetAvailable: false });
+ expect(getThreadAutoSettlementSearchAvailability([]).eligibleEnvironmentIds).toEqual([]);
+ });
+});
+
+describe("settings sidebar scope", () => {
+ it("shows Overview only for project and checkout targets", () => {
+ expect(isSettingsOverviewVisible({})).toBe(false);
+ expect(isSettingsOverviewVisible({ machine: "remote" })).toBe(false);
+ expect(isSettingsOverviewVisible({ project: "project" })).toBe(true);
+ expect(isSettingsOverviewVisible({ project: "project", checkout: "checkout" })).toBe(true);
+ });
});
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index f5657999071..605023c2326 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -1,5 +1,12 @@
import { isElectron } from "~/env";
import { isMacPlatform, isWindowsPlatform, normalizeSearchText } from "~/lib/utils";
+import type { EnvironmentId } from "@t3tools/contracts";
+import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
+import {
+ validateSettingsScopeSearch,
+ type ResolvedSettingsScope,
+ type SettingsScopeSearch,
+} from "./settingsScope";
export type SettingsPath =
| "/settings/projects"
@@ -13,6 +20,19 @@ export type SettingsPath =
| "/settings/connections"
| "/settings/archived";
+/**
+ * Where a setting can be edited. Device-local rows have no scope: they render
+ * at every selection. `project-defaults` rows accept project overrides, so
+ * they are reachable from any server-backed selection.
+ */
+export type SettingsSearchScope =
+ | "environment"
+ | "environment-defaults"
+ | "project-defaults"
+ | "project"
+ | "checkout"
+ | "connections";
+
export interface SettingsSearchItem {
readonly id: string;
readonly title: string;
@@ -20,6 +40,7 @@ export interface SettingsSearchItem {
readonly targetId?: string;
/** Descriptions, option labels, and aliases people may remember instead of the title. */
readonly searchTerms?: ReadonlyArray<string>;
+ readonly scope?: SettingsSearchScope;
// Its row only renders in the desktop app, so a browser result would land on
// an anchor that isn't there.
readonly desktopOnly?: boolean;
@@ -28,7 +49,7 @@ export interface SettingsSearchItem {
// not expose a result that points to a missing anchor.
readonly windowsOnly?: boolean;
readonly cloudOnly?: boolean;
- readonly primaryOnly?: boolean;
+ readonly environmentOnly?: boolean;
readonly providerSettingsOnly?: boolean;
readonly localBackendManagementOnly?: boolean;
readonly wslAvailableOnly?: boolean;
@@ -37,7 +58,7 @@ export interface SettingsSearchItem {
export interface SettingsSearchAvailability {
readonly hasCloudPublicConfig: boolean;
- readonly hasPrimaryEnvironment: boolean;
+ readonly hasEnvironment: boolean;
readonly hasProviderSettingsEnvironment: boolean;
readonly canManageLocalBackend: boolean;
readonly isWslSettingsRowVisible: boolean;
@@ -49,9 +70,9 @@ export interface SettingsSearchAvailability {
* subtitles both render from this record, so each label exists once.
*/
export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
+ "/settings/projects": "Project",
"/settings/general": "General",
"/settings/appearance": "Appearance",
- "/settings/projects": "Projects",
"/settings/keybindings": "Keybindings",
"/settings/snap-shot": "SnapShots",
"/settings/providers": "Providers",
@@ -70,10 +91,22 @@ export const SETTINGS_SEARCH_ITEMS = [
{
id: "project-defaults",
title: "Project defaults and overrides",
+ to: "/settings/general",
+ scope: "project-defaults",
+ searchTerms: ["model workspace environments projects inheritance checkout"],
+ },
+ {
+ id: "project-overview",
+ title: "Project overview",
to: "/settings/projects",
- searchTerms: [
- "model workspace browser machines projects inheritance automatic pull checkout grouping actions scripts",
- ],
+ searchTerms: ["name icon emoji image checkout remove delete"],
+ },
+ {
+ id: "default-model",
+ title: "Default model",
+ to: "/settings/general",
+ scope: "project-defaults",
+ searchTerms: ["new thread project provider reasoning effort"],
},
{
id: "color-scheme",
@@ -174,6 +207,7 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/general",
searchTerms: ["sidebar inactivity days no activity automatically"],
requiresThreadAutoSettlement: true,
+ scope: "project-defaults",
},
{
id: "auto-settle-merged-threads",
@@ -181,6 +215,7 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/general",
searchTerms: ["pull request merge closed automatically sidebar"],
requiresThreadAutoSettlement: true,
+ scope: "project-defaults",
},
{
id: "days-before-auto-settle",
@@ -189,6 +224,7 @@ export const SETTINGS_SEARCH_ITEMS = [
targetId: "auto-settle-inactive-threads",
searchTerms: ["thread timeout activity sidebar"],
requiresThreadAutoSettlement: true,
+ scope: "project-defaults",
},
{
id: "time-format",
@@ -231,11 +267,13 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Provider update checks",
to: "/settings/general",
searchTerms: ["installed cli versions newer available codex claude cursor grok opencode"],
+ scope: "environment-defaults",
},
{
id: "continue-threads-after-server-update",
title: "Continue threads after restarts",
to: "/settings/general",
+ scope: "project-defaults",
searchTerms: [
"resume running active interrupted work restart reboot machine crash desktop update automatically",
],
@@ -244,6 +282,7 @@ export const SETTINGS_SEARCH_ITEMS = [
id: "background-activity",
title: "Background activity",
to: "/settings/general",
+ scope: "environment-defaults",
searchTerms: [
"balanced performance battery saver advanced git fetch provider health refresh host power monitor idle policy",
],
@@ -251,19 +290,22 @@ export const SETTINGS_SEARCH_ITEMS = [
{
id: "new-threads",
title: "New threads",
- to: "/settings/projects",
+ to: "/settings/general",
+ scope: "project-defaults",
searchTerms: ["default workspace mode draft local worktree"],
},
{
id: "start-from-origin",
title: "Start from origin",
to: "/settings/general",
+ scope: "project-defaults",
searchTerms: ["new worktrees latest matching remote branch local"],
},
{
id: "add-project-starts-in",
title: "Add project starts in",
to: "/settings/general",
+ scope: "environment-defaults",
searchTerms: ["base directory folder browser path home"],
},
{
@@ -295,6 +337,7 @@ export const SETTINGS_SEARCH_ITEMS = [
id: "text-generation-model",
title: "Text generation model",
to: "/settings/general",
+ scope: "project-defaults",
searchTerms: ["generated thread titles source control content default provider"],
},
{
@@ -319,6 +362,7 @@ export const SETTINGS_SEARCH_ITEMS = [
id: "legacy-token-streaming",
title: "Stream token by token (legacy)",
to: "/settings/general",
+ scope: "project-defaults",
searchTerms: ["response output old compatibility"],
},
{
@@ -399,8 +443,9 @@ export const SETTINGS_SEARCH_ITEMS = [
{
id: "agent-browser-access",
title: "Agent browser access",
- to: "/settings/projects",
- searchTerms: ["allow open drive preview tools sessions"],
+ to: "/settings/integrations",
+ scope: "project-defaults",
+ searchTerms: ["allow disable enable open drive preview tools sessions project override"],
},
{
id: "device-hosts",
@@ -476,10 +521,25 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/integrations",
searchTerms: ["agent opens browser pop into view hide"],
},
+ {
+ id: "automatic-pull",
+ title: "Automatically pull",
+ to: "/settings/source-control",
+ scope: "project-defaults",
+ searchTerms: ["auto pull default branch current checkout fast forward upstream"],
+ },
+ {
+ id: "pull-request-merge-method",
+ title: "Default merge method",
+ to: "/settings/source-control",
+ scope: "project-defaults",
+ searchTerms: ["pull request merge squash rebase last selected"],
+ },
{
id: "source-control",
title: "Source control",
to: "/settings/source-control",
+ scope: "environment-defaults",
searchTerms: [
"version control git github gitlab bitbucket azure devops hosting integrations credentials scan server environment",
],
@@ -491,7 +551,8 @@ export const SETTINGS_SEARCH_ITEMS = [
searchTerms: [
"automatic remote branch refresh background credentials security keys seconds off",
],
- primaryOnly: true,
+ environmentOnly: true,
+ scope: "environment-defaults",
},
{
id: "source-control-writing-style",
@@ -500,14 +561,14 @@ export const SETTINGS_SEARCH_ITEMS = [
searchTerms: [
"repository conventions conventional commits custom instructions change descriptions request titles",
],
- primaryOnly: true,
+ environmentOnly: true,
},
{
id: "follow-change-request-templates",
title: "Follow change request templates",
to: "/settings/source-control",
searchTerms: ["repository pr pull request description structure"],
- primaryOnly: true,
+ environmentOnly: true,
},
{
id: "source-control-writer-model",
@@ -516,7 +577,14 @@ export const SETTINGS_SEARCH_ITEMS = [
searchTerms: [
"override generated commit change request pr titles descriptions branch bookmark",
],
- primaryOnly: true,
+ environmentOnly: true,
+ scope: "project-defaults",
+ },
+ {
+ id: "project-actions",
+ title: "Actions",
+ to: "/settings/projects",
+ searchTerms: ["commands scripts setup run dev server checkout worktree t3.json import"],
},
{
id: "environment-icon",
@@ -606,6 +674,111 @@ export type SettingsSearchItemId = (typeof SETTINGS_SEARCH_ITEMS)[number]["id"];
const SEARCH_ITEMS_BY_ID = new Map(SETTINGS_SEARCH_ITEMS.map((item) => [item.id, item] as const));
+const SETTINGS_CATEGORY_SCOPES: Readonly<Record<SettingsPath, SettingsSearchScope | null>> = {
+ "/settings/projects": "project",
+ "/settings/general": null,
+ "/settings/appearance": null,
+ "/settings/snap-shot": null,
+ // Keybindings fan out to the selection; Providers shows the representative
+ // environment at any selection. Neither needs a particular scope to render.
+ "/settings/keybindings": null,
+ "/settings/providers": null,
+ "/settings/integrations": null,
+ "/settings/source-control": "environment-defaults",
+ "/settings/connections": "connections",
+ "/settings/archived": "project-defaults",
+};
+
+/** Search keeps the selected target. A missing row can explain its owning scope instead. */
+export function getSettingsSearchTargetScope(targetId: string) {
+ const items: readonly SettingsSearchItem[] = SETTINGS_SEARCH_ITEMS;
+ const item =
+ items.find((candidate) => candidate.id === targetId) ??
+ items.find((candidate) => candidate.targetId === targetId);
+ return item
+ ? {
+ title: item.title,
+ scope: item.scope ?? SETTINGS_CATEGORY_SCOPES[item.to],
+ ...(item.requiresThreadAutoSettlement ? { requiresThreadAutoSettlement: true } : {}),
+ }
+ : null;
+}
+
+interface AutoSettlementSearchEnvironment {
+ readonly environmentId: EnvironmentId;
+ readonly connection: { readonly phase: EnvironmentConnectionPhase };
+ readonly serverConfig: {
+ readonly environment: {
+ readonly capabilities: { readonly threadAutoSettlement?: boolean };
+ };
+ } | null;
+}
+
+/** Discovery needs one capable environment; the selected page needs every connected target to support it. */
+export function getThreadAutoSettlementSearchAvailability(
+ environments: readonly AutoSettlementSearchEnvironment[],
+ scope?: Pick<ResolvedSettingsScope, "kind" | "environmentIds">,
+) {
+ const connected = environments.filter(
+ (environment) =>
+ environment.connection.phase === "connected" && environment.serverConfig !== null,
+ );
+ const eligibleEnvironmentIds = connected
+ .filter(
+ (environment) =>
+ environment.serverConfig?.environment.capabilities.threadAutoSettlement === true,
+ )
+ .map((environment) => environment.environmentId);
+ const selected = connected.filter((environment) =>
+ scope?.environmentIds.includes(environment.environmentId),
+ );
+ return {
+ eligibleEnvironmentIds,
+ isTargetAvailable:
+ scope !== undefined &&
+ scope.kind !== "unavailable" &&
+ selected.length > 0 &&
+ selected.every((environment) => eligibleEnvironmentIds.includes(environment.environmentId)),
+ };
+}
+
+export function isSettingsSearchScopeAvailable(
+ requiredScope: SettingsSearchScope | null,
+ scopeKind: ResolvedSettingsScope["kind"],
+): boolean {
+ switch (requiredScope) {
+ case null:
+ case "connections":
+ return true;
+ case "environment":
+ case "checkout":
+ return requiredScope === scopeKind;
+ case "project":
+ return scopeKind === "project" || scopeKind === "checkout";
+ case "environment-defaults":
+ return scopeKind === "environment" || scopeKind === "all";
+ case "project-defaults":
+ return (
+ scopeKind === "environment" ||
+ scopeKind === "all" ||
+ scopeKind === "project" ||
+ scopeKind === "checkout"
+ );
+ }
+}
+
+function settingsScopeKindFromSearch(search: SettingsScopeSearch): ResolvedSettingsScope["kind"] {
+ const target = validateSettingsScopeSearch({ ...search });
+ if (target.checkout && !target.project) return "unavailable";
+ if (target.project) return target.checkout ? "checkout" : "project";
+ return target.machine ? "environment" : "all";
+}
+
+export function isSettingsOverviewVisible(search: SettingsScopeSearch): boolean {
+ const kind = settingsScopeKindFromSearch(search);
+ return kind === "project" || kind === "checkout";
+}
+
/**
* `id` and `title` props for the element a search item anchors to. Panels
* spread (or pick from) this instead of restating the strings, so the catalog
@@ -626,7 +799,7 @@ export function filterAvailableSettingsSearchItems(
return items.filter(
(item) =>
(!item.cloudOnly || availability.hasCloudPublicConfig) &&
- (!item.primaryOnly || availability.hasPrimaryEnvironment) &&
+ (!item.environmentOnly || availability.hasEnvironment) &&
(!item.providerSettingsOnly || availability.hasProviderSettingsEnvironment) &&
(!item.localBackendManagementOnly || availability.canManageLocalBackend) &&
(!item.wslAvailableOnly || availability.isWslSettingsRowVisible) &&
diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts
index a2f5ca62766..b4a892f4527 100644
--- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts
+++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts
@@ -1,23 +1,22 @@
import { useMemo } from "react";
-import { useAtomValue } from "@effect/atom-react";
import { AuthAccessWriteScope } from "@t3tools/contracts";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { isElectron } from "~/env";
import { desktopWslStateAtom } from "~/state/desktopWslState";
-import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
+import { useEnvironments } from "~/state/environments";
import { useEnvironmentQuery } from "~/state/query";
import { usePrimarySessionState } from "~/environments/primary";
-import { primaryServerConfigAtom } from "~/state/server";
import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic";
import { isProviderSettingsEnvironmentAvailable } from "./ProviderSettingsPanel.logic";
-import { filterAvailableSettingsSearchItems } from "./settingsSearch";
+import {
+ filterAvailableSettingsSearchItems,
+ getThreadAutoSettlementSearchAvailability,
+} from "./settingsSearch";
export function useAvailableSettingsSearchItems() {
- const primaryEnvironmentId = usePrimaryEnvironmentId();
const { environments } = useEnvironments();
const primarySessionState = usePrimarySessionState();
- const primaryServerConfig = useAtomValue(primaryServerConfigAtom);
const desktopWsl = useEnvironmentQuery(isElectron ? desktopWslStateAtom : null);
const canManageLocalBackend =
isElectron ||
@@ -29,7 +28,7 @@ export function useAvailableSettingsSearchItems() {
() =>
filterAvailableSettingsSearchItems({
hasCloudPublicConfig: hasCloudPublicConfig(),
- hasPrimaryEnvironment: primaryEnvironmentId !== null,
+ hasEnvironment: environments.some((environment) => environment.serverConfig !== null),
hasProviderSettingsEnvironment: environments.some((environment) =>
isProviderSettingsEnvironmentAvailable({
connectionPhase: environment.connection.phase,
@@ -42,15 +41,8 @@ export function useAvailableSettingsSearchItems() {
error: desktopWsl.error,
}),
hasThreadAutoSettlement:
- primaryServerConfig?.environment.capabilities.threadAutoSettlement === true,
+ getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0,
}),
- [
- canManageLocalBackend,
- desktopWsl.data,
- desktopWsl.error,
- environments,
- primaryEnvironmentId,
- primaryServerConfig,
- ],
+ [canManageLocalBackend, desktopWsl.data, desktopWsl.error, environments],
);
}
diff --git a/apps/web/src/components/settings/useProjectScriptSettings.ts b/apps/web/src/components/settings/useProjectScriptSettings.ts
new file mode 100644
index 00000000000..ed7ded33c30
--- /dev/null
+++ b/apps/web/src/components/settings/useProjectScriptSettings.ts
@@ -0,0 +1,193 @@
+import {
+ isAtomCommandInterrupted,
+ mapAtomCommandResult,
+ squashAtomCommandFailure,
+ type AtomCommandResult,
+} from "@t3tools/client-runtime/state/runtime";
+import {
+ type EnvironmentId,
+ type ProjectId,
+ type ProjectScript,
+ type ResolvedKeybindingsConfig,
+ type ServerSettings,
+} from "@t3tools/contracts";
+import { resolveProjectScripts } from "@t3tools/shared/projectScripts";
+import { clearProjectSettingsOverrides } from "@t3tools/shared/projectSettings";
+import * as Cause from "effect/Cause";
+import { AsyncResult } from "effect/unstable/reactivity";
+import { useRef, useState } from "react";
+
+import { isElectron } from "../../env";
+import {
+ decodeProjectScriptKeybindingRule,
+ keybindingValueForCommand,
+} from "../../lib/projectScriptKeybindings";
+import {
+ buildProjectScript,
+ commandForProjectScript,
+ nextProjectScriptId,
+} from "../../projectScripts";
+import { useProjects } from "../../state/entities";
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import type { NewProjectScriptInput } from "../projectScriptEditor";
+import { toastManager } from "../ui/toast";
+
+function reportScriptFailure(result: AtomCommandResult<unknown, unknown>) {
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add({
+ type: "error",
+ title: "Failed to save project actions",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ });
+ }
+ return mapAtomCommandResult(result, () => undefined);
+}
+
+/**
+ * Edits the action list on every target: the environment default when there is
+ * no project, else that project's override entry. Shortcuts follow on desktop.
+ */
+export function useProjectScriptSettings(
+ targets: readonly {
+ environmentId: EnvironmentId;
+ settings: ServerSettings;
+ keybindings: ResolvedKeybindingsConfig;
+ project?: { id: ProjectId; scripts: readonly ProjectScript[] };
+ }[],
+) {
+ const projects = useProjects();
+ const [saving, setSaving] = useState(false);
+ const savingRef = useRef(false);
+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, "project actions update");
+ const upsertKeybinding = useAtomCommand(
+ serverEnvironment.upsertKeybinding,
+ "action shortcut update",
+ );
+ const removeKeybinding = useAtomCommand(
+ serverEnvironment.removeKeybinding,
+ "action shortcut removal",
+ );
+
+ async function persist(
+ transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null,
+ scriptId?: string,
+ keybinding?: string | null,
+ ): Promise<AtomCommandResult<void, unknown>> {
+ if (savingRef.current || targets.length === 0) {
+ const message = "No available machine, or another action change is saving.";
+ toastManager.add({ type: "error", title: "Actions not saved", description: message });
+ return AsyncResult.failure(Cause.fail(new Error(message)));
+ }
+ savingRef.current = true;
+ setSaving(true);
+ try {
+ for (const { environmentId, settings, keybindings, project } of targets) {
+ const current = project
+ ? resolveProjectScripts(settings, project)
+ : settings.defaultProjectScripts;
+ const nextScripts = transform(current);
+ const effectiveScripts = nextScripts ?? settings.defaultProjectScripts;
+ const result = await updateSettings({
+ environmentId,
+ input: {
+ patch: project
+ ? {
+ projectSettingsOverrides: {
+ [project.id]:
+ nextScripts === null
+ ? clearProjectSettingsOverrides(settings, project.id, [
+ "defaultProjectScripts",
+ ])
+ : {
+ ...settings.projectSettingsOverrides[project.id],
+ defaultProjectScripts: nextScripts,
+ },
+ },
+ }
+ : { defaultProjectScripts: nextScripts ?? [] },
+ },
+ });
+ if (result._tag === "Failure") return reportScriptFailure(result);
+ if (!isElectron) continue;
+ const changedIds = scriptId
+ ? [scriptId]
+ : current
+ .filter((script) => !effectiveScripts.some((next) => next.id === script.id))
+ .map((script) => script.id);
+ for (const id of changedIds) {
+ const command = commandForProjectScript(id);
+ const previousValue = keybindingValueForCommand(keybindings, command);
+ const previous = previousValue
+ ? decodeProjectScriptKeybindingRule({ keybinding: previousValue, command })
+ : null;
+ const next = decodeProjectScriptKeybindingRule({ keybinding, command });
+ const retainedElsewhere =
+ !nextScripts?.some((script) => script.id === id) &&
+ ((project && settings.defaultProjectScripts.some((script) => script.id === id)) ||
+ Object.entries(settings.projectSettingsOverrides).some(
+ ([projectId, entry]) =>
+ projectId !== project?.id &&
+ entry.defaultProjectScripts?.some((script) => script.id === id),
+ ) ||
+ projects.some(
+ (other) =>
+ other.environmentId === environmentId &&
+ other.id !== project?.id &&
+ (project ? resolveProjectScripts(settings, other) : other.scripts).some(
+ (script) => script.id === id,
+ ),
+ ));
+ const bindingResult = next
+ ? await upsertKeybinding({
+ environmentId,
+ input:
+ previous && previous.key !== next.key ? { ...next, replace: previous } : next,
+ })
+ : previous && !retainedElsewhere
+ ? await removeKeybinding({ environmentId, input: previous })
+ : null;
+ if (bindingResult?._tag === "Failure") return reportScriptFailure(bindingResult);
+ }
+ }
+ return AsyncResult.success(undefined);
+ } finally {
+ savingRef.current = false;
+ setSaving(false);
+ }
+ }
+
+ function submit(scriptId: string | null, input: NewProjectScriptInput) {
+ const existingIds = [
+ ...projects.flatMap((project) => project.scripts.map((script) => script.id)),
+ ...targets.flatMap(({ settings, project }) =>
+ [
+ ...settings.defaultProjectScripts,
+ ...Object.values(settings.projectSettingsOverrides).flatMap(
+ (entry) => entry.defaultProjectScripts ?? [],
+ ),
+ ...(project?.scripts ?? []),
+ ].map((script) => script.id),
+ ),
+ ];
+ const id = scriptId ?? nextProjectScriptId(input.name, existingIds);
+ const next = buildProjectScript(id, input);
+ return persist(
+ (current) => {
+ const updated = current.map((script) =>
+ script.id === id
+ ? next
+ : input.runOnWorktreeCreate
+ ? { ...script, runOnWorktreeCreate: false }
+ : script,
+ );
+ return scriptId === null ? [...updated, next] : updated;
+ },
+ id,
+ input.keybinding,
+ );
+ }
+
+ return { saving, persist, submit };
+}
diff --git a/apps/web/src/components/settings/useScopedModelAvailability.ts b/apps/web/src/components/settings/useScopedModelAvailability.ts
new file mode 100644
index 00000000000..a851a1876ad
--- /dev/null
+++ b/apps/web/src/components/settings/useScopedModelAvailability.ts
@@ -0,0 +1,55 @@
+import type { ProviderInstanceId, UnifiedSettings } from "@t3tools/contracts";
+import { useCallback } from "react";
+
+import { getCustomModelOptionsByInstance } from "../../modelSelection";
+import {
+ applyProviderInstanceSettings,
+ deriveProviderInstanceEntries,
+ type ProviderInstanceEntry,
+} from "../../providerInstances";
+import { useEnvironments } from "../../state/environments";
+import { useSettingsScope } from "./SettingsScopeContext";
+
+/**
+ * A model choice fans out to every selected target, so it must exist on all
+ * of them. Returns the reason a (instance, model) pair cannot be applied, or
+ * null when every target can honor it. The representative's entries decide
+ * which driver the instance id names.
+ */
+export function useScopedModelDisabledReason(
+ settings: UnifiedSettings,
+ entries: readonly ProviderInstanceEntry[],
+) {
+ const { targets } = useSettingsScope();
+ const { environments } = useEnvironments();
+ return useCallback(
+ (instanceId: ProviderInstanceId, model: string): string | null => {
+ const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
+ for (const candidate of targets) {
+ const environment = environments.find(
+ (entry) => entry.environmentId === candidate.environmentId,
+ );
+ const config = environment?.serverConfig;
+ if (!config) continue;
+ const entry = applyProviderInstanceSettings(
+ deriveProviderInstanceEntries(config.providers),
+ candidate.settings,
+ ).find((option) => option.instanceId === instanceId);
+ const options = getCustomModelOptionsByInstance(
+ { ...settings, ...candidate.settings },
+ config.providers,
+ ).get(instanceId);
+ if (
+ !entry?.enabled ||
+ !entry.isAvailable ||
+ entry.driverKind !== sourceEntry?.driverKind ||
+ !options?.some((option) => option.slug === model && !option.isUnavailable)
+ ) {
+ return `This model is unavailable on ${environment?.label ?? "a selected environment"}. Select that environment to choose its model separately.`;
+ }
+ }
+ return null;
+ },
+ [entries, environments, settings, targets],
+ );
+}
diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.ts
new file mode 100644
index 00000000000..ddf6b60b9aa
--- /dev/null
+++ b/apps/web/src/components/settings/useScopedSettings.ts
@@ -0,0 +1,121 @@
+import {
+ DEFAULT_SERVER_SETTINGS,
+ type ProjectScopedServerSettingKey,
+ type ServerSettings,
+ type UnifiedSettings,
+} from "@t3tools/contracts";
+import { useCallback, useMemo } from "react";
+
+import {
+ mergeEnvironmentSettings,
+ persistClientSettingsPatch,
+ useClientSettings,
+} from "../../hooks/useSettings";
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { toastManager } from "../ui/toast";
+import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
+import {
+ persistScopedSettingsPatch,
+ planProjectOverridesClear,
+ planScopedSettingsClear,
+ planScopedSettingsPatch,
+ scopedSettingsAreMixed,
+ scopedSettingsSource,
+ type ProjectOverrideEntry,
+ type ScopedSettingsPatch,
+} from "./scopedSettings";
+
+/** Effective settings for the representative target: project overrides applied on top of its environment. */
+export function useScopedSettings<T = UnifiedSettings>(
+ selector?: (settings: UnifiedSettings) => T,
+): T {
+ const { target } = useSettingsScope();
+ const clientSettings = useClientSettings();
+ const serverSettings = target?.settings ?? DEFAULT_SERVER_SETTINGS;
+ const settings = useMemo(
+ () => mergeEnvironmentSettings(serverSettings, clientSettings),
+ [clientSettings, serverSettings],
+ );
+ return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
+}
+
+export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
+ const { targets } = useSettingsScope();
+ return scopedSettingsAreMixed(targets, keys);
+}
+
+/** Where the keys' effective values come from across the selected targets. */
+export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
+ const { targets } = useSettingsScope();
+ return scopedSettingsSource(targets, keys);
+}
+
+function useRunScopedPlan() {
+ const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
+ return useCallback(
+ (plan: ReturnType<typeof planScopedSettingsPatch>) => {
+ if (plan.unavailableReason) {
+ toastManager.add({
+ type: "warning",
+ title: "Setting not saved",
+ description: plan.unavailableReason,
+ });
+ return;
+ }
+ void persistScopedSettingsPatch(plan, persistServer, persistClientSettingsPatch).then(
+ ({ failedEnvironments, savedEnvironmentCount }) => {
+ if (failedEnvironments.length === 0) return;
+ toastManager.add({
+ type: "error",
+ title:
+ savedEnvironmentCount > 0
+ ? "Setting saved on some environments"
+ : "Setting not saved",
+ description: `Could not update ${failedEnvironments.map((environment) => environment.label).join(", ")}.${savedEnvironmentCount > 0 ? " The other selected environments saved the change." : ""}`,
+ });
+ },
+ );
+ },
+ [persistServer],
+ );
+}
+
+export function useUpdateScopedSettings() {
+ const { scope, environments } = useSettingsScope();
+ const run = useRunScopedPlan();
+ return useCallback(
+ (patch: ScopedSettingsPatch) => run(planScopedSettingsPatch(scope, environments, patch)),
+ [environments, run, scope],
+ );
+}
+
+/**
+ * Drop the project overrides for `keys` so the selected checkouts inherit
+ * again. Rows also render outside the settings layout (provider cards,
+ * dialogs), where there is no scope and nothing to clear.
+ */
+export function useClearScopedSettings() {
+ const context = useOptionalSettingsScope();
+ const run = useRunScopedPlan();
+ return useCallback(
+ (keys: readonly ProjectScopedServerSettingKey[]) => {
+ if (context === null) return;
+ run(planScopedSettingsClear(context.scope, context.environments, keys));
+ },
+ [context, run],
+ );
+}
+
+/** Clear `keys` on specific project entries, from an environment scope's chain popover. */
+export function useClearProjectOverrides() {
+ const context = useOptionalSettingsScope();
+ const run = useRunScopedPlan();
+ return useCallback(
+ (entries: readonly ProjectOverrideEntry[], keys: readonly ProjectScopedServerSettingKey[]) => {
+ if (context === null) return;
+ run(planProjectOverridesClear(context.environments, entries, keys));
+ },
+ [context, run],
+ );
+}
diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx
index 4657a0b9a97..b2bbf6aeccb 100644
--- a/apps/web/src/components/ui/button.tsx
+++ b/apps/web/src/components/ui/button.tsx
@@ -33,6 +33,8 @@ const buttonVariants = cva(
micro:
"h-5 gap-1 rounded-sm px-[calc(--spacing(1.5)-1px)] text-[11px] before:rounded-[calc(var(--radius-sm)-1px)] sm:text-[11px] [&_svg:not([class*='size-'])]:size-3 sm:[&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:h-7",
+ "sm-multiline":
+ "min-h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] py-[calc(--spacing(1)-1px)] whitespace-normal sm:min-h-7",
xl: "h-11 px-[calc(--spacing(4)-1px)] text-lg sm:h-10 sm:text-base [&_svg:not([class*='size-'])]:size-5 sm:[&_svg:not([class*='size-'])]:size-4.5",
xs: "h-7 gap-1 px-[calc(--spacing(2)-1px)] text-sm sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5",
},
diff --git a/apps/web/src/components/ui/switch.tsx b/apps/web/src/components/ui/switch.tsx
index 267b314caa4..33114c5512b 100644
--- a/apps/web/src/components/ui/switch.tsx
+++ b/apps/web/src/components/ui/switch.tsx
@@ -4,15 +4,21 @@ import { Switch as SwitchPrimitive } from "@base-ui/react/switch";
import { cn } from "~/lib/utils";
+/**
+ * `mixed` renders the thumb centred on a muted track for a selection whose
+ * targets disagree (the macOS mixed-state convention). It is presentational:
+ * the caller still decides what a click sets, usually on for everyone.
+ */
function Switch({
className,
size = "default",
+ mixed = false,
...props
-}: SwitchPrimitive.Root.Props & { size?: "default" | "sm" }) {
+}: SwitchPrimitive.Root.Props & { size?: "default" | "sm"; mixed?: boolean }) {
return (
<SwitchPrimitive.Root
className={cn(
- "inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 cursor-pointer items-center rounded-full p-[2px] outline-none transition-[background-color,box-shadow] duration-200 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-checked:bg-primary data-unchecked:bg-input data-disabled:cursor-not-allowed data-disabled:opacity-64",
+ "inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 cursor-pointer items-center rounded-full p-[2px] outline-none transition-[background-color,box-shadow] duration-200 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-checked:bg-primary data-unchecked:bg-input data-disabled:cursor-not-allowed data-disabled:opacity-64 data-[mixed]:bg-input",
size === "sm"
? "[--thumb-size:--spacing(4)] sm:[--thumb-size:--spacing(3.5)]"
: "[--thumb-size:--spacing(5)] sm:[--thumb-size:--spacing(4)]",
@@ -20,11 +26,15 @@ function Switch({
)}
data-size={size}
data-slot="switch"
+ data-mixed={mixed ? "" : undefined}
+ aria-checked={mixed ? "mixed" : undefined}
{...props}
>
<SwitchPrimitive.Thumb
className={cn(
"pointer-events-none block size-[calc(var(--thumb-size)-2px)] shrink-0 origin-left in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:scale-x-110 in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] rounded-(--thumb-size) bg-background shadow-sm/5 will-change-transform [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] data-checked:origin-right data-checked:translate-x-[calc(var(--thumb-size)-4px)]",
+ mixed &&
+ "translate-x-[calc((var(--thumb-size)-4px)/2)] opacity-70 data-checked:translate-x-[calc((var(--thumb-size)-4px)/2)]",
)}
data-slot="switch-thumb"
/>
diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts
index afd503e63c2..84d59f05a83 100644
--- a/apps/web/src/hooks/useHandleNewThread.test.ts
+++ b/apps/web/src/hooks/useHandleNewThread.test.ts
@@ -3,6 +3,11 @@ import { describe, expect, it, vi } from "vite-plus/test";
const testState = vi.hoisted(() => {
let completeProjectFileRead: (value: null) => void = () => undefined;
let projectFileRead = Promise.resolve<null>(null);
+ let targetSettings = {
+ defaultThreadEnvMode: "local" as "local" | "worktree",
+ newWorktreesStartFromOrigin: false,
+ defaultModelSelection: null,
+ };
let storedDraft: {
readonly draftId: string;
readonly environmentId: string;
@@ -35,10 +40,25 @@ const testState = vi.hoisted(() => {
get projectFileRead() {
return projectFileRead;
},
- reset(nextStoredDraft: typeof storedDraft) {
+ get targetSettings() {
+ return targetSettings;
+ },
+ reset(
+ nextStoredDraft: typeof storedDraft,
+ workspaceDefaults = {
+ envMode: "local" as "local" | "worktree",
+ startFromOrigin: false,
+ },
+ ) {
storedDraft = nextStoredDraft;
+ targetSettings = {
+ defaultThreadEnvMode: workspaceDefaults.envMode,
+ newWorktreesStartFromOrigin: workspaceDefaults.startFromOrigin,
+ defaultModelSelection: null,
+ };
router.state.location.href = "/";
router.navigate.mockClear();
+ draftStore.setDraftThreadContext.mockClear();
draftStore.setLogicalProjectDraftThreadId.mockClear();
projectFileRead = new Promise<null>((resolve) => {
completeProjectFileRead = resolve;
@@ -51,18 +71,18 @@ const testState = vi.hoisted(() => {
vi.mock("@effect/atom-react", () => ({
useAtomValue: (atom: unknown) =>
atom === "primary-settings"
- ? { newWorktreesStartFromOrigin: false }
+ ? { newWorktreesStartFromOrigin: !testState.targetSettings.newWorktreesStartFromOrigin }
: new Map([
[
- "environment-ssh",
+ "environment-primary",
{
settings: {
- defaultThreadEnvMode: "local",
- newWorktreesStartFromOrigin: false,
- defaultModelSelection: null,
+ ...testState.targetSettings,
+ newWorktreesStartFromOrigin: !testState.targetSettings.newWorktreesStartFromOrigin,
},
},
],
+ ["environment-ssh", { settings: testState.targetSettings }],
]),
}));
vi.mock("@t3tools/client-runtime/environment", () => ({
@@ -74,6 +94,15 @@ vi.mock("@t3tools/contracts", () => ({
DEFAULT_RUNTIME_MODE: "default",
DEFAULT_SERVER_SETTINGS: {},
}));
+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,
+ sources: { defaultModelSelection: "environment", defaultThreadEnvMode: "environment" },
+ overrides: {},
+ }),
+}));
vi.mock("@t3tools/shared/threadEnvMode", () => ({
resolveDefaultThreadEnvMode: (input: {
readonly projectFile: "local" | "worktree" | null;
@@ -99,9 +128,9 @@ vi.mock("../composerDraftStore", () => {
useComposerDraftStore,
};
});
-vi.mock("../lib/chatThreadActions", () => ({
+vi.mock("../lib/chatThreadActions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../lib/chatThreadActions")>()),
hasExplicitComposerModelSelection: () => false,
- resolveNewDraftStartFromOrigin: () => false,
resolveNewThreadModelSelectionOverride: () => null,
}));
vi.mock("../lib/t3ProjectFileDefaults", () => ({
@@ -143,19 +172,19 @@ vi.mock("./useSettings", () => ({ useClientSettings: () => ({}) }));
import { useNewThreadHandler } from "./useHandleNewThread";
-describe("useNewThreadHandler", () => {
- it.each([
- ["new", null],
- [
- "reusable",
- {
- draftId: "draft-existing",
- environmentId: "environment-ssh",
- promotedTo: null,
- threadId: "thread-existing",
- },
- ],
- ])("abandons a delayed %s draft open when the user navigates elsewhere", async (_, draft) => {
+describe.each([
+ ["new", null],
+ [
+ "reusable",
+ {
+ draftId: "draft-existing",
+ environmentId: "environment-ssh",
+ promotedTo: null,
+ threadId: "thread-existing",
+ },
+ ],
+])("useNewThreadHandler with a %s draft", (_, draft) => {
+ it("abandons a delayed draft open when the user navigates elsewhere", async () => {
testState.reset(draft);
const openThread = useNewThreadHandler();
const pendingOpen = openThread(
@@ -171,4 +200,58 @@ describe("useNewThreadHandler", () => {
expect(testState.router.navigate).not.toHaveBeenCalled();
expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled();
});
+
+ it.each([true, false])(
+ "uses the target environment's start-from-origin default of %s",
+ async (startFromOrigin) => {
+ testState.reset(draft, { envMode: "worktree", startFromOrigin });
+ const openThread = useNewThreadHandler();
+ const projectRef = {
+ environmentId: "environment-ssh",
+ projectId: "project-remote",
+ } as never;
+ const pendingOpen = openThread(projectRef);
+
+ testState.completeProjectFileRead(null);
+ const opened = await pendingOpen;
+
+ expect(opened).toEqual({
+ draftId: draft?.draftId ?? "draft-delayed",
+ threadId: draft?.threadId ?? "thread-delayed",
+ });
+ expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
+ "remote-project",
+ projectRef,
+ opened!.draftId,
+ expect.objectContaining({ envMode: "worktree", startFromOrigin }),
+ );
+ if (draft) {
+ expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(
+ draft.draftId,
+ expect.objectContaining({ envMode: "worktree", startFromOrigin }),
+ );
+ }
+ },
+ );
+
+ it.each([true, false])(
+ "preserves an explicit start-from-origin choice of %s",
+ async (startFromOrigin) => {
+ testState.reset(draft, { envMode: "worktree", startFromOrigin: !startFromOrigin });
+ const openThread = useNewThreadHandler();
+ const projectRef = {
+ environmentId: "environment-ssh",
+ projectId: "project-remote",
+ } as never;
+
+ const opened = await openThread(projectRef, { envMode: "worktree", startFromOrigin });
+
+ expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
+ "remote-project",
+ projectRef,
+ opened!.draftId,
+ expect.objectContaining({ envMode: "worktree", startFromOrigin }),
+ );
+ },
+ );
});
diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts
index 9b2afb3a61f..c72bef07996 100644
--- a/apps/web/src/hooks/useHandleNewThread.ts
+++ b/apps/web/src/hooks/useHandleNewThread.ts
@@ -27,6 +27,7 @@ import {
getProjectOrderKey,
selectProjectGroupingSettings,
} from "../logicalProject";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode";
import { readProjects, readThreadShell, useProjects, useThread } from "../state/entities";
import {
@@ -35,7 +36,7 @@ import {
resolveNewThreadModelSelectionOverride,
} from "../lib/chatThreadActions";
import { readT3ProjectFileDefaultThreadEnvMode } from "../lib/t3ProjectFileDefaults";
-import { environmentServerConfigsAtom, primaryServerSettingsAtom } from "../state/server";
+import { environmentServerConfigsAtom } from "../state/server";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import { useClientSettings } from "./useSettings";
@@ -61,7 +62,6 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef
export function useNewThreadHandler() {
const environmentServerConfigs = useAtomValue(environmentServerConfigsAtom);
- const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const router = useRouter();
const getCurrentRouteTarget = useCallback(() => {
@@ -139,10 +139,21 @@ export function useNewThreadHandler() {
candidate.id === projectRef.projectId &&
candidate.environmentId === projectRef.environmentId,
);
+ // The resolver applies project overrides and, until the server has
+ // folded them, the aggregate's own legacy fields.
+ const projectSettings = resolveProjectSettings(
+ targetServerSettings,
+ project?.id ?? null,
+ project,
+ );
+ const projectDefaultModelSelection = projectSettings.settings.defaultModelSelection;
+ const projectThreadEnvMode =
+ projectSettings.sources.defaultThreadEnvMode === "project"
+ ? projectSettings.settings.defaultThreadEnvMode
+ : undefined;
const resolveModelSelectionOverride = (destinationDraftId: DraftId) =>
resolveNewThreadModelSelectionOverride({
- projectDefaultSelection:
- project?.defaultModelSelection ?? targetServerSettings.defaultModelSelection ?? null,
+ projectDefaultSelection: projectDefaultModelSelection ?? null,
carrySelection: carryModelSelection,
carrySourceDraftId:
currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null,
@@ -152,16 +163,16 @@ 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 && project.defaultThreadEnvMode == null;
+ const consultProjectFile = project !== undefined && projectThreadEnvMode == null;
return resolveDefaultThreadEnvMode({
- projectSetting: project?.defaultThreadEnvMode,
+ projectSetting: projectThreadEnvMode,
projectFile: consultProjectFile
? await readT3ProjectFileDefaultThreadEnvMode(
project.environmentId,
project.workspaceRoot,
)
: null,
- globalDefault: targetServerSettings.defaultThreadEnvMode,
+ globalDefault: projectSettings.settings.defaultThreadEnvMode,
});
};
const logicalProjectKey = project
@@ -258,7 +269,7 @@ export function useNewThreadHandler() {
envMode: defaultEnvMode,
startFromOrigin: resolveNewDraftStartFromOrigin({
envMode: defaultEnvMode,
- newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
+ newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin,
}),
};
}
@@ -413,7 +424,7 @@ export function useNewThreadHandler() {
options?.startFromOrigin ??
resolveNewDraftStartFromOrigin({
envMode: initialEnvMode,
- newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
+ newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin,
}),
runtimeMode: carryRuntimeMode ?? DEFAULT_RUNTIME_MODE,
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
@@ -433,13 +444,7 @@ export function useNewThreadHandler() {
return { draftId, threadId };
})();
},
- [
- environmentServerConfigs,
- getCurrentRouteTarget,
- primaryServerSettings.newWorktreesStartFromOrigin,
- projectGroupingSettings,
- router,
- ],
+ [environmentServerConfigs, getCurrentRouteTarget, projectGroupingSettings, router],
);
}
diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts
index 2df74d6a5da..194cc36c55f 100644
--- a/apps/web/src/hooks/useSettings.ts
+++ b/apps/web/src/hooks/useSettings.ts
@@ -27,8 +27,6 @@ import {
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import {
filterSharedServerPatch,
- findSharedSettingsMismatches,
- pickSharedServerSettings,
splitSharedServerPatch,
supportsSharedSettingsSync,
} from "@t3tools/client-runtime/state/shared-settings";
@@ -493,73 +491,6 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
return updateSettings;
}
-/**
- * Shared-settings sync targets whose values differ from the primary's,
- * plus an action that writes the primary's values to all of them. Drift
- * happens when an environment was offline during an edit or was changed by
- * an older client.
- */
-export function useSharedSettingsSync() {
- const primaryEnvironment = usePrimaryEnvironment();
- const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
- const primaryCapabilities = primaryEnvironment?.serverConfig?.environment.capabilities;
- // Read the loaded config, not `primaryServerSettingsAtom`: that atom falls
- // back to defaults while the primary is disconnected, and "apply to all"
- // must never push defaults over real values. Same for a primary too old to
- // hold the shared keys: its decoded defaults are not a source of truth.
- const primarySettings =
- primaryEnvironment !== null && supportsSharedSettingsSync(primaryEnvironment)
- ? (primaryEnvironment.serverConfig?.settings ?? null)
- : null;
- const { environments } = useEnvironments();
- const persistServerSettings = useAtomCommand(
- serverEnvironment.updateSettings,
- "server settings update",
- );
-
- const mismatches = useMemo(
- () =>
- findSharedSettingsMismatches({
- primaryEnvironmentId,
- primarySettings,
- primaryCapabilities,
- environments: environments.map((environment) => ({
- environmentId: environment.environmentId,
- label: environment.label,
- syncEligible: supportsSharedSettingsSync(environment),
- settings: environment.serverConfig?.settings ?? null,
- capabilities: environment.serverConfig?.environment.capabilities,
- })),
- }),
- [environments, primaryEnvironmentId, primarySettings, primaryCapabilities],
- );
-
- const applyToAll = useCallback(() => {
- if (primarySettings === null) {
- return;
- }
- const patch = pickSharedServerSettings(primarySettings, primaryCapabilities);
- for (const mismatch of mismatches) {
- const target = environments.find(
- (candidate) => candidate.environmentId === mismatch.environmentId,
- );
- void persistServerSettings({
- environmentId: mismatch.environmentId,
- input: {
- patch: filterSharedServerPatch(
- patch,
- target?.serverConfig?.environment.capabilities,
- target?.serverConfig?.settings,
- primarySettings,
- ),
- },
- });
- }
- }, [environments, mismatches, persistServerSettings, primarySettings, primaryCapabilities]);
-
- return { mismatches, applyToAll };
-}
-
export function useUpdateEnvironmentSettings(environmentId: EnvironmentId) {
return useUpdateSettingsTarget(environmentId);
}
diff --git a/apps/web/src/lib/resourceTelemetryState.ts b/apps/web/src/lib/resourceTelemetryState.ts
index 47ca79898df..4b97b3b4671 100644
--- a/apps/web/src/lib/resourceTelemetryState.ts
+++ b/apps/web/src/lib/resourceTelemetryState.ts
@@ -1,4 +1,8 @@
-import type { ResourceTelemetryHistoryInput, ResourceTelemetrySnapshot } from "@t3tools/contracts";
+import type {
+ EnvironmentId,
+ ResourceTelemetryHistoryInput,
+ ResourceTelemetrySnapshot,
+} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { useCallback } from "react";
@@ -15,9 +19,14 @@ export interface ResourceTelemetryState {
readonly retry: () => Promise<ResourceTelemetrySnapshot>;
}
-export function useResourceTelemetry(): ResourceTelemetryState {
+export function useResourceTelemetry(
+ targetEnvironmentId?: EnvironmentId | null,
+): ResourceTelemetryState {
const primaryEnvironment = usePrimaryEnvironment();
- const environmentId = primaryEnvironment?.environmentId ?? null;
+ const environmentId =
+ targetEnvironmentId === undefined
+ ? (primaryEnvironment?.environmentId ?? null)
+ : targetEnvironmentId;
const query = useEnvironmentQuery(
environmentId === null
? null
@@ -40,9 +49,15 @@ export function useResourceTelemetry(): ResourceTelemetryState {
return { ...query, retry };
}
-export function useResourceTelemetryHistory(input: ResourceTelemetryHistoryInput) {
+export function useResourceTelemetryHistory(
+ input: ResourceTelemetryHistoryInput,
+ targetEnvironmentId?: EnvironmentId | null,
+) {
const primaryEnvironment = usePrimaryEnvironment();
- const environmentId = primaryEnvironment?.environmentId ?? null;
+ const environmentId =
+ targetEnvironmentId === undefined
+ ? (primaryEnvironment?.environmentId ?? null)
+ : targetEnvironmentId;
return useEnvironmentQuery(
environmentId === null
? null
diff --git a/apps/web/src/routes/settings.integrations.tsx b/apps/web/src/routes/settings.integrations.tsx
index 3fa49ae93f2..641a3036c6f 100644
--- a/apps/web/src/routes/settings.integrations.tsx
+++ b/apps/web/src/routes/settings.integrations.tsx
@@ -2,10 +2,6 @@ import { createFileRoute } from "@tanstack/react-router";
import { IntegrationsSettingsPanel } from "../components/settings/IntegrationsSettings";
-function SettingsIntegrationsRoute() {
- return <IntegrationsSettingsPanel />;
-}
-
export const Route = createFileRoute("/settings/integrations")({
- component: SettingsIntegrationsRoute,
+ component: IntegrationsSettingsPanel,
});
diff --git a/apps/web/src/routes/settings.projects.tsx b/apps/web/src/routes/settings.projects.tsx
index 36b20d1560f..12190b4213f 100644
--- a/apps/web/src/routes/settings.projects.tsx
+++ b/apps/web/src/routes/settings.projects.tsx
@@ -1,24 +1,6 @@
import { createFileRoute } from "@tanstack/react-router";
import { ProjectsSettings } from "../components/settings/ProjectsSettings";
-import { validateSettingsScopeSearch } from "../components/settings/settingsScope";
export const Route = createFileRoute("/settings/projects")({
- validateSearch: validateSettingsScopeSearch,
- component: ProjectsRoute,
+ component: ProjectsSettings,
});
-
-function ProjectsRoute() {
- const search = Route.useSearch();
- const navigate = Route.useNavigate();
- return (
- <ProjectsSettings
- value={search}
- onScopeChange={(scope) => {
- void navigate({
- search: scope,
- replace: true,
- });
- }}
- />
- );
-}
diff --git a/apps/web/src/routes/settings.providers.tsx b/apps/web/src/routes/settings.providers.tsx
index bb85b8bb6ff..54eb77ea093 100644
--- a/apps/web/src/routes/settings.providers.tsx
+++ b/apps/web/src/routes/settings.providers.tsx
@@ -2,10 +2,32 @@ import { createFileRoute } from "@tanstack/react-router";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { ProviderSettingsPanel } from "../components/settings/ProviderSettingsPanel";
+import { useSettingsScope } from "../components/settings/SettingsScopeContext";
+/**
+ * Providers are machine state, so the page shows one environment at a time:
+ * the chosen one, or the representative of the selection. A project crumb
+ * narrows the candidates to the environments that project is registered on.
+ */
function SettingsProvidersRoute() {
const target = Route.useSearch();
- return <ProviderSettingsPanel {...target} />;
+ const { environment, scope } = useSettingsScope();
+ if (!environment) {
+ return (
+ <p className="p-8 text-sm text-muted-foreground">
+ {scope.kind === "environment"
+ ? `Reconnect ${scope.label} to set up its providers.`
+ : "Connect an environment to set up its providers."}
+ </p>
+ );
+ }
+ return (
+ <ProviderSettingsPanel
+ environmentId={environment.environmentId}
+ {...(target.instanceId ? { instanceId: target.instanceId } : {})}
+ scoped
+ />
+ );
}
export const Route = createFileRoute("/settings/providers")({
diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx
index 5e921fca5c2..cd6ca454649 100644
--- a/apps/web/src/routes/settings.tsx
+++ b/apps/web/src/routes/settings.tsx
@@ -1,4 +1,3 @@
-import { RotateCcwIcon } from "lucide-react";
import {
Outlet,
createFileRoute,
@@ -7,18 +6,34 @@ import {
useLocation,
useNavigate,
} from "@tanstack/react-router";
-import { useCallback, useEffect, useState } from "react";
-
+import { useCallback, useEffect, useState, type ReactNode } from "react";
+import { RotateCcwIcon } from "lucide-react";
+import { Button } from "../components/ui/button";
import { useSettingsRestore } from "../components/settings/SettingsPanels";
+
import { SettingsBreadcrumb } from "../components/settings/SettingsBreadcrumb";
-import { Button } from "../components/ui/button";
import { SidebarInset } from "../components/ui/sidebar";
import { WorkspacePageHeader } from "../components/WorkspacePageHeader";
import { isElectron } from "../env";
+import {
+ SettingsScopeProvider,
+ useSettingsScope,
+} from "../components/settings/SettingsScopeContext";
+import { useSettingsProjectGroups } from "../components/settings/useSettingsProjectGroups";
+import { useEnvironments } from "../state/environments";
+import { SettingsScopeNotice } from "../components/settings/SettingsScopeNotice";
+import {
+ retainSettingsScope,
+ validateSettingsRouteSearch,
+} from "../components/settings/settingsScopeNavigation";
+import {
+ getSettingsSearchTargetScope,
+ getThreadAutoSettlementSearchAvailability,
+ isSettingsSearchScopeAvailable,
+} from "../components/settings/settingsSearch";
-function RestoreDefaultsButton({ onRestored }: { onRestored: () => void }) {
+function RestoreDeviceDefaultsButton({ onRestored }: { onRestored: () => void }) {
const { changedSettingLabels, restoreDefaults } = useSettingsRestore(onRestored);
-
return (
<Button
size="xs"
@@ -27,18 +42,87 @@ function RestoreDefaultsButton({ onRestored }: { onRestored: () => void }) {
onClick={() => void restoreDefaults()}
>
<RotateCcwIcon className="mx-1 size-3.5" />
- Restore defaults
+ Restore device defaults
</Button>
);
}
+/** Pages whose every row is saved on this client; the scope selects are hidden there. */
+const DEVICE_ONLY_PATHS = new Set([
+ "/settings/appearance",
+ "/settings/snap-shot",
+ "/settings/connections",
+]);
+
+function SettingsScopeBoundary({ pathname, children }: { pathname: string; children: ReactNode }) {
+ const { scope, connectedEnvironments } = useSettingsScope();
+ const { environments } = useEnvironments();
+ const hash = useLocation({ select: (location) => location.hash });
+ const searchTarget = getSettingsSearchTargetScope(hash);
+ const autoSettlementAvailability = searchTarget?.requiresThreadAutoSettlement
+ ? getThreadAutoSettlementSearchAvailability(environments, scope)
+ : null;
+ if (
+ scope.kind !== "unavailable" &&
+ searchTarget &&
+ autoSettlementAvailability &&
+ !autoSettlementAvailability.isTargetAvailable
+ ) {
+ return (
+ <SettingsScopeNotice
+ target="environment"
+ targetId={hash}
+ eligibleEnvironmentIds={autoSettlementAvailability.eligibleEnvironmentIds}
+ >
+ {autoSettlementAvailability.eligibleEnvironmentIds.length > 0
+ ? `${searchTarget.title} requires a supporting environment. Choose one to continue.`
+ : `${searchTarget.title} requires a supporting environment. Connect or update an environment to continue.`}
+ </SettingsScopeNotice>
+ );
+ }
+ if (
+ scope.kind !== "unavailable" &&
+ searchTarget &&
+ !isSettingsSearchScopeAvailable(searchTarget.scope, scope.kind)
+ ) {
+ const target =
+ searchTarget.scope === "environment" ||
+ searchTarget.scope === "project" ||
+ searchTarget.scope === "checkout"
+ ? searchTarget.scope
+ : "all";
+ return (
+ <SettingsScopeNotice target={target} targetId={hash}>
+ {`${searchTarget.title} is not available for the selected target. Choose its owning scope to continue.`}
+ </SettingsScopeNotice>
+ );
+ }
+ // Device-local pages ignore the scope entirely; the project page follows
+ // remembered members while a grouping change replaces its URL key.
+ if (DEVICE_ONLY_PATHS.has(pathname) || pathname === "/settings/projects") {
+ return children;
+ }
+ if (scope.kind === "unavailable")
+ return <p className="p-8 text-sm text-muted-foreground">{scope.message}</p>;
+ if (scope.kind === "environment" && connectedEnvironments.length === 0) {
+ return (
+ <p className="p-8 text-sm text-muted-foreground">
+ Reconnect {scope.label} to change its settings.
+ </p>
+ );
+ }
+ return children;
+}
+
function SettingsContentLayout() {
const location = useLocation();
const navigate = useNavigate();
const canGoBack = useCanGoBack();
+ const { search, selectScope } = useSettingsScope();
+ const groups = useSettingsProjectGroups();
+ const { environments } = useEnvironments();
const [restoreSignal, setRestoreSignal] = useState(0);
- const showRestoreDefaults = location.pathname === "/settings/general";
- const handleRestored = () => setRestoreSignal((value) => value + 1);
+ const showScope = !DEVICE_ONLY_PATHS.has(location.pathname);
const navigateBackWithinApp = useCallback(() => {
if (canGoBack) {
window.history.back();
@@ -73,17 +157,31 @@ function SettingsContentLayout() {
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
<WorkspacePageHeader electron={isElectron}>
<div className="flex w-full items-center gap-3">
- <SettingsBreadcrumb pathname={location.pathname} />
- {showRestoreDefaults ? (
- <div className="ms-auto flex items-center gap-2">
- <RestoreDefaultsButton onRestored={handleRestored} />
+ <SettingsBreadcrumb
+ pathname={location.pathname}
+ scope={
+ showScope
+ ? { value: search, groups, environments, onChange: selectScope }
+ : undefined
+ }
+ />
+ {location.pathname === "/settings/general" ? (
+ <div className="ms-auto flex shrink-0 items-center">
+ <RestoreDeviceDefaultsButton
+ onRestored={() => setRestoreSignal((value) => value + 1)}
+ />
</div>
) : null}
</div>
</WorkspacePageHeader>
- <div key={restoreSignal} className="min-h-0 flex flex-1 flex-col">
- <Outlet />
+ <div
+ key={`${JSON.stringify(search)}:${restoreSignal}`}
+ className="min-h-0 flex flex-1 flex-col"
+ >
+ <SettingsScopeBoundary pathname={location.pathname}>
+ <Outlet />
+ </SettingsScopeBoundary>
</div>
</div>
</SidebarInset>
@@ -91,10 +189,35 @@ function SettingsContentLayout() {
}
function SettingsRouteLayout() {
- return <SettingsContentLayout />;
+ const rawSearch = Route.useSearch();
+ const navigate = Route.useNavigate();
+ const pathname = useLocation({ select: (location) => location.pathname });
+ return (
+ <SettingsScopeProvider
+ search={rawSearch}
+ onChange={(next) => {
+ // Send every axis so the retain middleware sees an explicit target
+ // even when the choice is "all", which is the absence of a key.
+ void navigate({
+ to: pathname,
+ search: () => ({
+ project: next.project,
+ machine: next.machine,
+ checkout: next.checkout,
+ }),
+ hash: "",
+ resetScroll: false,
+ });
+ }}
+ >
+ <SettingsContentLayout />
+ </SettingsScopeProvider>
+ );
}
export const Route = createFileRoute("/settings")({
+ validateSearch: validateSettingsRouteSearch,
+ search: { middlewares: [retainSettingsScope] },
beforeLoad: async ({ context, location }) => {
if (
context.authGateState.status !== "authenticated" &&
diff --git a/apps/web/src/state/server.ts b/apps/web/src/state/server.ts
index f13965e5b4d..11fd2e7dc0f 100644
--- a/apps/web/src/state/server.ts
+++ b/apps/web/src/state/server.ts
@@ -100,10 +100,6 @@ export const primaryServerAvailableEditorsAtom = Atom.make(
get(primaryServerConfigAtom)?.availableEditors ?? EMPTY_AVAILABLE_EDITORS,
).pipe(Atom.withLabel("web-primary-server-available-editors"));
-export const primaryServerKeybindingsConfigPathAtom = Atom.make(
- (get): string | null => get(primaryServerConfigAtom)?.keybindingsConfigPath ?? null,
-).pipe(Atom.withLabel("web-primary-server-keybindings-config-path"));
-
const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray<EnvironmentTheme> = [];
/**
@@ -115,8 +111,3 @@ export const primaryServerEnvironmentThemesAtom = Atom.make(
(get): ReadonlyArray<EnvironmentTheme> =>
get(primaryServerConfigAtom)?.environmentThemes ?? EMPTY_ENVIRONMENT_THEMES,
).pipe(Atom.withLabel("web-primary-server-environment-themes"));
-
-export const primaryServerObservabilityAtom = Atom.make(
- (get): ServerConfig["observability"] | null =>
- get(primaryServerConfigAtom)?.observability ?? null,
-).pipe(Atom.withLabel("web-primary-server-observability"));
diff --git a/docs/internals/overview.md b/docs/internals/overview.md
index b348a0ac088..6ca41871679 100644
--- a/docs/internals/overview.md
+++ b/docs/internals/overview.md
@@ -41,6 +41,15 @@ Provider-specific behavior belongs behind an adapter. Orchestration works with n
and events, so adding a provider should not require branches throughout the domain or clients.
See [provider constraints](./providers.md).
+## Settings ownership
+
+Client preferences stay in the current client; environment defaults and project overrides stay
+on their owning server. The web and desktop settings target is URL state, resolved against current
+connections and project membership. An unavailable target must not fall back to another environment.
+**All environments** is an explicit bulk edit of connected, loaded servers, not a durable global
+default or a promise to synchronize offline or future environments. Project-group targets similarly
+select known environment-local checkouts; the group itself does not store inherited defaults.
+
## Durable intent and side effects
The event log is the source of truth for orchestration state. The
diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md
index c76c18544df..e4fae5a86c3 100644
--- a/docs/user/project-settings.md
+++ b/docs/user/project-settings.md
@@ -1,34 +1,56 @@
-# Project settings
+# Settings and project overrides
-Open **Settings → Projects**. The project and machine pickers start at **All projects** and
-**All machines**.
+The Settings breadcrumb ends with the environment and project a change applies to. They start
+at **All environments** and **All projects** and stay selected as you move between categories or
+search for a setting.
-Change the default model, workspace, automatic pull, agent browser access, or actions for projects that inherit those values.
-Select an individual project to override a default. Reset its row to inherit again. Changing a
-default preserves explicit project overrides. Workspace preferences in `t3.json` take precedence
-over machine defaults when the project has no explicit workspace override.
+Preferences saved on this device, such as appearance, confirmations and browser profiles, always
+show and ignore the selection. Everything else is stored on a server. Choose one environment to
+edit its settings, or leave **All environments** to edit every connected environment at once.
+Offline environments keep their current values; this is a bulk edit, not a synced global default.
-Select a machine to limit edits to it. **All machines** writes defaults to connected machines;
-offline machines keep their previous values. Mixed values are indicated when selected machines
-or checkouts disagree. Browser access changes apply when an agent session next starts.
+Choose a project to override settings for it on the selected environments. A layers icon beside
+each server row's title shows where the value comes from: the built-in default, the environment,
+or a project override. Click it to see that chain on every selected environment. An override can
+be reset to inherit again. Settings that cannot be overridden by a project are shown read-only
+while a project is selected.
-Project grouping has a client-wide default across machines, with individual checkout overrides.
-Shared actions apply to inheriting projects; editing a project's actions creates an independent list.
-Reset that list to use shared actions again. Existing project actions are preserved.
+When the selected environments disagree, the control shows **Mixed** in place of a value and the
+layers icon turns amber. Picking a value applies it to every selected environment.
-Project names, icons, removal, and importing actions from a checkout remain project-specific.
-When there are several checkouts, the checkout picker selects which actions and grouping to edit.
+Changing an environment value never touches a project's own override. When projects override the
+setting you are editing, the layers icon counts them and the chain lists each one with its value:
+click a project to jump to it, or **Reset all** to make those projects follow the environment
+again.
+
+Providers and diagnostics are per machine: they show one environment at a time, the primary
+one until you pick another. Every other setting fans out to the selection.
+
+## Defaults and inheritance
+
+General contains the model and workspace for new threads. Integrations controls agent browser
+access. Source Control contains automatic pull, the default pull request merge method and text
+generation. The same rows edit environment defaults or project overrides depending on the
+project crumb.
+
+The Project category, shown while a project is selected, holds the project's name, icon, actions,
+checkouts and removal. Actions belong to a project: editing them creates the project's own list
+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.
+Browser access changes apply when an agent session next starts.
## Project icons
-Choose an icon, emoji, or image from the project to make it easier to recognize. The choice applies
-to selected checkouts in the project group and appears on connected clients. Choose **Automatic** to
-let T3 Code detect an icon again.
+Select the project and open Project to choose an icon, emoji, or image. The choice applies to
+every checkout in the project group and appears on connected clients. Choose **Automatic** to let
+T3 Code detect an icon again.
## Keep the default branch current
-Enable **Automatically pull** to keep the default-branch checkout up to date with its configured
-upstream.
+In Source Control, enable **Automatically pull** to keep the default-branch checkout up to date
+with its configured upstream. Choose an environment to set the default or a project to override it.
T3 Code only pulls when it can fast-forward and the checkout has no changed files, untracked files,
or local commits. It skips checkouts on another branch or without an upstream. If a checkout has
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index 360057dd56a..a4d9efbf87a 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -86,10 +86,12 @@ settlement, but an old closed or merged pull request does not settle work you
resumed after it closed.
Change these rules in **Settings → General**. They continue to run when your apps
-are closed. Changes apply to connected environments that support shared settings;
-offline environments and older servers keep their previous values. If connected
-environments disagree, **Apply to all** copies your current settings to those named
-in the warning. Changing a rule does not reopen already settled threads.
+are closed. On web and desktop, choose an environment at the top to change only
+its rules, or **All environments** to update connected environments together.
+Mixed values show where the selected environments disagree. Mobile applies these
+rules to connected environments that support shared settings. Offline environments
+and older servers keep their previous values. Changing a rule does not reopen
+already settled threads.
## Link a pull request