Skip to content

Commit bc26278

Browse files
committed
fix(mobile): update outdated servers and respect provider permissions
1 parent 07d38b8 commit bc26278

8 files changed

Lines changed: 285 additions & 35 deletions

File tree

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3+
import type { EnvironmentId } from "@t3tools/contracts";
4+
import { AsyncResult } from "effect/reactivity";
5+
import { useEffect, useRef, useState } from "react";
6+
import { View } from "react-native";
7+
8+
import { AppText as Text } from "../../components/ui/AppText";
9+
import * as Dialog from "../../components/ui/Dialog";
10+
import {
11+
describeOutdatedServer,
12+
serverEnvironment,
13+
updateOutdatedServer,
14+
} from "../../state/server";
15+
import { useAtomCommand } from "../../state/use-atom-command";
16+
import { SettingsActionRow } from "./components/SettingsActionRow";
17+
import { SettingsSection } from "./components/SettingsSection";
18+
import { findEnvironmentUpdate } from "./environment-maintenance";
19+
20+
export function OutdatedServerUpdateSection({
21+
environmentId,
22+
label,
23+
}: {
24+
readonly environmentId: EnvironmentId;
25+
readonly label: string;
26+
}) {
27+
const describe = useAtomCommand(describeOutdatedServer, { reportFailure: false });
28+
const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
29+
const state = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
30+
const [release, setRelease] = useState<{
31+
fromVersion: string;
32+
targetVersion: string | null;
33+
} | null>(null);
34+
const [checking, setChecking] = useState(false);
35+
const [error, setError] = useState<string | null>(null);
36+
const controller = useRef<AbortController | null>(null);
37+
useEffect(() => () => controller.current?.abort(), []);
38+
const busy = checking || state.status === "running";
39+
40+
async function check() {
41+
if (busy || controller.current !== null) return;
42+
const request = new AbortController();
43+
controller.current = request;
44+
setChecking(true);
45+
setError(null);
46+
const timeout = setTimeout(() => request.abort(), 20_000);
47+
const result = await settlePromise(async () => {
48+
const description = await describe(environmentId);
49+
if (AsyncResult.isFailure(description)) throw squashAtomCommandFailure(description);
50+
const fromVersion = description.value.serverVersion;
51+
const targetVersion = await findEnvironmentUpdate(fromVersion, request.signal);
52+
if (!request.signal.aborted) setRelease({ fromVersion, targetVersion });
53+
});
54+
clearTimeout(timeout);
55+
controller.current = null;
56+
setChecking(false);
57+
if (AsyncResult.isFailure(result)) {
58+
const failure = squashAtomCommandFailure(result);
59+
setError(failure instanceof Error ? failure.message : "Could not check for updates.");
60+
}
61+
}
62+
63+
function requestUpdate() {
64+
const targetVersion = release?.targetVersion;
65+
if (busy || !release || !targetVersion) return;
66+
Dialog.alert(
67+
`Update ${label}?`,
68+
`Install T3 Code ${targetVersion}. T3 Code restarts on that machine and reconnects. Running threads may be interrupted.`,
69+
[
70+
{ text: "Cancel", style: "cancel" },
71+
{
72+
text: "Update",
73+
onPress: () => {
74+
setError(null);
75+
void update({
76+
environmentId,
77+
input: { targetVersion },
78+
fromVersion: release.fromVersion,
79+
});
80+
},
81+
},
82+
],
83+
);
84+
}
85+
86+
return (
87+
<SettingsSection title="T3 Code">
88+
<View className="gap-1 p-4">
89+
<Text className="text-base text-foreground">
90+
{release ? `Version ${release.fromVersion}` : "Update required"}
91+
</Text>
92+
<Text className="text-sm text-foreground-muted">
93+
{state.status === "running"
94+
? state.stage === "resuming"
95+
? "Restarting and reconnecting…"
96+
: state.stage === "installing"
97+
? "Installing update…"
98+
: "Downloading update…"
99+
: release
100+
? release.targetVersion
101+
? `Version ${release.targetVersion} is available.`
102+
: "No newer version is available yet."
103+
: "This app needs a newer version of T3 Code on this machine."}
104+
</Text>
105+
{error || state.status === "failed" ? (
106+
<Text selectable accessibilityRole="alert" className="text-sm text-danger-foreground">
107+
{error ?? (state.status === "failed" ? state.message : null)}
108+
</Text>
109+
) : null}
110+
</View>
111+
<SettingsActionRow
112+
icon="arrow.clockwise"
113+
label="Check for updates"
114+
disabled={busy}
115+
loading={checking}
116+
onPress={() => void check()}
117+
/>
118+
{release?.targetVersion ? (
119+
<SettingsActionRow
120+
icon="arrow.up.circle"
121+
label={state.status === "failed" ? "Retry update" : `Update to ${release.targetVersion}`}
122+
disabled={busy}
123+
loading={state.status === "running"}
124+
onPress={requestUpdate}
125+
/>
126+
) : null}
127+
</SettingsSection>
128+
);
129+
}

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,14 @@ import { AppText as Text } from "../../components/ui/AppText";
1717
import { ProviderIcon } from "../../components/ProviderIcon";
1818
import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
1919
import { appAtomRegistry } from "../../state/atom-registry";
20+
import { environmentPresentations } from "../../state/presentation";
2021
import { serverEnvironment } from "../../state/server";
2122
import { environmentSession, useEnvironmentScope, readEnvironmentScope } from "../../state/session";
2223
import { useAtomCommand } from "../../state/use-atom-command";
2324
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
2425
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
2526
import { EnvironmentRoutesSection } from "./EnvironmentRoutesSection";
27+
import { OutdatedServerUpdateSection } from "./OutdatedServerUpdateSection";
2628
import { SettingsActionRow } from "./components/SettingsActionRow";
2729
import { SettingsScreen } from "./components/SettingsScreen";
2830
import { SettingsSection } from "./components/SettingsSection";
@@ -58,6 +60,9 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
5860
const session = useAtomValue(environmentSession.sessionStateValueAtom(environmentId));
5961
const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));
6062
const updateState = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
63+
const outdated =
64+
useAtomValue(environmentPresentations.presentationAtom(environmentId))?.entry
65+
.serverUpdateRequired === true;
6166
const updateServer = useAtomCommand(serverEnvironment.updateServer);
6267
const updateProvider = useAtomCommand(serverEnvironment.updateProvider);
6368
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders);
@@ -206,7 +211,12 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
206211
})
207212
}
208213
/>
209-
{!connected ? (
214+
{outdated ? (
215+
<OutdatedServerUpdateSection
216+
environmentId={environmentId}
217+
label={environment.environmentLabel}
218+
/>
219+
) : !connected ? (
210220
<Text className="px-2 text-sm text-foreground-muted">
211221
Connect this environment to manage it.
212222
</Text>
@@ -225,7 +235,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
225235
</Text>
226236
) : null}
227237
{notice ? <Text className="px-2 text-sm text-foreground-muted">{notice}</Text> : null}
228-
{config ? (
238+
{config && !outdated ? (
229239
<>
230240
<SettingsSection title="T3 Code">
231241
<View className="gap-1 p-4">

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

Lines changed: 40 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import {
44
squashAtomCommandFailure,
55
type AtomCommandResult,
66
} from "@t3tools/client-runtime/state/runtime";
7-
import type { ProviderAuthResponse, ServerProvider } from "@t3tools/contracts";
7+
import {
8+
AuthProvidersManageScope,
9+
type ProviderAuthResponse,
10+
type ServerProvider,
11+
} from "@t3tools/contracts";
812
import { useAtomValue } from "@effect/atom-react";
913
import { useRef, useState } from "react";
1014
import { Linking, Pressable, ScrollView, TextInput, View } from "react-native";
@@ -15,6 +19,7 @@ import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
1519
import { environmentPresentations } from "../../state/presentation";
1620
import { useEnvironmentQuery } from "../../state/query";
1721
import { serverEnvironment } from "../../state/server";
22+
import { useEnvironmentsWithScope } from "../../state/session";
1823
import { useAtomCommand } from "../../state/use-atom-command";
1924
import { SettingsActionRow } from "./components/SettingsActionRow";
2025
import {
@@ -27,6 +32,7 @@ import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-en
2732

2833
export function SettingsProviderAccountsRouteScreen() {
2934
const { selectedTargets } = useSettingsEnvironmentFilter();
35+
const permittedEnvironments = useEnvironmentsWithScope(selectedTargets, AuthProvidersManageScope);
3036
const providersByEnvironment = useAtomValue(environmentPresentations.providersByEnvironmentAtom);
3137
const insets = useSafeAreaInsets();
3238
return (
@@ -44,28 +50,39 @@ export function SettingsProviderAccountsRouteScreen() {
4450
) : (
4551
selectedTargets.map((environment) => (
4652
<SettingsSection key={environment.environmentId} title={environment.label}>
47-
{(providersByEnvironment.get(environment.environmentId) ?? [])
48-
.filter(
49-
(provider) =>
50-
provider.setup?.canAuthenticate ||
51-
(provider.driver === "acpRegistry" && provider.installed),
52-
)
53-
.map((provider) => (
54-
<ProviderAccount
55-
key={provider.instanceId}
56-
environment={environment}
57-
provider={provider}
58-
/>
59-
))}
60-
{!(providersByEnvironment.get(environment.environmentId) ?? []).some(
61-
(provider) =>
62-
provider.setup?.canAuthenticate ||
63-
(provider.driver === "acpRegistry" && provider.installed),
64-
) ? (
65-
<Text className="p-4 text-foreground-muted">
66-
Configure a provider with in-app sign-in in web or desktop Settings.
67-
</Text>
68-
) : null}
53+
{!permittedEnvironments.has(environment.environmentId) ? (
54+
<View className="gap-1 p-4">
55+
<Text className="text-base text-foreground">Limited permissions</Text>
56+
<Text className="text-sm text-foreground-muted">
57+
{`This session can view ${environment.label}'s providers but can't change their settings.`}
58+
</Text>
59+
</View>
60+
) : (
61+
<>
62+
{(providersByEnvironment.get(environment.environmentId) ?? [])
63+
.filter(
64+
(provider) =>
65+
provider.setup?.canAuthenticate ||
66+
(provider.driver === "acpRegistry" && provider.installed),
67+
)
68+
.map((provider) => (
69+
<ProviderAccount
70+
key={provider.instanceId}
71+
environment={environment}
72+
provider={provider}
73+
/>
74+
))}
75+
{!(providersByEnvironment.get(environment.environmentId) ?? []).some(
76+
(provider) =>
77+
provider.setup?.canAuthenticate ||
78+
(provider.driver === "acpRegistry" && provider.installed),
79+
) ? (
80+
<Text className="p-4 text-foreground-muted">
81+
Configure a provider with in-app sign-in in web or desktop Settings.
82+
</Text>
83+
) : null}
84+
</>
85+
)}
6986
</SettingsSection>
7087
))
7188
)}

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
import { createServerEnvironmentAtoms } from "@t3tools/client-runtime/state/server";
2+
import {
3+
createOutdatedServerDescriptionCommand,
4+
createOutdatedServerUpdateCommand,
5+
} from "@t3tools/client-runtime/state/outdatedServerUpdate";
26
import { createEnvironmentServerConfigsAtom } from "@t3tools/client-runtime/state/shell";
37

48
import { environmentCatalog } from "../connection/catalog";
@@ -11,6 +15,8 @@ export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRunt
1115
usageLimitSources: true,
1216
usageLimitsCommand: true,
1317
});
18+
export const describeOutdatedServer = createOutdatedServerDescriptionCommand(connectionAtomRuntime);
19+
export const updateOutdatedServer = createOutdatedServerUpdateCommand(connectionAtomRuntime);
1420
export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
1521
catalogValueAtom: environmentCatalog.catalogValueAtom,
1622
serverConfigValueAtom: serverEnvironment.configValueAtom,

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
AuthOrchestrationOperateScope,
3+
AuthProvidersManageScope,
34
EnvironmentId,
45
type AuthSessionState,
56
} from "@t3tools/contracts";
@@ -111,3 +112,25 @@ it("uses exact new-server permissions and keeps old-server grants usable", () =>
111112
appAtomRegistry.set(source(primary), AsyncResult.success(session(true)));
112113
expect(useEnvironmentScope(primary, AuthOrchestrationOperateScope)).toBe(true);
113114
});
115+
116+
it("limits provider accounts to environments granting provider management", () => {
117+
const environments = [{ environmentId: primary }, { environmentId: secondary }];
118+
const permitted = () => useEnvironmentsWithScope(environments, AuthProvidersManageScope);
119+
appAtomRegistry.set(
120+
source(primary),
121+
AsyncResult.success({ ...session(true), permissions: [AuthOrchestrationOperateScope] }),
122+
);
123+
expect(permitted()).toEqual(new Set());
124+
appAtomRegistry.set(
125+
source(secondary),
126+
AsyncResult.success({ ...session(false), permissions: [AuthProvidersManageScope] }),
127+
);
128+
expect(permitted()).toEqual(new Set([secondary]));
129+
appAtomRegistry.set(source(primary), AsyncResult.success(session(true)));
130+
expect(permitted()).toEqual(new Set([primary, secondary]));
131+
appAtomRegistry.set(
132+
source(secondary),
133+
AsyncResult.success({ ...session(true), scopes: [AuthProvidersManageScope], permissions: [] }),
134+
);
135+
expect(permitted()).toEqual(new Set([primary]));
136+
});

‎packages/client-runtime/src/connection/outdatedHostUpdate.test.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import * as Socket from "effect/socket/Socket";
1717
import type { ConnectionCatalogEntry } from "./catalog.ts";
1818
import { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
1919
import { PrimaryConnectionTarget } from "./model.ts";
20-
import { updateOutdatedHost } from "./outdatedHostUpdate.ts";
20+
import { describeOutdatedHost, updateOutdatedHost } from "./outdatedHostUpdate.ts";
2121
import * as EnvironmentRegistry from "./registry.ts";
2222
import * as ConnectionResolver from "./resolver.ts";
2323
import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
@@ -49,6 +49,47 @@ const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown
4949
const encodeJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
5050
const encodeDescriptor = Schema.encodeSync(Schema.fromJsonString(ExecutionEnvironmentDescriptor));
5151

52+
describe("describeOutdatedHost", () => {
53+
it.effect("discovers a disabled outdated host without opening a normal session", () =>
54+
Effect.gen(function* () {
55+
const expected = descriptor(undefined, "0.0.45");
56+
const result = yield* describeOutdatedHost(TARGET.environmentId).pipe(
57+
Effect.provideService(
58+
EnvironmentRegistry.EnvironmentRegistry,
59+
EnvironmentRegistry.EnvironmentRegistry.of({
60+
entries: yield* SubscriptionRef.make<
61+
ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
62+
>(
63+
new Map([
64+
[TARGET.environmentId, { target: TARGET, profile: Option.none(), enabled: false }],
65+
]),
66+
),
67+
} as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
68+
),
69+
Effect.provideService(
70+
ConnectionResolver.ConnectionResolver,
71+
ConnectionResolver.ConnectionResolver.of({
72+
prepare: () => Effect.die(new Error("normal sessions reject this protocol")),
73+
prepareForUpdate: (entry) =>
74+
Effect.succeed({
75+
descriptor: expected,
76+
prepared: {
77+
environmentId: entry.target.environmentId,
78+
label: entry.target.label,
79+
httpBaseUrl: TARGET.httpBaseUrl,
80+
socketUrl: "wss://build.example.test/ws",
81+
httpAuthorization: null,
82+
target: TARGET,
83+
},
84+
}),
85+
}),
86+
),
87+
);
88+
expect(result).toEqual(expected);
89+
}),
90+
);
91+
});
92+
5293
type Listener = (event: { readonly type: string; readonly data?: unknown }) => void;
5394

5495
class OutdatedHostSocket {

0 commit comments

Comments
 (0)