Merge origin/main into codex-turn-mapping
Co-authored-by: codex <[email protected]>
This commit is contained in:
commit
ae3a25649a
31 files changed
+1009
-211
No files matched your search
@@ -18,6 +18,7 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
environmentIdentificationMode: "artwork",
|
||||
favorites: [],
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
|
||||
@@ -24,13 +24,7 @@ import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironment
|
||||
import { ConnectionStatusDot } from "./ConnectionStatusDot";
|
||||
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
|
||||
|
||||
/**
|
||||
* "T3 Connect" section: every environment published to the signed-in account,
|
||||
* with connect switches, availability status, refresh, and loading/error
|
||||
* states. Shared between the Settings environments screen and the T3 Connect
|
||||
* onboarding sheet.
|
||||
*/
|
||||
export function CloudEnvironmentRows(props: {
|
||||
interface CloudEnvironmentRowsProps {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
|
||||
@@ -41,8 +35,31 @@ export function CloudEnvironmentRows(props: {
|
||||
* pull-to-refresh).
|
||||
*/
|
||||
readonly showHeader?: boolean;
|
||||
}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* "T3 Connect" section: every environment published to the signed-in account,
|
||||
* with connect switches, availability status, refresh, and loading/error
|
||||
* states. Shared between the Settings environments screen and the T3 Connect
|
||||
* onboarding sheet.
|
||||
*/
|
||||
export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
// Showcase captures run without a Clerk publishable key, so `ClerkProvider`
|
||||
// is never mounted and any `useAuth` call throws — the fixture states whether
|
||||
// the rows are signed in instead of asking Clerk.
|
||||
if (props.showcaseSignedIn !== undefined) {
|
||||
return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
|
||||
}
|
||||
return <SignedInCloudEnvironmentRows {...props} />;
|
||||
}
|
||||
|
||||
function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
if (!isSignedIn) return null;
|
||||
return <CloudEnvironmentRowsContent {...props} />;
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments =
|
||||
@@ -67,8 +84,6 @@ export function CloudEnvironmentRows(props: {
|
||||
|
||||
const showHeader = props.showHeader ?? true;
|
||||
|
||||
if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
|
||||
{showHeader ? (
|
||||
|
||||
@@ -14,7 +14,7 @@ import { getLocalStorageItem } from "../hooks/useLocalStorage";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import { cn, isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { useSidebarV2Enabled } from "../hooks/useSettings";
|
||||
import { useEnvironmentIdentificationMode, useSidebarV2Enabled } from "../hooks/useSettings";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import ThreadSidebarV2 from "./SidebarV2";
|
||||
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
@@ -62,7 +62,10 @@ function SidebarControl() {
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const { toggleSidebar } = useSidebar();
|
||||
const isSidebarVisible = useSidebarVisibility();
|
||||
const stageBackdropVariant = useSidebarStageBackdropVariant();
|
||||
const environmentIdentificationMode = useEnvironmentIdentificationMode();
|
||||
const stageBackdropVariant = useSidebarStageBackdropVariant(
|
||||
environmentIdentificationMode === "artwork",
|
||||
);
|
||||
const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle");
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { StageBackdropArt, StageBackdropButtonArt } from "./SidebarStageBackdrop";
|
||||
import {
|
||||
resolveEnvironmentIdentificationPillLabel,
|
||||
resolveSidebarStageBackdropVariant,
|
||||
StageBackdropArt,
|
||||
StageBackdropButtonArt,
|
||||
} from "./SidebarStageBackdrop";
|
||||
|
||||
describe("SidebarStageBackdrop", () => {
|
||||
it("resolves stage artwork only when enabled", () => {
|
||||
expect(resolveSidebarStageBackdropVariant("Dev")).toBe("dev");
|
||||
expect(resolveSidebarStageBackdropVariant("Nightly")).toBe("nightly");
|
||||
expect(resolveSidebarStageBackdropVariant("Dev", false)).toBeNull();
|
||||
expect(resolveSidebarStageBackdropVariant("Alpha")).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves supported environment pill labels", () => {
|
||||
expect(resolveEnvironmentIdentificationPillLabel("Dev")).toBe("Dev");
|
||||
expect(resolveEnvironmentIdentificationPillLabel("nightly")).toBe("Nightly");
|
||||
expect(resolveEnvironmentIdentificationPillLabel("Latest")).toBeNull();
|
||||
expect(resolveEnvironmentIdentificationPillLabel("Alpha")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["nightly", "dev"] as const)(
|
||||
"uses unique SVG definition ids when %s artwork is rendered more than once",
|
||||
(variant) => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
||||
import { primaryServerConfigAtom } from "../state/server";
|
||||
|
||||
export type SidebarStageBackdropVariant = "nightly" | "dev";
|
||||
export type EnvironmentIdentificationPillLabel = "Dev" | "Nightly";
|
||||
|
||||
// A wide viewBox keeps the 96-unit art height at a fixed scale while sidebar resizing reveals
|
||||
// more horizontal canvas instead of zooming the scene.
|
||||
@@ -13,23 +14,36 @@ const STAGE_BACKDROP_VIEW_BOX = "0 0 8192 96";
|
||||
|
||||
export function resolveSidebarStageBackdropVariant(
|
||||
stageLabel: string,
|
||||
enabled = true,
|
||||
): SidebarStageBackdropVariant | null {
|
||||
if (!enabled) return null;
|
||||
const normalized = stageLabel.trim().toLowerCase();
|
||||
if (normalized === "nightly") return "nightly";
|
||||
if (normalized === "dev") return "dev";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useSidebarStageBackdropVariant(): SidebarStageBackdropVariant | null {
|
||||
export function resolveEnvironmentIdentificationPillLabel(
|
||||
stageLabel: string,
|
||||
): EnvironmentIdentificationPillLabel | null {
|
||||
const normalized = stageLabel.trim().toLowerCase();
|
||||
if (normalized === "dev") return "Dev";
|
||||
if (normalized === "nightly") return "Nightly";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useEnvironmentStageLabel(): string {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
return resolveSidebarStageBackdropVariant(
|
||||
resolveServerBackedAppStageLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
}),
|
||||
);
|
||||
return resolveServerBackedAppStageLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSidebarStageBackdropVariant(enabled = true): SidebarStageBackdropVariant | null {
|
||||
return resolveSidebarStageBackdropVariant(useEnvironmentStageLabel(), enabled);
|
||||
}
|
||||
|
||||
/** Stage-channel header art; palettes mirror the per-channel app icons in `assets/`. */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { memo, type PointerEventHandler } from "react";
|
||||
import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
|
||||
import { useEnvironmentIdentificationMode } from "~/hooks/useSettings";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
|
||||
import { Button } from "../ui/button";
|
||||
@@ -73,7 +74,10 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
const pointerFocusProps = preserveComposerFocusOnPointerDown
|
||||
? { onPointerDown: preventPointerFocus }
|
||||
: undefined;
|
||||
const stageBackdropVariant = useSidebarStageBackdropVariant();
|
||||
const environmentIdentificationMode = useEnvironmentIdentificationMode();
|
||||
const stageBackdropVariant = useSidebarStageBackdropVariant(
|
||||
environmentIdentificationMode === "artwork",
|
||||
);
|
||||
|
||||
if (pendingAction) {
|
||||
return (
|
||||
|
||||
@@ -22,7 +22,9 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE,
|
||||
DEFAULT_UNIFIED_SETTINGS,
|
||||
type EnvironmentIdentificationMode,
|
||||
MAX_GLASS_OPACITY,
|
||||
MIN_GLASS_OPACITY,
|
||||
} from "@t3tools/contracts/settings";
|
||||
@@ -41,6 +43,10 @@ import {
|
||||
} from "../../components/desktopUpdate.logic";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { TraitsPicker } from "../chat/TraitsPicker";
|
||||
import {
|
||||
resolveEnvironmentIdentificationPillLabel,
|
||||
useEnvironmentStageLabel,
|
||||
} from "../SidebarStageBackdrop";
|
||||
import { isElectron } from "../../env";
|
||||
import { buildHostedChannelSelectionUrl, type HostedAppChannel } from "../../hostedPairing";
|
||||
import { useTheme } from "../../hooks/useTheme";
|
||||
@@ -115,6 +121,12 @@ const THEME_OPTIONS = [
|
||||
},
|
||||
] as const;
|
||||
|
||||
const ENVIRONMENT_IDENTIFICATION_LABELS: Record<EnvironmentIdentificationMode, string> = {
|
||||
artwork: "Artwork",
|
||||
pill: "Version pill",
|
||||
none: "None",
|
||||
};
|
||||
|
||||
const TIMESTAMP_FORMAT_LABELS = {
|
||||
locale: "System default",
|
||||
"12-hour": "12-hour",
|
||||
@@ -403,6 +415,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
() => [
|
||||
...(theme !== "system" ? ["Theme"] : []),
|
||||
...(settings.glassOpacity !== DEFAULT_UNIFIED_SETTINGS.glassOpacity ? ["Glass opacity"] : []),
|
||||
...(settings.environmentIdentificationMode !==
|
||||
DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode
|
||||
? ["Environment identification"]
|
||||
: []),
|
||||
...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat
|
||||
? ["Time format"]
|
||||
: []),
|
||||
@@ -458,6 +474,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.newWorktreesStartFromOrigin,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.environmentIdentificationMode,
|
||||
settings.glassOpacity,
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.enableAssistantStreaming,
|
||||
@@ -485,6 +502,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
|
||||
environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode,
|
||||
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
|
||||
@@ -508,55 +526,23 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
};
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
export function AppearanceSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const lastEnabledProjectGroupingMode = useRef<SidebarProjectGroupingMode>(
|
||||
readLastEnabledProjectGroupingMode(),
|
||||
);
|
||||
const observability = useAtomValue(primaryServerObservabilityAtom);
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const environmentStageLabel = useEnvironmentStageLabel();
|
||||
const showEnvironmentIdentification =
|
||||
resolveEnvironmentIdentificationPillLabel(environmentStageLabel) !== null;
|
||||
const glassOpacityRatio =
|
||||
(settings.glassOpacity - MIN_GLASS_OPACITY) / (MAX_GLASS_OPACITY - MIN_GLASS_OPACITY);
|
||||
const glassOpacitySliderStyle = {
|
||||
"--glass-slider-progress": `${glassOpacityRatio * 100}%`,
|
||||
"--glass-slider-fill-offset": `${0.5 - glassOpacityRatio}rem`,
|
||||
} as CSSProperties;
|
||||
const diagnosticsDescription = formatDiagnosticsDescription({
|
||||
localTracingEnabled: observability?.localTracingEnabled ?? false,
|
||||
otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
|
||||
otlpTracesUrl: observability?.otlpTracesUrl,
|
||||
otlpMetricsEnabled: observability?.otlpMetricsEnabled ?? false,
|
||||
otlpMetricsUrl: observability?.otlpMetricsUrl,
|
||||
});
|
||||
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const textGenerationModelInstanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const textGenInstanceEntry = textGenerationModelInstanceEntries.find(
|
||||
(entry) => entry.instanceId === textGenInstanceId,
|
||||
);
|
||||
const textGenProvider: ProviderDriverKind =
|
||||
textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;
|
||||
const textGenerationModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
textGenInstanceId,
|
||||
textGenModel,
|
||||
);
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="General">
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow
|
||||
title="Theme"
|
||||
description="Choose how T3 Code looks across the app."
|
||||
@@ -636,6 +622,118 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
{showEnvironmentIdentification ? (
|
||||
<SettingsRow
|
||||
title="Environment identification"
|
||||
description="Choose how Dev and Nightly environments are identified."
|
||||
resetAction={
|
||||
settings.environmentIdentificationMode !== DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE ? (
|
||||
<SettingResetButton
|
||||
label="environment identification"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
environmentIdentificationMode: DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={settings.environmentIdentificationMode}
|
||||
onValueChange={(value) => {
|
||||
if (value === "artwork" || value === "pill" || value === "none") {
|
||||
updateSettings({ environmentIdentificationMode: value });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Environment identification">
|
||||
<SelectValue>
|
||||
{ENVIRONMENT_IDENTIFICATION_LABELS[settings.environmentIdentificationMode]}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{Object.entries(ENVIRONMENT_IDENTIFICATION_LABELS).map(([value, label]) => (
|
||||
<SelectItem hideIndicator key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<SettingsRow
|
||||
title="Word wrap"
|
||||
description="Wrap long lines in code blocks, tables, diffs, and file previews by default."
|
||||
resetAction={
|
||||
settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? (
|
||||
<SettingResetButton
|
||||
label="word wrapping"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.wordWrap}
|
||||
onCheckedChange={(checked) => updateSettings({ wordWrap: Boolean(checked) })}
|
||||
aria-label="Wrap code, tables, diffs, and file previews by default"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const lastEnabledProjectGroupingMode = useRef<SidebarProjectGroupingMode>(
|
||||
readLastEnabledProjectGroupingMode(),
|
||||
);
|
||||
const observability = useAtomValue(primaryServerObservabilityAtom);
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const diagnosticsDescription = formatDiagnosticsDescription({
|
||||
localTracingEnabled: observability?.localTracingEnabled ?? false,
|
||||
otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
|
||||
otlpTracesUrl: observability?.otlpTracesUrl,
|
||||
otlpMetricsEnabled: observability?.otlpMetricsEnabled ?? false,
|
||||
otlpMetricsUrl: observability?.otlpMetricsUrl,
|
||||
});
|
||||
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const textGenerationModelInstanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const textGenInstanceEntry = textGenerationModelInstanceEntries.find(
|
||||
(entry) => entry.instanceId === textGenInstanceId,
|
||||
);
|
||||
const textGenProvider: ProviderDriverKind =
|
||||
textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;
|
||||
const textGenerationModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
textGenInstanceId,
|
||||
textGenModel,
|
||||
);
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow
|
||||
title="Project Grouping"
|
||||
description="Combine matching repositories across environments."
|
||||
@@ -714,30 +812,6 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Word wrap"
|
||||
description="Wrap long lines in code blocks, tables, diffs, and file previews by default."
|
||||
resetAction={
|
||||
settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? (
|
||||
<SettingResetButton
|
||||
label="word wrapping"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.wordWrap}
|
||||
onCheckedChange={(checked) => updateSettings({ wordWrap: Boolean(checked) })}
|
||||
aria-label="Wrap code, tables, diffs, and file previews by default"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Hide whitespace changes"
|
||||
description="Set whether the diff panel ignores whitespace-only edits by default."
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
GitBranchIcon,
|
||||
KeyboardIcon,
|
||||
Link2Icon,
|
||||
PaletteIcon,
|
||||
Settings2Icon,
|
||||
} from "lucide-react";
|
||||
import { useCanGoBack, useNavigate } from "@tanstack/react-router";
|
||||
@@ -25,6 +26,7 @@ import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3Conne
|
||||
|
||||
export type SettingsSectionPath =
|
||||
| "/settings/general"
|
||||
| "/settings/appearance"
|
||||
| "/settings/keybindings"
|
||||
| "/settings/providers"
|
||||
| "/settings/scheduled-tasks"
|
||||
@@ -39,6 +41,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
icon: ComponentType<{ className?: string }>;
|
||||
}> = [
|
||||
{ label: "General", to: "/settings/general", icon: Settings2Icon },
|
||||
{ label: "Appearance", to: "/settings/appearance", icon: PaletteIcon },
|
||||
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
|
||||
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
|
||||
{ label: "Schedule Tasks", to: "/settings/scheduled-tasks", icon: CalendarClockIcon },
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { SettingsIcon } from "lucide-react";
|
||||
import { memo, useCallback } from "react";
|
||||
import { Link, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { APP_STAGE_LABEL } from "../../branding";
|
||||
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { primaryServerConfigAtom } from "../../state/server";
|
||||
import { resolveSidebarStageBadgeLabel } from "../Sidebar.logic";
|
||||
import { SidebarStageBackdrop, resolveSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
|
||||
import {
|
||||
resolveEnvironmentIdentificationPillLabel,
|
||||
resolveSidebarStageBackdropVariant,
|
||||
SidebarStageBackdrop,
|
||||
useEnvironmentStageLabel,
|
||||
} from "../SidebarStageBackdrop";
|
||||
import { Badge } from "../ui/badge";
|
||||
import {
|
||||
SidebarFooter,
|
||||
SidebarHeader,
|
||||
@@ -25,8 +28,16 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
}: {
|
||||
isElectron: boolean;
|
||||
}) {
|
||||
const stageLabel = useSidebarStageLabel();
|
||||
const backdropVariant = resolveSidebarStageBackdropVariant(stageLabel);
|
||||
const stageLabel = useEnvironmentStageLabel();
|
||||
const environmentIdentificationMode = useEnvironmentIdentificationMode();
|
||||
const backdropVariant = resolveSidebarStageBackdropVariant(
|
||||
stageLabel,
|
||||
environmentIdentificationMode === "artwork",
|
||||
);
|
||||
const pillLabel =
|
||||
environmentIdentificationMode === "pill"
|
||||
? resolveEnvironmentIdentificationPillLabel(stageLabel)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<SidebarHeader
|
||||
@@ -44,6 +55,16 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
)}
|
||||
/>
|
||||
<SidebarBrand onBackdrop={backdropVariant !== null} />
|
||||
{pillLabel ? (
|
||||
<Badge
|
||||
className="relative z-10 ml-1 rounded-full px-1.5 text-muted-foreground"
|
||||
data-environment-identification="pill"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
>
|
||||
{pillLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
</SidebarHeader>
|
||||
);
|
||||
});
|
||||
@@ -71,16 +92,6 @@ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function useSidebarStageLabel() {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
return resolveSidebarStageBadgeLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
});
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
|
||||
@@ -6,7 +6,18 @@ import {
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { mergeEnvironmentSettings } from "./useSettings";
|
||||
import { mergeEnvironmentSettings, resolveEnvironmentIdentificationMode } from "./useSettings";
|
||||
|
||||
describe("resolveEnvironmentIdentificationMode", () => {
|
||||
it("keeps identification hidden until client settings hydrate", () => {
|
||||
expect(resolveEnvironmentIdentificationMode({ mode: "artwork", settingsHydrated: false })).toBe(
|
||||
"none",
|
||||
);
|
||||
expect(resolveEnvironmentIdentificationMode({ mode: "pill", settingsHydrated: true })).toBe(
|
||||
"pill",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeEnvironmentSettings", () => {
|
||||
it("combines the selected environment's server settings with client preferences", () => {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
type ClientSettingsPatch,
|
||||
type ClientSettings,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
type EnvironmentIdentificationMode,
|
||||
type UnifiedSettings,
|
||||
} from "@t3tools/contracts/settings";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
@@ -222,6 +223,20 @@ export function useClientSettings<T = ClientSettings>(
|
||||
return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
|
||||
}
|
||||
|
||||
export function resolveEnvironmentIdentificationMode(input: {
|
||||
mode: EnvironmentIdentificationMode;
|
||||
settingsHydrated: boolean;
|
||||
}): EnvironmentIdentificationMode {
|
||||
// Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
|
||||
return input.settingsHydrated ? input.mode : "none";
|
||||
}
|
||||
|
||||
export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
|
||||
const settingsHydrated = useClientSettingsHydrated();
|
||||
const mode = useClientSettingsValue().environmentIdentificationMode;
|
||||
return resolveEnvironmentIdentificationMode({ mode, settingsHydrated });
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolved sidebar v2 state: an explicit choice in Settings → Beta if the user
|
||||
* has made one, otherwise the default for this build stage (on for nightly and
|
||||
|
||||
@@ -23,6 +23,7 @@ import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagn
|
||||
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
|
||||
import { Route as SettingsBetaRouteImport } from './routes/settings.beta'
|
||||
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
|
||||
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
|
||||
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
|
||||
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
|
||||
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
|
||||
@@ -96,6 +97,11 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
|
||||
path: '/archived',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsAppearanceRoute = SettingsAppearanceRouteImport.update({
|
||||
id: '/appearance',
|
||||
path: '/appearance',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const ConnectCallbackRoute = ConnectCallbackRouteImport.update({
|
||||
id: '/connect_/callback',
|
||||
path: '/connect/callback',
|
||||
@@ -119,6 +125,7 @@ export interface FileRoutesByFullPath {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
@@ -136,6 +143,7 @@ export interface FileRoutesByTo {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
@@ -156,6 +164,7 @@ export interface FileRoutesById {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect_/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
@@ -177,6 +186,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
@@ -194,6 +204,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
@@ -213,6 +224,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/connect_/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
@@ -335,6 +347,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsArchivedRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/appearance': {
|
||||
id: '/settings/appearance'
|
||||
path: '/appearance'
|
||||
fullPath: '/settings/appearance'
|
||||
preLoaderRoute: typeof SettingsAppearanceRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/connect_/callback': {
|
||||
id: '/connect_/callback'
|
||||
path: '/connect/callback'
|
||||
@@ -374,6 +393,7 @@ const ChatRouteChildren: ChatRouteChildren = {
|
||||
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
|
||||
|
||||
interface SettingsRouteChildren {
|
||||
SettingsAppearanceRoute: typeof SettingsAppearanceRoute
|
||||
SettingsArchivedRoute: typeof SettingsArchivedRoute
|
||||
SettingsBetaRoute: typeof SettingsBetaRoute
|
||||
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
|
||||
@@ -386,6 +406,7 @@ interface SettingsRouteChildren {
|
||||
}
|
||||
|
||||
const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsAppearanceRoute: SettingsAppearanceRoute,
|
||||
SettingsArchivedRoute: SettingsArchivedRoute,
|
||||
SettingsBetaRoute: SettingsBetaRoute,
|
||||
SettingsConnectionsRoute: SettingsConnectionsRoute,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { AppearanceSettingsPanel } from "../components/settings/SettingsPanels";
|
||||
|
||||
function SettingsAppearanceRoute() {
|
||||
return <AppearanceSettingsPanel />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/settings/appearance")({
|
||||
component: SettingsAppearanceRoute,
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import * as RemovalPolicy from "alchemy/RemovalPolicy";
|
||||
import type { EffectPgDatabase } from "drizzle-orm/effect-postgres";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { relayDatabaseMode } from "./dbConfig.ts";
|
||||
|
||||
@@ -17,6 +18,23 @@ export class RelayDb extends Context.Service<
|
||||
}
|
||||
>()("t3code-relay/db/RelayDb") {}
|
||||
|
||||
export class RelayTransactions extends Context.Service<
|
||||
RelayTransactions,
|
||||
{
|
||||
readonly withTransaction: RelayDb["Service"]["$client"]["withTransaction"];
|
||||
}
|
||||
>()("t3code-relay/db/RelayTransactions") {
|
||||
static readonly layer = Layer.effect(
|
||||
RelayTransactions,
|
||||
Effect.gen(function* () {
|
||||
const db = yield* RelayDb;
|
||||
return RelayTransactions.of({
|
||||
withTransaction: db.$client.withTransaction,
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const PlanetscaleDatabase = Effect.gen(function* () {
|
||||
const { stage } = yield* Alchemy.Stack;
|
||||
const schema = yield* Drizzle.Schema("RelaySchema", {
|
||||
|
||||
@@ -198,7 +198,9 @@ function makeAllocations(
|
||||
recordDns: () => Effect.die("unused"),
|
||||
markReady: () => Effect.die("unused"),
|
||||
claimRelease: () => Effect.die("unused"),
|
||||
claimDeprovision: () => Effect.die("unused"),
|
||||
remove: () => Effect.die("unused"),
|
||||
removeClaimed: () => Effect.die("unused"),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { PgDialect, QueryBuilder } from "drizzle-orm/pg-core";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
@@ -58,13 +58,17 @@ describe("EnvironmentCredentials", () => {
|
||||
it.effect("does not retain credential tokens when lookup persistence fails", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const token = "t3env_sensitive-credential-token";
|
||||
const whereConditions: Array<unknown> = [];
|
||||
const fakeDb = {
|
||||
select: () => ({
|
||||
from: (table: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentCredentials);
|
||||
return {
|
||||
where: () => ({
|
||||
limit: () => Effect.fail(cause),
|
||||
where: (condition: unknown) => ({
|
||||
limit: () => {
|
||||
whereConditions.push(condition);
|
||||
return Effect.fail(cause);
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
@@ -81,6 +85,13 @@ describe("EnvironmentCredentials", () => {
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("token");
|
||||
expect(whereConditions).toHaveLength(1);
|
||||
|
||||
const query = new PgDialect().sqlToQuery(whereConditions[0] as never);
|
||||
expect(query.sql).toContain("exists");
|
||||
expect(query.sql).toContain('"relay_environment_links"."environment_id"');
|
||||
expect(query.sql).toContain('"relay_environment_links"."environment_public_key"');
|
||||
expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EnvironmentCredentials.layer.pipe(
|
||||
@@ -180,7 +191,6 @@ describe("EnvironmentCredentials", () => {
|
||||
const updateValues: Array<Record<string, unknown>> = [];
|
||||
const whereConditions: Array<unknown> = [];
|
||||
const fakeDb = {
|
||||
select: (fields: Parameters<QueryBuilder["select"]>[0]) => new QueryBuilder().select(fields),
|
||||
update: (table: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentCredentials);
|
||||
return {
|
||||
|
||||
@@ -6,7 +6,8 @@ import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { and, eq, isNull, ne, notExists } from "drizzle-orm";
|
||||
import { and, eq, exists, isNull, ne, notExists } from "drizzle-orm";
|
||||
import { QueryBuilder } from "drizzle-orm/pg-core";
|
||||
|
||||
import * as RelayDb from "../db.ts";
|
||||
import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persistence/schema.ts";
|
||||
@@ -196,6 +197,24 @@ const make = Effect.gen(function* () {
|
||||
and(
|
||||
eq(relayEnvironmentCredentials.credentialHash, credentialHash),
|
||||
isNull(relayEnvironmentCredentials.revokedAt),
|
||||
exists(
|
||||
new QueryBuilder()
|
||||
.select({ userId: relayEnvironmentLinks.userId })
|
||||
.from(relayEnvironmentLinks)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
relayEnvironmentLinks.environmentId,
|
||||
relayEnvironmentCredentials.environmentId,
|
||||
),
|
||||
eq(
|
||||
relayEnvironmentLinks.environmentPublicKey,
|
||||
relayEnvironmentCredentials.environmentPublicKey,
|
||||
),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.limit(1)
|
||||
@@ -238,7 +257,7 @@ const make = Effect.gen(function* () {
|
||||
eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),
|
||||
isNull(relayEnvironmentCredentials.revokedAt),
|
||||
notExists(
|
||||
db
|
||||
new QueryBuilder()
|
||||
.select({ userId: relayEnvironmentLinks.userId })
|
||||
.from(relayEnvironmentLinks)
|
||||
.where(
|
||||
|
||||
@@ -136,6 +136,7 @@ function testLayer(input?: {
|
||||
revokeForEnvironmentPublicKey: () => Effect.succeed(false),
|
||||
}),
|
||||
Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, {
|
||||
prepareDeprovision: () => Effect.succeed(null),
|
||||
deprovision: input?.deprovision ?? (() => Effect.void),
|
||||
release: () => Effect.succeed(true),
|
||||
provision: () =>
|
||||
|
||||
@@ -10,6 +10,61 @@ const layerWithDb = (db: RelayDb.RelayDb["Service"]) =>
|
||||
ManagedEndpointAllocations.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, db)));
|
||||
|
||||
describe("ManagedEndpointAllocations", () => {
|
||||
it.effect("returns a claim generation only when deprovision wins the allocation CAS", () => {
|
||||
let claimedAt: string | undefined;
|
||||
const fakeDb = {
|
||||
update: (table: unknown) => {
|
||||
expect(table).toBe(relayManagedEndpointAllocations);
|
||||
return {
|
||||
set: (values: { readonly updatedAt: string }) => {
|
||||
claimedAt = values.updatedAt;
|
||||
return {
|
||||
where: () => ({
|
||||
returning: () => Effect.succeed([{ userId: "user-1" }]),
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
|
||||
const generation = yield* allocations.claimDeprovision({
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
updatedAt: "captured-generation",
|
||||
});
|
||||
|
||||
expect(generation).toBe(claimedAt);
|
||||
expect(generation).not.toBeNull();
|
||||
}).pipe(Effect.provide(layerWithDb(fakeDb)));
|
||||
});
|
||||
|
||||
it.effect("does not remove an allocation superseded after a deprovision claim", () => {
|
||||
const fakeDb = {
|
||||
delete: (table: unknown) => {
|
||||
expect(table).toBe(relayManagedEndpointAllocations);
|
||||
return {
|
||||
where: () => ({
|
||||
returning: () => Effect.succeed([]),
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
|
||||
expect(
|
||||
yield* allocations.removeClaimed({
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
updatedAt: "outdated-claim-generation",
|
||||
}),
|
||||
).toBe(false);
|
||||
}).pipe(Effect.provide(layerWithDb(fakeDb)));
|
||||
});
|
||||
|
||||
it.effect("retains database failures with allocation operation and identity", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const fakeDb = {
|
||||
|
||||
@@ -51,7 +51,9 @@ export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErro
|
||||
"record-dns",
|
||||
"mark-ready",
|
||||
"claim-release",
|
||||
"claim-deprovision",
|
||||
"remove",
|
||||
"remove-claimed",
|
||||
]),
|
||||
stage: Schema.Literals(["database-request", "resolve-reservation"]),
|
||||
userId: Schema.String,
|
||||
@@ -91,6 +93,14 @@ interface ClaimManagedEndpointReleaseInput extends ManagedEndpointAllocationKey
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
interface ClaimManagedEndpointDeprovisionInput extends ManagedEndpointAllocationKey {
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
interface RemoveClaimedManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export class ManagedEndpointAllocations extends Context.Service<
|
||||
ManagedEndpointAllocations,
|
||||
{
|
||||
@@ -119,9 +129,22 @@ export class ManagedEndpointAllocations extends Context.Service<
|
||||
readonly claimRelease: (
|
||||
input: ClaimManagedEndpointReleaseInput,
|
||||
) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;
|
||||
/**
|
||||
* Claims the complete allocation for teardown only if its generation still
|
||||
* matches the snapshot captured by the unlink operation.
|
||||
*
|
||||
* Returns the claim generation used by `removeClaimed`, or null when a
|
||||
* concurrent provision has already superseded the snapshot.
|
||||
*/
|
||||
readonly claimDeprovision: (
|
||||
input: ClaimManagedEndpointDeprovisionInput,
|
||||
) => Effect.Effect<string | null, ManagedEndpointAllocationPersistenceError>;
|
||||
readonly remove: (
|
||||
input: ManagedEndpointAllocationKey,
|
||||
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
|
||||
readonly removeClaimed: (
|
||||
input: RemoveClaimedManagedEndpointAllocationInput,
|
||||
) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;
|
||||
}
|
||||
>()("t3code-relay/environments/ManagedEndpointAllocations") {}
|
||||
|
||||
@@ -321,6 +344,35 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
return claimed;
|
||||
}),
|
||||
claimDeprovision: Effect.fn("relay.managed_endpoint_allocations.claim_deprovision")(function* (
|
||||
input: ClaimManagedEndpointDeprovisionInput,
|
||||
) {
|
||||
const claimedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const claimed = yield* db
|
||||
.update(relayManagedEndpointAllocations)
|
||||
.set({ updatedAt: claimedAt })
|
||||
.where(
|
||||
and(
|
||||
whereAllocation(input),
|
||||
eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),
|
||||
),
|
||||
)
|
||||
.returning({ userId: relayManagedEndpointAllocations.userId })
|
||||
.pipe(
|
||||
Effect.map((rows) => rows.length > 0),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "claim-deprovision",
|
||||
stage: "database-request",
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return claimed ? claimedAt : null;
|
||||
}),
|
||||
remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* (
|
||||
input: ManagedEndpointAllocationKey,
|
||||
) {
|
||||
@@ -339,6 +391,32 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
}),
|
||||
removeClaimed: Effect.fn("relay.managed_endpoint_allocations.remove_claimed")(function* (
|
||||
input: RemoveClaimedManagedEndpointAllocationInput,
|
||||
) {
|
||||
return yield* db
|
||||
.delete(relayManagedEndpointAllocations)
|
||||
.where(
|
||||
and(
|
||||
whereAllocation(input),
|
||||
eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),
|
||||
),
|
||||
)
|
||||
.returning({ userId: relayManagedEndpointAllocations.userId })
|
||||
.pipe(
|
||||
Effect.map((rows) => rows.length > 0),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "remove-claimed",
|
||||
stage: "database-request",
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -50,7 +50,9 @@ interface AllocationCall {
|
||||
| "recordDns"
|
||||
| "markReady"
|
||||
| "claimRelease"
|
||||
| "remove";
|
||||
| "claimDeprovision"
|
||||
| "remove"
|
||||
| "removeClaimed";
|
||||
readonly input: unknown;
|
||||
}
|
||||
|
||||
@@ -226,11 +228,31 @@ function makeAllocations(calls: AllocationCall[] = []) {
|
||||
mutate(allocationKey(input), (current) => current);
|
||||
return true;
|
||||
}),
|
||||
claimDeprovision: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push({ operation: "claimDeprovision", input });
|
||||
const allocation = allocations.get(allocationKey(input));
|
||||
if (allocation === undefined || allocation.updatedAt !== input.updatedAt) {
|
||||
return null;
|
||||
}
|
||||
mutate(allocationKey(input), (current) => current);
|
||||
return allocations.get(allocationKey(input))?.updatedAt ?? null;
|
||||
}),
|
||||
remove: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push({ operation: "remove", input });
|
||||
allocations.delete(allocationKey(input));
|
||||
}),
|
||||
removeClaimed: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push({ operation: "removeClaimed", input });
|
||||
const allocation = allocations.get(allocationKey(input));
|
||||
if (allocation === undefined || allocation.updatedAt !== input.updatedAt) {
|
||||
return false;
|
||||
}
|
||||
allocations.delete(allocationKey(input));
|
||||
return true;
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -774,12 +796,54 @@ describe("ManagedEndpointProvider", () => {
|
||||
"recordDns",
|
||||
"markReady",
|
||||
"get",
|
||||
"remove",
|
||||
"claimDeprovision",
|
||||
"removeClaimed",
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("does not deprovision an allocation superseded by a concurrent relink", () => {
|
||||
const tunnelCalls: TunnelCall[] = [];
|
||||
const dnsCalls: DnsCall[] = [];
|
||||
const allocationCalls: AllocationCall[] = [];
|
||||
const layer = providerLayer(
|
||||
makePersistentTunnelClient(tunnelCalls),
|
||||
makeDnsClient(dnsCalls),
|
||||
makeAllocations(allocationCalls),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
|
||||
const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
|
||||
const request = {
|
||||
...key,
|
||||
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
|
||||
} as const;
|
||||
yield* provider.provision(request);
|
||||
const unlinkTarget = yield* provider.prepareDeprovision(key);
|
||||
expect(unlinkTarget).not.toBeNull();
|
||||
if (unlinkTarget === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A relink refreshes the allocation generation after unlink captured its
|
||||
// target but before unlink begins external teardown.
|
||||
yield* provider.provision(request);
|
||||
const tunnelCallCount = tunnelCalls.length;
|
||||
const dnsCallCount = dnsCalls.length;
|
||||
const allocationCallCount = allocationCalls.length;
|
||||
|
||||
yield* provider.deprovision({ ...key, target: unlinkTarget });
|
||||
|
||||
expect(tunnelCalls).toHaveLength(tunnelCallCount);
|
||||
expect(dnsCalls).toHaveLength(dnsCallCount);
|
||||
expect(allocationCalls.slice(allocationCallCount).map((call) => call.operation)).toEqual([
|
||||
"claimDeprovision",
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("releases the tunnel while keeping the allocation, DNS record, and hostname", () => {
|
||||
const tunnelCalls: TunnelCall[] = [];
|
||||
const dnsCalls: DnsCall[] = [];
|
||||
@@ -1004,8 +1068,10 @@ describe("ManagedEndpointProvider", () => {
|
||||
"recordDns",
|
||||
"markReady",
|
||||
"get",
|
||||
"claimDeprovision",
|
||||
"get",
|
||||
"remove",
|
||||
"claimDeprovision",
|
||||
"removeClaimed",
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
@@ -1046,7 +1112,7 @@ describe("ManagedEndpointProvider", () => {
|
||||
});
|
||||
yield* provider.deprovision(key);
|
||||
|
||||
expect(allocationCalls.map((call) => call.operation)).toContain("remove");
|
||||
expect(allocationCalls.map((call) => call.operation)).toContain("removeClaimed");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
|
||||
@@ -77,6 +77,7 @@ export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<M
|
||||
const ManagedEndpointDeprovisioningStage = Schema.Literals([
|
||||
"load-allocation",
|
||||
"claim-release",
|
||||
"claim-deprovision",
|
||||
"delete-dns-record",
|
||||
"delete-tunnel",
|
||||
"remove-allocation",
|
||||
@@ -123,6 +124,8 @@ export interface ManagedEndpointProvisioningResult {
|
||||
readonly runtime: RelayManagedEndpointRuntimeConfig;
|
||||
}
|
||||
|
||||
export type ManagedEndpointDeprovisionTarget = ManagedEndpointAllocations.ManagedEndpointAllocation;
|
||||
|
||||
export class ManagedEndpointProvider extends Context.Service<
|
||||
ManagedEndpointProvider,
|
||||
{
|
||||
@@ -131,9 +134,22 @@ export class ManagedEndpointProvider extends Context.Service<
|
||||
readonly environmentId: string;
|
||||
readonly origin: RelayManagedEndpointOrigin;
|
||||
}) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
|
||||
/**
|
||||
* Captures the allocation generation owned by an unlink before its link
|
||||
* revocation commits. Passing this target to `deprovision` prevents a
|
||||
* concurrent relink from having its newer allocation torn down.
|
||||
*/
|
||||
readonly prepareDeprovision: (input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
}) => Effect.Effect<
|
||||
ManagedEndpointDeprovisionTarget | null,
|
||||
ManagedEndpointDeprovisioningFailed
|
||||
>;
|
||||
readonly deprovision: (input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly target?: ManagedEndpointDeprovisionTarget | null;
|
||||
}) => Effect.Effect<void, ManagedEndpointDeprovisioningFailed>;
|
||||
/**
|
||||
* Deletes the provisioned Cloudflare tunnel while keeping the allocation
|
||||
@@ -424,13 +440,9 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
return ManagedEndpointProvider.of({
|
||||
deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.user_id": input.userId,
|
||||
"relay.environment_id": input.environmentId,
|
||||
});
|
||||
const allocation = yield* allocations.get(input).pipe(
|
||||
const prepareDeprovision = Effect.fn("relay.managed_endpoint_provider.prepare_deprovision")(
|
||||
function* (input: { readonly userId: string; readonly environmentId: string }) {
|
||||
return yield* allocations.get(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDeprovisioningFailed({
|
||||
@@ -440,9 +452,42 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return ManagedEndpointProvider.of({
|
||||
prepareDeprovision,
|
||||
deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.user_id": input.userId,
|
||||
"relay.environment_id": input.environmentId,
|
||||
});
|
||||
const allocation =
|
||||
input.target === undefined ? yield* prepareDeprovision(input) : input.target;
|
||||
if (allocation === null) {
|
||||
return;
|
||||
}
|
||||
const claimedAt = yield* allocations
|
||||
.claimDeprovision({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
updatedAt: allocation.updatedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDeprovisioningFailed({
|
||||
...input,
|
||||
stage: "claim-deprovision",
|
||||
...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
|
||||
...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (claimedAt === null) {
|
||||
return;
|
||||
}
|
||||
const dnsRecordId = allocation.dnsRecordId;
|
||||
if (dnsRecordId !== null) {
|
||||
yield* ignoreNotFound(dns.deleteRecord(dnsRecordId)).pipe(
|
||||
@@ -471,18 +516,24 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
}
|
||||
yield* allocations.remove(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDeprovisioningFailed({
|
||||
...input,
|
||||
stage: "remove-allocation",
|
||||
...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
|
||||
...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* allocations
|
||||
.removeClaimed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
updatedAt: claimedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDeprovisioningFailed({
|
||||
...input,
|
||||
stage: "remove-allocation",
|
||||
...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
|
||||
...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
release: Effect.fn("relay.managed_endpoint_provider.release")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Layer from "effect/Layer";
|
||||
|
||||
import * as RelayDb from "../db.ts";
|
||||
import {
|
||||
relayEnvironmentLinks,
|
||||
relayManagedEndpointAllocations,
|
||||
relayManagedTunnelLimits,
|
||||
} from "../persistence/schema.ts";
|
||||
@@ -28,7 +29,16 @@ function makeFakeDb(input: {
|
||||
}
|
||||
expect(table).toBe(relayManagedEndpointAllocations);
|
||||
return {
|
||||
where: () => input.countRows ?? Effect.succeed([{ activeTunnels: 0 }]),
|
||||
innerJoin: (table: unknown, condition: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentLinks);
|
||||
expect(condition).toBeDefined();
|
||||
return {
|
||||
where: (where: unknown) => {
|
||||
expect(where).toBeDefined();
|
||||
return input.countRows ?? Effect.succeed([{ activeTunnels: 0 }]);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, count, eq, ne } from "drizzle-orm";
|
||||
import { and, count, eq, isNull, ne } from "drizzle-orm";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -6,6 +6,7 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as RelayDb from "../db.ts";
|
||||
import {
|
||||
relayEnvironmentLinks,
|
||||
relayManagedEndpointAllocations,
|
||||
relayManagedTunnelLimits,
|
||||
} from "../persistence/schema.ts";
|
||||
@@ -81,10 +82,19 @@ export const make = Effect.gen(function* () {
|
||||
const counted = yield* db
|
||||
.select({ activeTunnels: count() })
|
||||
.from(relayManagedEndpointAllocations)
|
||||
.innerJoin(
|
||||
relayEnvironmentLinks,
|
||||
and(
|
||||
eq(relayEnvironmentLinks.userId, relayManagedEndpointAllocations.userId),
|
||||
eq(relayEnvironmentLinks.environmentId, relayManagedEndpointAllocations.environmentId),
|
||||
),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(relayManagedEndpointAllocations.userId, input.userId),
|
||||
ne(relayManagedEndpointAllocations.environmentId, input.environmentId),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
eq(relayEnvironmentLinks.managedTunnelsEnabled, true),
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
|
||||
@@ -14,6 +14,7 @@ import * as Tracer from "effect/Tracer";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { RelayEnvironmentAuth } from "@t3tools/contracts/relay";
|
||||
|
||||
import {
|
||||
@@ -22,12 +23,17 @@ import {
|
||||
relayDocsRedirectRoute,
|
||||
relayEnvironmentAuthLayer,
|
||||
relayNotFoundRoute,
|
||||
revokeEnvironmentLinkRecord,
|
||||
traceRelayHttpRequestWith,
|
||||
unlinkEnvironmentRecord,
|
||||
verifyRelayClientBearerToken,
|
||||
withoutCapturedParentSpan,
|
||||
} from "./Api.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as RelayDb from "../db.ts";
|
||||
import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
|
||||
import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";
|
||||
|
||||
vi.mock("@clerk/backend", () => ({
|
||||
createClerkClient: vi.fn(),
|
||||
@@ -155,6 +161,240 @@ describe("relay environment authentication", () => {
|
||||
});
|
||||
});
|
||||
|
||||
function relayUnlinkTestLayer(input?: {
|
||||
readonly withTransaction?: RelayDb.RelayTransactions["Service"]["withTransaction"];
|
||||
readonly getForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["getForUser"];
|
||||
readonly revokeForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["revokeForUser"];
|
||||
readonly revokeCredential?: EnvironmentCredentials.EnvironmentCredentials["Service"]["revokeForEnvironmentPublicKey"];
|
||||
readonly prepareDeprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["prepareDeprovision"];
|
||||
readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];
|
||||
}) {
|
||||
return Layer.mergeAll(
|
||||
Layer.succeed(
|
||||
RelayDb.RelayTransactions,
|
||||
RelayDb.RelayTransactions.of({
|
||||
withTransaction: input?.withTransaction ?? ((effect) => effect),
|
||||
}),
|
||||
),
|
||||
Layer.succeed(
|
||||
EnvironmentLinks.EnvironmentLinks,
|
||||
EnvironmentLinks.EnvironmentLinks.of({
|
||||
upsert: () => Effect.die("unused upsert"),
|
||||
listUsersForEnvironment: () => Effect.die("unused listUsersForEnvironment"),
|
||||
listDeliveryUsersForEnvironment: () => Effect.die("unused listDeliveryUsersForEnvironment"),
|
||||
listPublicKeysForEnvironment: () => Effect.die("unused listPublicKeysForEnvironment"),
|
||||
listForUser: () => Effect.die("unused listForUser"),
|
||||
getForUser: input?.getForUser ?? (() => Effect.succeed(null)),
|
||||
revokeForUser: input?.revokeForUser ?? (() => Effect.succeed(false)),
|
||||
}),
|
||||
),
|
||||
Layer.succeed(
|
||||
EnvironmentCredentials.EnvironmentCredentials,
|
||||
EnvironmentCredentials.EnvironmentCredentials.of({
|
||||
create: () => Effect.die("unused create"),
|
||||
authenticate: () => Effect.die("unused authenticate"),
|
||||
revokeForEnvironmentPublicKey: input?.revokeCredential ?? (() => Effect.succeed(false)),
|
||||
}),
|
||||
),
|
||||
Layer.succeed(
|
||||
ManagedEndpointProvider.ManagedEndpointProvider,
|
||||
ManagedEndpointProvider.ManagedEndpointProvider.of({
|
||||
provision: () => Effect.die("unused provision"),
|
||||
prepareDeprovision: input?.prepareDeprovision ?? (() => Effect.succeed(null)),
|
||||
deprovision: input?.deprovision ?? (() => Effect.void),
|
||||
release: () => Effect.die("unused release"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const linkedEnvironmentRecord = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Environment 1",
|
||||
endpoint: {
|
||||
httpBaseUrl: "https://environment-1.example.test/",
|
||||
wsBaseUrl: "wss://environment-1.example.test/ws",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
},
|
||||
environmentPublicKey: "public-key",
|
||||
linkedAt: "2026-07-28T00:00:00.000Z",
|
||||
} as const;
|
||||
|
||||
describe("relay environment unlink", () => {
|
||||
it.effect("revokes the link and its credentials in one database transaction", () => {
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
expect(
|
||||
yield* revokeEnvironmentLinkRecord({
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
environmentPublicKey: "public-key",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(calls).toEqual(["transaction", "link", "credential"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
relayUnlinkTestLayer({
|
||||
withTransaction: (effect) => {
|
||||
calls.push("transaction");
|
||||
return effect;
|
||||
},
|
||||
revokeForUser: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("link");
|
||||
return true;
|
||||
}),
|
||||
revokeCredential: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("credential");
|
||||
return true;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("commits database revocation before deprovisioning the managed endpoint", () => {
|
||||
const calls: Array<string> = [];
|
||||
const deprovisionTarget = {
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
hostname: "environment-1.example.test",
|
||||
tunnelId: "tunnel-1",
|
||||
tunnelName: "environment-1-tunnel",
|
||||
dnsRecordId: "dns-1",
|
||||
readyAt: "2026-07-28T00:00:00.000Z",
|
||||
updatedAt: "generation-before-unlink",
|
||||
} satisfies ManagedEndpointProvider.ManagedEndpointDeprovisionTarget;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
expect(
|
||||
yield* unlinkEnvironmentRecord({
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(calls).toEqual([
|
||||
"prepare",
|
||||
"lookup",
|
||||
"transaction",
|
||||
"link",
|
||||
"credential",
|
||||
"deprovision",
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
relayUnlinkTestLayer({
|
||||
withTransaction: (effect) => {
|
||||
calls.push("transaction");
|
||||
return effect;
|
||||
},
|
||||
getForUser: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("lookup");
|
||||
return linkedEnvironmentRecord;
|
||||
}),
|
||||
revokeForUser: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("link");
|
||||
return true;
|
||||
}),
|
||||
revokeCredential: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("credential");
|
||||
return true;
|
||||
}),
|
||||
prepareDeprovision: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("prepare");
|
||||
return deprovisionTarget;
|
||||
}),
|
||||
deprovision: (request) =>
|
||||
Effect.sync(() => {
|
||||
expect(request.target).toBe(deprovisionTarget);
|
||||
calls.push("deprovision");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not deprovision when database revocation fails", () => {
|
||||
const calls: Array<string> = [];
|
||||
const failure = new EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError({
|
||||
environmentId: "environment-1",
|
||||
cause: "database unavailable",
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
expect(
|
||||
yield* Effect.flip(
|
||||
unlinkEnvironmentRecord({
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
}),
|
||||
),
|
||||
).toBe(failure);
|
||||
expect(calls).toEqual(["prepare", "transaction", "link", "credential"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
relayUnlinkTestLayer({
|
||||
withTransaction: (effect) => {
|
||||
calls.push("transaction");
|
||||
return effect;
|
||||
},
|
||||
getForUser: () => Effect.succeed(linkedEnvironmentRecord),
|
||||
revokeForUser: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("link");
|
||||
return true;
|
||||
}),
|
||||
revokeCredential: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("credential");
|
||||
}).pipe(Effect.andThen(Effect.fail(failure))),
|
||||
prepareDeprovision: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("prepare");
|
||||
return null;
|
||||
}),
|
||||
deprovision: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("deprovision");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("retries deprovisioning after the link is already revoked", () => {
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
expect(
|
||||
yield* unlinkEnvironmentRecord({
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(calls).toEqual(["prepare", "deprovision"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
relayUnlinkTestLayer({
|
||||
prepareDeprovision: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("prepare");
|
||||
return null;
|
||||
}),
|
||||
deprovision: () =>
|
||||
Effect.sync(() => {
|
||||
calls.push("deprovision");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("relay request tracing", () => {
|
||||
it.effect(
|
||||
"does not parent endpoint spans to an ambient parent captured while building handlers",
|
||||
|
||||
+69
-22
@@ -403,6 +403,67 @@ export const healthApi = HttpApiBuilder.group(
|
||||
}),
|
||||
);
|
||||
|
||||
export const revokeEnvironmentLinkRecord = Effect.fn(
|
||||
"relay.api.client.revokeEnvironmentLinkRecord",
|
||||
)(function* (input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly environmentPublicKey: string;
|
||||
}) {
|
||||
const transactions = yield* RelayDb.RelayTransactions;
|
||||
const links = yield* EnvironmentLinks.EnvironmentLinks;
|
||||
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
|
||||
return yield* transactions.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const revoked = yield* links.revokeForUser({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* credentials.revokeForEnvironmentPublicKey({
|
||||
environmentId: input.environmentId,
|
||||
environmentPublicKey: input.environmentPublicKey,
|
||||
});
|
||||
}
|
||||
return revoked;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnvironmentRecord")(
|
||||
function* (input: { readonly userId: string; readonly environmentId: string }) {
|
||||
const links = yield* EnvironmentLinks.EnvironmentLinks;
|
||||
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
|
||||
const deprovisionTarget = yield* managedEndpointProvider.prepareDeprovision({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
});
|
||||
const link = yield* links.getForUser({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
});
|
||||
const unlinked =
|
||||
link === null
|
||||
? false
|
||||
: yield* revokeEnvironmentLinkRecord({
|
||||
userId: input.userId,
|
||||
environmentId: link.environmentId,
|
||||
environmentPublicKey: link.environmentPublicKey,
|
||||
});
|
||||
|
||||
// External teardown cannot share the SQL transaction. Run it only after
|
||||
// revocation commits so a database failure leaves a fully usable active
|
||||
// link. Still run teardown when the link is already revoked, allowing a
|
||||
// retry to finish cleanup after an earlier Cloudflare failure.
|
||||
yield* managedEndpointProvider.deprovision({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
target: deprovisionTarget,
|
||||
});
|
||||
return unlinked;
|
||||
},
|
||||
);
|
||||
|
||||
export const mobileApi = HttpApiBuilder.group(
|
||||
RelayApi,
|
||||
"mobile",
|
||||
@@ -470,7 +531,6 @@ export const clientApi = HttpApiBuilder.group(
|
||||
const linker = yield* EnvironmentLinker.EnvironmentLinker;
|
||||
const links = yield* EnvironmentLinks.EnvironmentLinks;
|
||||
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
|
||||
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
|
||||
const devices = yield* Devices.Devices;
|
||||
return handlers
|
||||
.handle(
|
||||
@@ -592,29 +652,16 @@ export const clientApi = HttpApiBuilder.group(
|
||||
Effect.fn("relay.api.client.unlinkEnvironment")(function* (args) {
|
||||
const { params } = args;
|
||||
const { userId } = yield* RelayClientPrincipal;
|
||||
yield* managedEndpointProvider
|
||||
.deprovision({
|
||||
userId,
|
||||
environmentId: params.environmentId,
|
||||
})
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
|
||||
const link = yield* links.getForUser({
|
||||
const unlinked = yield* unlinkEnvironmentRecord({
|
||||
userId,
|
||||
environmentId: params.environmentId,
|
||||
});
|
||||
if (link === null) {
|
||||
return { ok: false };
|
||||
}
|
||||
const unlinked = yield* links.revokeForUser({
|
||||
userId,
|
||||
environmentId: params.environmentId,
|
||||
});
|
||||
if (unlinked) {
|
||||
yield* credentials.revokeForEnvironmentPublicKey({
|
||||
environmentId: link.environmentId,
|
||||
environmentPublicKey: link.environmentPublicKey,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
SqlError: () => relayInternalErrorResponse("internal_error"),
|
||||
ManagedEndpointDeprovisioningFailed: () =>
|
||||
relayInternalErrorResponse("upstream_unavailable"),
|
||||
}),
|
||||
);
|
||||
return { ok: unlinked };
|
||||
}, mapRelayCommonApiErrors("not_authorized")),
|
||||
)
|
||||
|
||||
@@ -217,7 +217,11 @@ export const ApiLive = Api.make(
|
||||
Layer.provideMerge(LiveActivities.layer),
|
||||
Layer.provideMerge(DeliveryAttempts.layer),
|
||||
Layer.provideMerge(RelayTokens.layer),
|
||||
Layer.provideMerge(Layer.succeed(RelayDb.RelayDb, db)),
|
||||
Layer.provideMerge(
|
||||
RelayDb.RelayTransactions.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(RelayDb.RelayDb, db)),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(Layer.effect(RelayConfiguration.RelayConfiguration, loadSettings)),
|
||||
Layer.provideMerge(webcryptoLayer),
|
||||
);
|
||||
|
||||
@@ -163,32 +163,11 @@ describe("effectiveSettled", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not re-settle a warm thread on the merge signal: a message sent in a settled thread keeps it active until idle", () => {
|
||||
// The merge signal never clears, so without the idle guard a follow-up
|
||||
// message would un-settle the row only until its turn completed, then
|
||||
// snap straight back into the settled tail.
|
||||
const justActive = makeShell({ activityAt: "2026-04-09T23:30:00.000Z" });
|
||||
// The idle gate is strict: activity exactly one hour old is still warm.
|
||||
const boundary = makeShell({ activityAt: "2026-04-09T23:00:00.000Z" });
|
||||
const idle = makeShell({ activityAt: "2026-04-09T22:59:59.999Z" });
|
||||
|
||||
it("settles immediately when a change request merges or closes", () => {
|
||||
const recentlyActive = makeShell({ activityAt: "2026-04-09T23:59:59.999Z" });
|
||||
for (const changeRequestState of ["merged", "closed"] as const) {
|
||||
expect(
|
||||
effectiveSettled(justActive, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: null,
|
||||
changeRequestState,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
effectiveSettled(boundary, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: null,
|
||||
changeRequestState,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
effectiveSettled(idle, {
|
||||
effectiveSettled(recentlyActive, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: null,
|
||||
changeRequestState,
|
||||
@@ -197,14 +176,18 @@ describe("effectiveSettled", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("re-settles a merged-PR thread once the follow-up burst goes idle", () => {
|
||||
// Same shell, advancing clock: active while warm, settled again after
|
||||
// the idle window passes — the burst cools and the merge signal wins.
|
||||
const shell = makeShell({ activityAt: "2026-04-09T23:30:00.000Z" });
|
||||
const options = { autoSettleAfterDays: null, changeRequestState: "merged" as const };
|
||||
|
||||
expect(effectiveSettled(shell, { ...options, now: NOW })).toBe(false);
|
||||
expect(effectiveSettled(shell, { ...options, now: "2026-04-10T00:30:00.001Z" })).toBe(true);
|
||||
it("keeps an explicitly un-settled merged-PR thread active", () => {
|
||||
const shell = makeShell({
|
||||
settledOverride: "active",
|
||||
activityAt: "2026-04-09T23:59:59.999Z",
|
||||
});
|
||||
expect(
|
||||
effectiveSettled(shell, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: null,
|
||||
changeRequestState: "merged",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("never settles a starting session, even with a settled override", () => {
|
||||
|
||||
@@ -267,20 +267,6 @@ export function threadWokeAt(
|
||||
return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A merged/closed change request settles its thread only once the thread has
|
||||
* been idle this long. Without the idle guard the merge signal is permanent:
|
||||
* sending a message to a merged-PR thread would un-settle the row only until
|
||||
* its turn completed, then the still-merged PR would snap it straight back
|
||||
* into the settled tail. An hour keeps the follow-up conversation visible
|
||||
* while it is warm; once the burst goes stale the merge signal settles it
|
||||
* again. Activity timestamps can originate on another device while `now` is
|
||||
* this caller's clock: skew shortens or stretches the window by its size,
|
||||
* the same exposure the inactivity auto-settle already accepts — worst case
|
||||
* is a row changing lists early or late, never lost work.
|
||||
*/
|
||||
export const CHANGE_REQUEST_SETTLE_IDLE_MS = 60 * 60 * 1_000;
|
||||
|
||||
/**
|
||||
* Settled resolution over the server-backed settled lifecycle. Activity
|
||||
* blockers (pending approval/user-input, a live session, an unadjudicated
|
||||
@@ -288,7 +274,7 @@ export const CHANGE_REQUEST_SETTLE_IDLE_MS = 60 * 60 * 1_000;
|
||||
* override. Past the blockers, the explicit user override (thread.settle /
|
||||
* thread.unsettle commands, projected into settledOverride + settledAt)
|
||||
* wins in both directions; without one, a thread auto-settles on a
|
||||
* merged/closed PR (once idle) or inactivity past the window. The server
|
||||
* merged/closed PR immediately or on inactivity past the window. The server
|
||||
* un-settles on real activity (user message, session start, approval/
|
||||
* user-input request), so an override never goes stale silently.
|
||||
*/
|
||||
@@ -331,16 +317,7 @@ export function effectiveSettled(
|
||||
// until real activity clears it server-side.
|
||||
if (shell.settledOverride === "active") return false;
|
||||
if (options.changeRequestState === "merged" || options.changeRequestState === "closed") {
|
||||
// Only an idle thread settles on the merge signal: the signal itself
|
||||
// never clears, so without this guard fresh activity (a message sent in
|
||||
// a settled thread) would re-settle the moment its turn completed.
|
||||
const lastActivityAt = threadLastActivityAt(shell);
|
||||
if (
|
||||
lastActivityAt === null ||
|
||||
Date.parse(lastActivityAt) < Date.parse(options.now) - CHANGE_REQUEST_SETTLE_IDLE_MS
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (options.autoSettleAfterDays === null) return false;
|
||||
|
||||
|
||||
@@ -49,6 +49,24 @@ describe("ClientSettings glass opacity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ClientSettings environment identification", () => {
|
||||
it("defaults to artwork and accepts each presentation mode", () => {
|
||||
expect(decodeClientSettings({}).environmentIdentificationMode).toBe("artwork");
|
||||
|
||||
for (const mode of ["artwork", "pill", "none"] as const) {
|
||||
expect(
|
||||
decodeClientSettingsPatch({ environmentIdentificationMode: mode })
|
||||
.environmentIdentificationMode,
|
||||
).toBe(mode);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects unsupported presentation modes", () => {
|
||||
expect(() => decodeClientSettings({ environmentIdentificationMode: "badge" })).toThrow();
|
||||
expect(() => decodeClientSettingsPatch({ environmentIdentificationMode: "badge" })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ClientSettings sidebar v2", () => {
|
||||
it("defaults the beta off with a three-day auto-settle threshold", () => {
|
||||
const settings = decodeClientSettings({});
|
||||
|
||||
@@ -58,6 +58,9 @@ export const GlassOpacity = Schema.Int.check(
|
||||
);
|
||||
export type GlassOpacity = typeof GlassOpacity.Type;
|
||||
export const DEFAULT_GLASS_OPACITY: GlassOpacity = 80;
|
||||
export const EnvironmentIdentificationMode = Schema.Literals(["artwork", "pill", "none"]);
|
||||
export type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;
|
||||
export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = "artwork";
|
||||
|
||||
export const ClientSettingsSchema = Schema.Struct({
|
||||
autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
@@ -67,6 +70,9 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed([])),
|
||||
),
|
||||
diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
environmentIdentificationMode: EnvironmentIdentificationMode.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE)),
|
||||
),
|
||||
glassOpacity: GlassOpacity.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)),
|
||||
),
|
||||
@@ -641,6 +647,7 @@ export const ClientSettingsPatch = Schema.Struct({
|
||||
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
|
||||
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
|
||||
glassOpacity: Schema.optionalKey(GlassOpacity),
|
||||
favorites: Schema.optionalKey(
|
||||
Schema.Array(
|
||||
|
||||
Reference in new issue
Block a user