Skip to content

Commit c3f5a86

Browse files
committed
feat: let users rename environments
Store environment names on the server so every client and T3 Connect share one label. Add authorized rename controls for web, desktop, and mobile with live propagation.
1 parent ad11723 commit c3f5a86

33 files changed

Lines changed: 760 additions & 44 deletions

‎apps/mobile/src/Stack.tsx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppea
5454
import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen";
5555
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
5656
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
57+
import { SettingsEnvironmentRenameRouteScreen } from "./features/settings/SettingsEnvironmentRenameRouteScreen";
5758
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
5859
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
5960
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
@@ -630,6 +631,16 @@ export const RootStack = createNativeStackNavigator({
630631
sheetGrabberVisible: true,
631632
},
632633
}),
634+
EnvironmentRename: createNativeStackScreen({
635+
screen: SettingsEnvironmentRenameRouteScreen,
636+
linking: "environment-rename",
637+
options: {
638+
title: "Rename Environment",
639+
...FORM_SHEET_PRESENTATION_OPTIONS,
640+
sheetAllowedDetents: [0.4],
641+
sheetGrabberVisible: true,
642+
},
643+
}),
633644
NewTaskSheet: createNativeStackScreen({
634645
screen: NewTaskSheetStack,
635646
linking: "new",

‎apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx‎

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { SymbolView } from "../../components/AppSymbol";
22
import { connectionStatusText } from "@t3tools/client-runtime/connection";
33
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
4-
import type { EnvironmentId } from "@t3tools/contracts";
4+
import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
55
import * as Cause from "effect/Cause";
66
import { AsyncResult } from "effect/unstable/reactivity";
77
import { useCallback, useState } from "react";
@@ -14,6 +14,7 @@ import { cn } from "../../lib/cn";
1414
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
1515
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
1616
import { ConnectionStatusDot } from "./ConnectionStatusDot";
17+
import { useEnvironmentSessionState } from "../../state/session";
1718

1819
function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null {
1920
return connectionStatusText({
@@ -29,12 +30,12 @@ export function ConnectionEnvironmentRow(props: {
2930
readonly onToggle: () => void;
3031
readonly onReconnect: (environmentId: EnvironmentId) => void;
3132
readonly onRemove: (environmentId: EnvironmentId) => void;
33+
readonly onRename: (environmentId: EnvironmentId) => void;
3234
readonly onUpdate: (
3335
environmentId: EnvironmentId,
3436
updates: { readonly label: string; readonly displayUrl: string },
3537
) => Promise<AtomCommandResult<unknown, unknown>>;
3638
}) {
37-
const [label, setLabel] = useState(props.environment.environmentLabel);
3839
const [url, setUrl] = useState(props.environment.displayUrl);
3940

4041
const mutedColor = useThemeColor("--color-icon-subtle");
@@ -46,9 +47,16 @@ export function ConnectionEnvironmentRow(props: {
4647
const isRetrying =
4748
props.environment.connectionState === "connecting" ||
4849
props.environment.connectionState === "reconnecting";
50+
const sessionState = useEnvironmentSessionState(props.environment.environmentId);
51+
const canRename =
52+
props.environment.connectionState === "connected" &&
53+
Boolean(
54+
sessionState.data?.authenticated &&
55+
sessionState.data.scopes?.includes(AuthOrchestrationOperateScope),
56+
);
4957
const handleSave = useCallback(async () => {
5058
const result = await props.onUpdate(props.environment.environmentId, {
51-
label: label.trim(),
59+
label: "",
5260
displayUrl: url.trim(),
5361
});
5462
if (AsyncResult.isSuccess(result)) {
@@ -60,7 +68,7 @@ export function ConnectionEnvironmentRow(props: {
6068
"Could not update environment",
6169
error instanceof Error ? error.message : "The environment could not be updated.",
6270
);
63-
}, [label, url, props]);
71+
}, [url, props]);
6472

6573
return (
6674
<Animated.View layout={LinearTransition.duration(250)} className="bg-card">
@@ -114,15 +122,30 @@ export function ConnectionEnvironmentRow(props: {
114122
) : null}
115123
</View>
116124

117-
<SymbolView
118-
name="chevron.down"
119-
size={12}
120-
tintColor={mutedColor}
121-
type="monochrome"
122-
style={{
123-
transform: [{ rotate: props.expanded ? "180deg" : "0deg" }],
124-
}}
125-
/>
125+
<View className="flex-row items-center gap-2">
126+
{canRename ? (
127+
<Pressable
128+
accessibilityLabel={`Rename ${props.environment.environmentLabel}`}
129+
accessibilityRole="button"
130+
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
131+
onPress={(event) => {
132+
event.stopPropagation();
133+
props.onRename(props.environment.environmentId);
134+
}}
135+
>
136+
<SymbolView name="pencil" size={13} tintColor={mutedColor} type="monochrome" />
137+
</Pressable>
138+
) : null}
139+
<SymbolView
140+
name="chevron.down"
141+
size={12}
142+
tintColor={mutedColor}
143+
type="monochrome"
144+
style={{
145+
transform: [{ rotate: props.expanded ? "180deg" : "0deg" }],
146+
}}
147+
/>
148+
</View>
126149
</Pressable>
127150

128151
{props.expanded ? (
@@ -137,20 +160,6 @@ export function ConnectionEnvironmentRow(props: {
137160
</Text>
138161
) : (
139162
<>
140-
<View className="gap-1.5">
141-
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
142-
Label
143-
</Text>
144-
<TextInput
145-
autoCapitalize="words"
146-
autoCorrect={false}
147-
placeholder="My MacBook"
148-
value={label}
149-
onChangeText={setLabel}
150-
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"
151-
/>
152-
</View>
153-
154163
<View className="gap-1.5">
155164
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
156165
URL

‎apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,9 @@ export function ConnectionsRouteScreen() {
7979
onReconnect={onReconnectEnvironment}
8080
onRemove={onRemoveEnvironmentPress}
8181
onUpdate={onUpdateEnvironment}
82+
onRename={(environmentId) =>
83+
navigation.navigate("EnvironmentRename", { environmentId })
84+
}
8285
/>
8386
</View>
8487
))}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2+
import type { EnvironmentId } from "@t3tools/contracts";
3+
import * as Cause from "effect/Cause";
4+
import { AsyncResult } from "effect/unstable/reactivity";
5+
import { useState } from "react";
6+
import { ActivityIndicator, Alert, Pressable, View } from "react-native";
7+
8+
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
9+
import { serverEnvironment } from "../../state/server";
10+
import { useAtomCommand } from "../../state/use-atom-command";
11+
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
12+
13+
export type SettingsEnvironmentRenameParams = {
14+
readonly environmentId: EnvironmentId;
15+
};
16+
17+
export function SettingsEnvironmentRenameRouteScreen({
18+
route,
19+
}: StaticScreenProps<SettingsEnvironmentRenameParams>) {
20+
const navigation = useNavigation();
21+
const { connectedEnvironments } = useRemoteConnections();
22+
const environment = connectedEnvironments.find(
23+
(candidate) => candidate.environmentId === route.params.environmentId,
24+
);
25+
const [label, setLabel] = useState(environment?.environmentLabel ?? "");
26+
const [saving, setSaving] = useState(false);
27+
const renameEnvironment = useAtomCommand(serverEnvironment.updateEnvironmentLabel, {
28+
reportFailure: false,
29+
});
30+
31+
const save = async () => {
32+
const nextLabel = label.trim();
33+
const duplicate =
34+
nextLabel.length > 0 &&
35+
connectedEnvironments.some(
36+
(candidate) =>
37+
candidate.environmentId !== route.params.environmentId &&
38+
candidate.environmentLabel === nextLabel,
39+
);
40+
if (duplicate) {
41+
Alert.alert(
42+
"Duplicate environment name",
43+
`Another environment is already named "${nextLabel}". Use this name for both environments?`,
44+
[
45+
{ text: "Cancel", style: "cancel" },
46+
{ text: "Use Name", onPress: () => void submit(nextLabel) },
47+
],
48+
);
49+
return;
50+
}
51+
await submit(nextLabel);
52+
};
53+
54+
const submit = async (nextLabel: string) => {
55+
setSaving(true);
56+
const result = await renameEnvironment({
57+
environmentId: route.params.environmentId,
58+
input: nextLabel,
59+
});
60+
setSaving(false);
61+
if (AsyncResult.isSuccess(result)) {
62+
navigation.goBack();
63+
return;
64+
}
65+
const error = Cause.squash(result.cause);
66+
Alert.alert(
67+
"Could not rename environment",
68+
error instanceof Error ? error.message : "The environment name was not saved.",
69+
);
70+
};
71+
72+
return (
73+
<View className="flex-1 gap-5 bg-sheet px-5 pt-5">
74+
<View className="gap-1.5">
75+
<Text className="text-sm text-foreground-muted">
76+
Clear the name to use the environment's machine name.
77+
</Text>
78+
<TextInput
79+
autoFocus
80+
autoCapitalize="words"
81+
autoCorrect={false}
82+
maxLength={40}
83+
placeholder="Environment name"
84+
value={label}
85+
editable={!saving && environment !== undefined}
86+
onChangeText={setLabel}
87+
onSubmitEditing={() => void save()}
88+
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"
89+
/>
90+
</View>
91+
<View className="flex-row gap-3">
92+
<Pressable
93+
className="min-h-[46px] flex-1 items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70"
94+
disabled={saving}
95+
onPress={() => navigation.goBack()}
96+
>
97+
<Text className="font-t3-bold text-foreground">Cancel</Text>
98+
</Pressable>
99+
<Pressable
100+
className="min-h-[46px] flex-1 items-center justify-center rounded-[14px] bg-primary active:opacity-70 disabled:opacity-50"
101+
disabled={saving || environment === undefined}
102+
onPress={() => void save()}
103+
>
104+
{saving ? (
105+
<ActivityIndicator color="white" />
106+
) : (
107+
<Text className="font-t3-bold text-primary-foreground">Save</Text>
108+
)}
109+
</Pressable>
110+
</View>
111+
</View>
112+
);
113+
}

‎apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,9 @@ export function SettingsEnvironmentsRouteScreen() {
145145
onReconnect={onReconnectEnvironment}
146146
onRemove={onRemoveEnvironmentPress}
147147
onUpdate={handleUpdateEnvironment}
148+
onRename={(environmentId) =>
149+
navigation.navigate("EnvironmentRename", { environmentId })
150+
}
148151
/>
149152
</View>
150153
))}

‎apps/mobile/src/state/environments.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,16 @@ export function projectEnvironmentPresentation(
2121
environmentId: EnvironmentId,
2222
presentation: BaseEnvironmentPresentation,
2323
): EnvironmentPresentation {
24+
const displayUrl = connectionCatalogDisplayUrl(presentation.entry);
2425
return {
2526
...presentation,
2627
environmentId,
27-
label: presentation.entry.target.label,
28-
displayUrl: connectionCatalogDisplayUrl(presentation.entry),
28+
label:
29+
presentation.serverConfig?.environment.label ??
30+
(presentation.entry.target._tag === "RelayConnectionTarget"
31+
? presentation.entry.target.label
32+
: (displayUrl ?? "Environment")),
33+
displayUrl,
2934
relayManaged: presentation.entry.target._tag === "RelayConnectionTarget",
3035
};
3136
}

‎apps/mobile/src/state/session.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
22
import { createEnvironmentSessionAtoms } from "@t3tools/client-runtime/state/session";
33
import type { EnvironmentId } from "@t3tools/contracts";
44
import * as Option from "effect/Option";
5-
import { Atom } from "effect/unstable/reactivity";
5+
import { AsyncResult, Atom } from "effect/unstable/reactivity";
66

77
import { connectionAtomRuntime } from "../connection/runtime";
88

@@ -19,3 +19,11 @@ export function usePreparedConnection(environmentId: EnvironmentId | null) {
1919
: environmentSession.preparedConnectionValueAtom(environmentId),
2020
);
2121
}
22+
23+
export function useEnvironmentSessionState(environmentId: EnvironmentId) {
24+
const result = useAtomValue(environmentSession.sessionStateAtom(environmentId));
25+
return {
26+
data: Option.getOrNull(AsyncResult.value(result)),
27+
isPending: result.waiting,
28+
};
29+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import { RelayApi } from "@t3tools/contracts/relay";
2+
import * as Duration from "effect/Duration";
3+
import * as Effect from "effect/Effect";
4+
import * as Option from "effect/Option";
5+
import * as Schedule from "effect/Schedule";
6+
import * as Stream from "effect/Stream";
7+
import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
8+
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
9+
10+
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
11+
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
12+
import { relayEnvironmentClient } from "../relay/relayEnvironmentClient.ts";
13+
import * as ServerSettings from "../serverSettings.ts";
14+
import { RELAY_ENVIRONMENT_CREDENTIAL_SECRET, RELAY_URL_SECRET } from "./config.ts";
15+
16+
const retrySchedule = Schedule.exponential("1 second").pipe(
17+
Schedule.modifyDelay(({ duration }) =>
18+
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
19+
),
20+
Schedule.upTo({ duration: "10 minutes" }),
21+
);
22+
23+
export const runEnvironmentLabelRelaySync = Effect.fn("runEnvironmentLabelRelaySync")(function* () {
24+
const secrets = yield* ServerSecretStore.ServerSecretStore;
25+
const environment = yield* ServerEnvironment.ServerEnvironment;
26+
const settings = yield* ServerSettings.ServerSettingsService;
27+
28+
const readSecretString = (name: string) =>
29+
secrets.get(name).pipe(
30+
Effect.map(
31+
Option.match({
32+
onNone: () => null,
33+
onSome: (bytes) => new TextDecoder().decode(bytes),
34+
}),
35+
),
36+
);
37+
38+
const synchronize = Effect.fn("synchronizeEnvironmentLabel")(function* (
39+
environmentLabel: string,
40+
) {
41+
// Apply the triggering setting before reading the descriptor. The
42+
// general descriptor watcher runs independently and may not have seen
43+
// this settings event yet.
44+
yield* environment.setEnvironmentLabel(environmentLabel);
45+
const [relayUrl, environmentCredential] = yield* Effect.all([
46+
readSecretString(RELAY_URL_SECRET),
47+
readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
48+
]);
49+
if (!relayUrl || !environmentCredential) return;
50+
51+
const descriptor = yield* environment.getDescriptor;
52+
const client = yield* HttpApiClient.make(RelayApi, {
53+
baseUrl: relayUrl,
54+
transformClient: relayEnvironmentClient(environmentCredential),
55+
}).pipe(Effect.provide(FetchHttpClient.layer));
56+
yield* client.server.updateEnvironmentLabel({
57+
params: { environmentId: descriptor.environmentId },
58+
payload: { label: descriptor.label },
59+
});
60+
yield* Effect.logDebug("synchronized environment label with relay", {
61+
environmentId: descriptor.environmentId,
62+
});
63+
});
64+
65+
const changes = yield* settings.subscribeChanges;
66+
const initialSettings = yield* settings.getSettings;
67+
const synchronizeWithRetry = (environmentLabel: string) =>
68+
synchronize(environmentLabel).pipe(
69+
Effect.retry({ schedule: retrySchedule }),
70+
Effect.catch((cause) =>
71+
Effect.logWarning("failed to synchronize environment label with relay", { cause }),
72+
),
73+
);
74+
75+
yield* synchronizeWithRetry(initialSettings.environmentLabel);
76+
yield* changes.pipe(
77+
Stream.map((next) => next.environmentLabel),
78+
Stream.changes,
79+
Stream.runForEach(synchronizeWithRetry),
80+
);
81+
});

0 commit comments

Comments
 (0)