Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions apps/web/src/components/settings/RenameEnvironmentDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { useState } from "react";

import { environmentCatalog } from "~/connection/catalog";
import { useAtomCommand } from "~/state/use-atom-command";
import { Button } from "../ui/button";
import {
Dialog,
DialogClose,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input";
import { Label } from "../ui/label";

// The popup unmounts when closed, so each open starts from the current label.
function RenameEnvironmentForm({
environmentId,
label: currentLabel,
onDone,
}: {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly onDone: () => void;
}) {
const [label, setLabel] = useState(currentLabel);
const setEnvironmentLabel = useAtomCommand(environmentCatalog.setLabel, "Rename environment");
const canSave = label.trim() !== "";

const save = async () => {
if (!canSave) return;
const result = await setEnvironmentLabel({ environmentId, label });
if (result._tag === "Success") onDone();
};

return (
<>
<DialogHeader>
<DialogTitle>Rename environment</DialogTitle>
</DialogHeader>
<DialogPanel>
<form
id="rename-environment-form"
className="grid gap-1.5"
onSubmit={(event) => {
event.preventDefault();
void save();
}}
>
<Label htmlFor="environment-label">Label</Label>
<Input
id="environment-label"
value={label}
onChange={(event) => setLabel(event.target.value)}
autoFocus
/>
</form>
</DialogPanel>
<DialogFooter variant="bare">
<DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
<Button type="submit" form="rename-environment-form" disabled={!canSave}>
Save
</Button>
</DialogFooter>
</>
);
}

export function RenameEnvironmentDialog({
open,
onOpenChange,
environmentId,
label,
}: {
readonly open: boolean;
readonly onOpenChange: (open: boolean) => void;
readonly environmentId: EnvironmentId;
readonly label: string;
}) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogPopup className="max-w-md">
<RenameEnvironmentForm
environmentId={environmentId}
label={label}
onDone={() => onOpenChange(false)}
/>
</DialogPopup>
</Dialog>
);
}
15 changes: 15 additions & 0 deletions apps/web/src/components/settings/SavedEnvironmentRows.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ChevronRightIcon,
ChevronsLeftRightEllipsisIcon,
EllipsisIcon,
PencilIcon,
RouteIcon,
} from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
Expand All @@ -29,6 +30,7 @@ import { SettingsRow } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
import { EnvironmentRoutesList } from "./EnvironmentRoutesList";
import { RenameEnvironmentDialog } from "./RenameEnvironmentDialog";
import {
ConnectionDiagnosisPanel,
ConnectionDiagnosisSummary,
Expand Down Expand Up @@ -117,6 +119,7 @@ export function SavedBackendListRow({
const [routesOpen, setRoutesOpen] = useState(false);
const [permissionsOpen, setPermissionsOpen] = useState(false);
const [diagnosisOpen, setDiagnosisOpen] = useState(false);
const [renameOpen, setRenameOpen] = useState(false);
const environmentId = environment.environmentId;
const unsupported = environment.connection.phase === "unsupported";
const blocked = unsupported && !hasSavedBearerRoute(environment.entry);
Expand Down Expand Up @@ -413,6 +416,12 @@ export function SavedBackendListRow({
environmentId={environmentId}
serverConfig={environment.serverConfig}
/>
{environment.relayManaged ? null : (
<MenuItem onClick={() => setRenameOpen(true)}>
<PencilIcon />
Rename…
</MenuItem>
)}
<MenuItem onClick={() => setRoutesOpen((open) => !open)}>
<RouteIcon />
{routesOpen ? "Hide routes" : "Routes"}
Expand All @@ -429,6 +438,12 @@ export function SavedBackendListRow({
</MenuItem>
</MenuPopup>
</Menu>
<RenameEnvironmentDialog
open={renameOpen}
onOpenChange={setRenameOpen}
environmentId={environmentId}
label={environment.label}
/>
</EnvironmentRow>
);
}
Expand Down
48 changes: 48 additions & 0 deletions packages/client-runtime/src/connection/registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2196,6 +2196,51 @@ describe("EnvironmentRegistry routes", () => {
}),
);

it.effect("renames every route and keeps credentials and learned state", () =>
Effect.gen(function* () {
const environmentId = LAN_TARGET.environmentId;
const learnedId = `learned:${environmentId}:http://100.64.0.9:3773@${LAN_TARGET.connectionId}`;
const harness = yield* makeHarness(
[
new BearerConnectionTarget({ ...LAN_TARGET, connectionId: learnedId }),
LAN_TARGET,
RELAY_TARGET,
],
[
new BearerConnectionProfile({ ...LAN_PROFILE, connectionId: learnedId, learned: true }),
LAN_PROFILE,
],
[[LAN_TARGET.connectionId, BEARER_CREDENTIAL]],
);
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
yield* registry.setLabel(environmentId, " Studio ");

expect(
routesOf(yield* Ref.get(harness.storedTargets), environmentId).map((target) => [
target._tag,
target.label,
]),
).toEqual([
["BearerConnectionTarget", "Studio"],
["BearerConnectionTarget", "Studio"],
["RelayConnectionTarget", "Studio"],
]);
const profiles = yield* Ref.get(harness.storedProfiles);
expect(profiles.get(learnedId)).toMatchObject({ label: "Studio", learned: true });
expect(profiles.get(LAN_TARGET.connectionId)?.label).toBe("Studio");
expect((yield* Ref.get(harness.storedCredentials)).get(LAN_TARGET.connectionId)).toEqual(
BEARER_CREDENTIAL,
);
const entry = (yield* SubscriptionRef.get(registry.entries)).get(environmentId);
expect(entry?.target.label).toBe("Studio");

const error = yield* registry.setLabel(environmentId, " ").pipe(Effect.flip);
expect(error._tag).toBe("ConnectionBlockedError");
}).pipe(Effect.provide(harness.layer), Effect.scoped);
}),
);

it.effect("removing the last route forgets the environment", () =>
Effect.gen(function* () {
const harness = yield* makeHarness(
Expand Down Expand Up @@ -2246,6 +2291,9 @@ describe("EnvironmentRegistry routes", () => {
LAN_TARGET.connectionId,
]);
expect(yield* permissions.get(yield* current())).toBe("read");

yield* registry.setLabel(LAN_TARGET.environmentId, "Studio");
expect(yield* permissions.get(yield* current())).toBe("read");
}).pipe(
Effect.provide(harness.layer),
Effect.provideService(PullRequestRoutingPermissions, permissions),
Expand Down
39 changes: 39 additions & 0 deletions packages/client-runtime/src/connection/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import {
findRouteToSameAddress,
hasSavedBearerRoute,
mergeLearnedRoutes,
routeWithLabel,
routesAfterRemoving,
upsertRoute,
type ReportedEndpoint,
Expand Down Expand Up @@ -151,6 +152,16 @@ export class EnvironmentRegistry extends Context.Service<
| PlatformEnvironmentRemovalError
| ConnectionBlockedError
>;
readonly setLabel: (
environmentId: EnvironmentId,
label: string,
) => Effect.Effect<
void,
| Persistence.ConnectionPersistenceError
| ConnectionAttemptError
| EnvironmentNotRegisteredError
| PlatformEnvironmentRemovalError
>;
readonly removeRelayEnvironments: () => Effect.Effect<
void,
| Persistence.ConnectionPersistenceError
Expand Down Expand Up @@ -1025,6 +1036,33 @@ export const make = Effect.gen(function* () {
);
});

const setLabel = Effect.fn("EnvironmentRegistry.setLabel")(function* (
environmentId: EnvironmentId,
label: string,
) {
const trimmed = label.trim();
if (trimmed === "") {
return yield* new ConnectionBlockedError({
reason: "configuration",
detail: "Environment label cannot be empty.",
});
}
yield* withLeaseLock(
environmentId,
Effect.gen(function* () {
const entry = yield* userEntry(environmentId);
const routes = connectionRoutes(entry);
if (routes.every((route) => route.target.label === trimmed)) return;
// Every route carries the label: the first one is displayed, and reordering can change it.
const renamed = routes.map((route) => routeWithLabel(route, trimmed));
for (const route of renamed) {
if (Option.isSome(route.profile)) yield* profiles.put(route.profile.value);
}
yield* replaceRoutesLocked(entry, renamed);
}),
);
});

const removeRelayEnvironments = Effect.fn("EnvironmentRegistry.removeRelayEnvironments")(
function* () {
const relayEnvironmentIds = [...(yield* SubscriptionRef.get(entries)).values()]
Expand Down Expand Up @@ -1193,6 +1231,7 @@ export const make = Effect.gen(function* () {
remove,
removeRoute,
reorderRoutes,
setLabel,
removeRelayEnvironments,
retryNow,
setEnabled,
Expand Down
33 changes: 32 additions & 1 deletion packages/client-runtime/src/connection/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,15 @@ import {
BearerConnectionProfile,
type ConnectionCatalogEntry,
type ConnectionRoute,
SshConnectionProfile,
} from "./catalog.ts";
import { BearerConnectionTarget, type ConnectionTarget } from "./model.ts";
import {
BearerConnectionTarget,
type ConnectionTarget,
PrimaryConnectionTarget,
RelayConnectionTarget,
SshConnectionTarget,
} from "./model.ts";

export type ConnectionRouteKind =
| "relay"
Expand Down Expand Up @@ -65,6 +72,30 @@ export function routeEntry(
return entryWithRoutes(entry, [route]);
}

function targetWithLabel(target: ConnectionTarget, label: string): ConnectionTarget {
switch (target._tag) {
case "PrimaryConnectionTarget":
return new PrimaryConnectionTarget({ ...target, label });
case "BearerConnectionTarget":
return new BearerConnectionTarget({ ...target, label });
case "RelayConnectionTarget":
return new RelayConnectionTarget({ ...target, label });
case "SshConnectionTarget":
return new SshConnectionTarget({ ...target, label });
}
}

export function routeWithLabel(route: ConnectionRoute, label: string): ConnectionRoute {
return {
target: targetWithLabel(route.target, label),
profile: Option.map(route.profile, (profile) =>
profile._tag === "SshConnectionProfile"
? new SshConnectionProfile({ ...profile, label })
: new BearerConnectionProfile({ ...profile, label }),
),
};
}

export function routeHttpBaseUrl(route: ConnectionRoute): string | null {
if (route.target._tag === "PrimaryConnectionTarget") return route.target.httpBaseUrl;
const profile = Option.getOrNull(route.profile);
Expand Down
10 changes: 10 additions & 0 deletions packages/client-runtime/src/state/connections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,15 @@ export function createEnvironmentCatalogAtoms<R, E>(
Effect.flatMap((registry) => registry.reorderRoutes(input.environmentId, input.routeIds)),
),
});
const setLabel = createRuntimeCommand(runtime, {
label: "environment-catalog:set-label",
scheduler: commandScheduler,
concurrency: serial,
execute: (input: { readonly environmentId: EnvironmentIdType; readonly label: string }) =>
EnvironmentRegistry.EnvironmentRegistry.pipe(
Effect.flatMap((registry) => registry.setLabel(input.environmentId, input.label)),
),
});
const retryNow = createRuntimeCommand(runtime, {
label: "environment-catalog:retry-now",
scheduler: commandScheduler,
Expand All @@ -208,5 +217,6 @@ export function createEnvironmentCatalogAtoms<R, E>(
removeRelayEnvironments,
retryNow,
setEnabled,
setLabel,
};
}
1 change: 1 addition & 0 deletions packages/client-runtime/src/state/threads-atoms.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?
remove: () => Effect.die("Unexpected environment removal"),
removeRoute: () => Effect.die("Unexpected route removal"),
reorderRoutes: () => Effect.die("Unexpected route reorder"),
setLabel: () => Effect.die("Unexpected label update"),
removeRelayEnvironments: () => Effect.die("Unexpected environment removal"),
retryNow: () => Effect.void,
setEnabled: () => Effect.die("Unexpected environment toggle"),
Expand Down
Loading