The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 633 lines 23.1 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import { msg, useGT, useMessages } from "gt-react-native";
3 import * as Dialog from "../../components/ui/Dialog";
4 import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
5 import {
6 AuthRelayConfigureScope,
7 AuthRelayWriteScope,
8 type EnvironmentId,
9 } from "@t3tools/contracts";
10 import { readEnvironmentScope } from "../../state/session";
11 import { appAtomRegistry } from "../../state/atom-registry";
12 import { serverEnvironment } from "../../state/server";
13 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
14 import { useAuth } from "@clerk/expo";
15 import { useAtomSet, useAtomValue } from "@effect/atom-react";
16 import * as Notifications from "expo-notifications";
17 import { useNavigation } from "@react-navigation/native";
18 import * as Cause from "effect/Cause";
19 import * as Effect from "effect/Effect";
20 import * as Exit from "effect/Exit";
21 import * as Schema from "effect/Schema";
22 import { AsyncResult } from "effect/reactivity";
23 import { useRef, useState, useSyncExternalStore } from "react";
24 import { Linking, Platform } from "react-native";
25 import { useSafeAreaInsets } from "react-native-safe-area-context";
26 import { m as resolveMessage } from "../../i18n/messages";
27
28 import { AppText as Text } from "../../components/ui/AppText";
29 import {
30 createEnvironmentCommand,
31 isAtomCommandInterrupted,
32 reportAtomCommandResult,
33 settleAsyncResult,
34 settlePromise,
35 squashAtomCommandFailure,
36 } from "@t3tools/client-runtime/state/runtime";
37 import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities";
38 import {
39 openAndroidLiveUpdateSettings,
40 supportsAndroidLiveUpdateSettings,
41 } from "../agent-awareness/androidNotifications";
42 import {
43 LiveActivityEnvironmentUpdateError,
44 setLiveActivityUpdatesEnabled,
45 } from "../agent-awareness/liveActivityPreferences";
46 import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
47 import {
48 agentAwarenessNotificationsReady,
49 getAgentAwarenessRegistrationStatus,
50 refreshAgentAwarenessRegistration,
51 subscribeAgentAwarenessRegistrationStatus,
52 } from "../agent-awareness/remoteRegistration";
53 import { connectionAtomRuntime } from "../../connection/runtime";
54 import {
55 CloudEnvironmentLinkError,
56 linkEnvironmentToCloudWithPreference,
57 updateLinkedEnvironmentLiveActivityPreference,
58 } from "../cloud/linkEnvironment";
59 import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
60 import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
61 import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
62 import { runtime } from "../../lib/runtime";
63 import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences";
64 import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
65 import { SettingsRow } from "./components/SettingsRow";
66 import { SettingsSection } from "./components/SettingsSection";
67 import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
68 import { SettingsScreen } from "./components/SettingsScreen";
69 import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
70
71 const updateLiveActivityPreference = createEnvironmentCommand(connectionAtomRuntime, {
72 label: "updateLiveActivityPreference",
73 execute: updateLinkedEnvironmentLiveActivityPreference,
74 });
75
76 const linkLiveActivityEnvironment = createEnvironmentCommand(connectionAtomRuntime, {
77 label: "linkLiveActivityEnvironment",
78 execute: linkEnvironmentToCloudWithPreference,
79 });
80
81 const isLiveActivityEnvironmentUpdateError = Schema.is(LiveActivityEnvironmentUpdateError);
82 const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
83
84 function toCloudEnvironmentLinkError(cause: unknown, message: string) {
85 return isCloudEnvironmentLinkError(cause)
86 ? cause
87 : new CloudEnvironmentLinkError({ message, cause });
88 }
89
90 const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* (
91 environmentId: EnvironmentId,
92 enabled: boolean,
93 ) {
94 const exit = yield* Effect.exit(
95 updateLiveActivityPreference.run(appAtomRegistry, { environmentId, input: enabled }),
96 );
97 if (Exit.isSuccess(exit)) return exit.value;
98 return yield* toCloudEnvironmentLinkError(
99 Cause.squash(exit.cause),
100 resolveMessage(msg("Could not update the environment's Live Activity preference.")),
101 );
102 });
103
104 const saveLocalPreference = (liveActivitiesEnabled: boolean) =>
105 saveMobilePreferences.run(appAtomRegistry, { liveActivitiesEnabled });
106
107 const linkEnvironmentWithPreference = Effect.fn("linkEnvironmentWithPreference")(function* (
108 environmentId: EnvironmentId,
109 input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean },
110 ) {
111 const exit = yield* Effect.exit(
112 linkLiveActivityEnvironment.run(appAtomRegistry, { environmentId, input }),
113 );
114 if (Exit.isSuccess(exit)) return;
115 return yield* toCloudEnvironmentLinkError(
116 Cause.squash(exit.cause),
117 resolveMessage(msg("Could not configure environment relay access.")),
118 );
119 });
120
121 /**
122 * A policy that turns Connect off refuses relay links and preferences, which would fail the
123 * whole batch, so those environments are skipped like ones this session cannot configure.
124 */
125 function canManageConnect(
126 environmentId: EnvironmentId,
127 scope: typeof AuthRelayConfigureScope | typeof AuthRelayWriteScope,
128 ) {
129 const policy = appAtomRegistry.get(
130 serverEnvironment.configValueAtom(environmentId),
131 )?.managedPolicy;
132 return (
133 readEnvironmentScope(environmentId, scope) &&
134 managedCapabilityDenial(policy, "connect") === undefined
135 );
136 }
137
138 type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
139 type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
140
141 const notificationStatusAtom = makePermissionStatusAtom<NotificationStatus>({
142 label: "mobile:notification-permission",
143 initial: "checking",
144 read: async () => {
145 if (Platform.OS !== "ios" && Platform.OS !== "android") return "unsupported";
146 const result = await settlePromise(() => Notifications.getPermissionsAsync());
147 if (result._tag === "Failure") {
148 reportAtomCommandResult(result, { label: "notification permission refresh" });
149 return "disabled";
150 }
151 return result.value.granted ? "enabled" : "disabled";
152 },
153 });
154
155 type LiveActivityBasis = {
156 readonly isLoaded: boolean;
157 readonly isSignedIn: boolean | undefined;
158 readonly preferencesResult: unknown;
159 };
160
161 function liveActivityStatusFrom(
162 isLoaded: boolean,
163 isSignedIn: boolean | undefined,
164 preferencesResult: AsyncResult.AsyncResult<{ readonly liveActivitiesEnabled?: boolean }, unknown>,
165 ): LiveActivityStatus {
166 if (!isLoaded) return "checking";
167 if (!isSignedIn) return "signed-out";
168 if (AsyncResult.isFailure(preferencesResult)) return "enabled";
169 if (!AsyncResult.isSuccess(preferencesResult)) return "checking";
170 return preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled";
171 }
172
173 function useDeviceRegistered(): boolean {
174 const status = useSyncExternalStore(
175 subscribeAgentAwarenessRegistrationStatus,
176 getAgentAwarenessRegistrationStatus,
177 () => "unknown" as const,
178 );
179 return status === "registered";
180 }
181
182 function useNotificationsReady(): boolean {
183 return useSyncExternalStore(
184 subscribeAgentAwarenessRegistrationStatus,
185 agentAwarenessNotificationsReady,
186 () => false,
187 );
188 }
189
190 export function SettingsNotificationsRouteScreen() {
191 const gt = useGT();
192 if (!hasCloudPublicConfig()) {
193 return (
194 <SettingsScreen title={gt("Notifications")}>
195 <ScrollView
196 contentInsetAdjustmentBehavior="automatic"
197 contentContainerClassName="px-5 pt-4"
198 >
199 <Text className="text-base text-foreground-muted">
200 {gt("Notifications require {product} in this app build.", { product: "T3 Connect" })}
201 </Text>
202 </ScrollView>
203 </SettingsScreen>
204 );
205 }
206
207 return <ConfiguredSettingsNotificationsRouteScreen />;
208 }
209
210 function ConfiguredSettingsNotificationsRouteScreen() {
211 const gt = useGT();
212 const m = useMessages();
213 const preferencesResult = useAtomValue(mobilePreferencesAtom);
214 const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
215 const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS, m);
216 const agentAwarenessSubtitle =
217 Platform.OS === "android" && !agentAwarenessPushAvailable
218 ? gt("Install a newer app build to enable notifications")
219 : agentAwarenessPlatform.subtitle;
220 const insets = useSafeAreaInsets();
221 const navigation = useNavigation();
222 const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
223 const { savedConnectionsById } = useSavedRemoteConnections();
224 const notificationStatus = useAtomValue(notificationStatusAtom);
225 const setNotificationStatus = useAtomSet(notificationStatusAtom);
226 // A write in progress or a failed one shows its own status until the auth or
227 // preference state it was based on changes.
228 const [liveActivityOverride, setLiveActivityOverride] = useState<{
229 readonly status: LiveActivityStatus;
230 readonly basis: LiveActivityBasis;
231 } | null>(null);
232 const liveActivityBasis: LiveActivityBasis = { isLoaded, isSignedIn, preferencesResult };
233 const liveActivityStatus =
234 liveActivityOverride !== null &&
235 liveActivityOverride.basis.isLoaded === isLoaded &&
236 liveActivityOverride.basis.isSignedIn === isSignedIn &&
237 liveActivityOverride.basis.preferencesResult === preferencesResult
238 ? liveActivityOverride.status
239 : liveActivityStatusFrom(isLoaded, isSignedIn, preferencesResult);
240 const setLiveActivityStatus = (status: LiveActivityStatus) =>
241 setLiveActivityOverride({ status, basis: liveActivityBasis });
242 const liveActivityWriteInFlight = useRef(false);
243 const deviceRegistered = useDeviceRegistered();
244 const notificationsReady = useNotificationsReady();
245 const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
246 ? preferencesResult.value.liveActivitiesEnabled !== false
247 : true;
248 const canClearLiveActivitiesPreference =
249 AsyncResult.isSuccess(preferencesResult) &&
250 preferencesResult.value.liveActivitiesEnabled !== false;
251
252 const connections = Object.values(savedConnectionsById);
253 const environmentCount = connections.length;
254
255 const requestNotifications = async () => {
256 const result = await settleAsyncResult(() =>
257 runtime.runPromiseExit(
258 requestAgentNotificationPermission.pipe(
259 Effect.tap((permission) =>
260 permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
261 ),
262 ),
263 ),
264 );
265 if (result._tag === "Failure") {
266 if (!isAtomCommandInterrupted(result)) {
267 const error = squashAtomCommandFailure(result);
268 Dialog.alert(
269 gt("Notifications unavailable"),
270 error instanceof Error
271 ? (errorDisplayMessage(error, resolveMessage) ?? error.message)
272 : gt("Could not request notification permission."),
273 );
274 }
275 return;
276 }
277 if (result.value.type === "granted") {
278 setNotificationStatus("enabled");
279 if (!agentAwarenessNotificationsReady()) {
280 Dialog.alert(
281 gt("Couldn't finish enabling notifications"),
282 gt(
283 "Notification access was granted, but this device could not be registered with {product}. Notifications will start once registration succeeds.",
284 { product: "T3 Connect" },
285 ),
286 );
287 }
288 return;
289 }
290 if (result.value.type === "unsupported") {
291 setNotificationStatus("unsupported");
292 Dialog.alert(
293 gt("Notifications unavailable"),
294 gt("Agent notifications are unavailable on this platform."),
295 );
296 return;
297 }
298 setNotificationStatus("disabled");
299 if (result.value.canAskAgain) {
300 Dialog.alert(gt("Notifications disabled"), gt("Notifications were not enabled."));
301 return;
302 }
303 Dialog.alert(
304 gt("Notifications disabled"),
305 gt("Notifications were denied for this app. Open Settings to enable them."),
306 [
307 { text: gt("Cancel"), style: "cancel" },
308 { text: gt("Open Settings"), onPress: () => void Linking.openSettings() },
309 ],
310 );
311 };
312
313 const promptSignIn = () => {
314 Dialog.alert(
315 gt("Sign in to {product}", { product: "T3 Connect" }),
316 gt("Live Activity updates require {product} so relay can deliver updates to this device.", {
317 product: "T3 Connect",
318 }),
319 [
320 { text: gt("Cancel"), style: "cancel" },
321 {
322 text: gt("Continue"),
323 onPress: () => navigation.navigate("SettingsAuth"),
324 },
325 ],
326 );
327 };
328
329 const linkEnvironments = async () => {
330 if (!isSignedIn) {
331 promptSignIn();
332 return;
333 }
334
335 setLiveActivityStatus("linking");
336 if (Platform.OS === "android") {
337 const permission = await settleAsyncResult(() =>
338 runtime.runPromiseExit(requestAgentNotificationPermission),
339 );
340 if (permission._tag === "Failure") {
341 setLiveActivityStatus("disabled");
342 const error = squashAtomCommandFailure(permission);
343 Dialog.alert(
344 gt("Ongoing activity unavailable"),
345 error instanceof Error
346 ? (errorDisplayMessage(error, resolveMessage) ?? error.message)
347 : gt("Could not enable agent notifications."),
348 );
349 return;
350 }
351 if (permission.value.type !== "granted") {
352 setLiveActivityStatus("disabled");
353 Dialog.alert(
354 gt("Notification permission needed"),
355 gt("Enable notifications in system Settings to show ongoing agent activity."),
356 [
357 { text: gt("Cancel"), style: "cancel" },
358 { text: gt("Open Settings"), onPress: () => void Linking.openSettings() },
359 ],
360 );
361 return;
362 }
363 setNotificationStatus("enabled");
364 }
365 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
366 if (tokenResult._tag === "Failure") {
367 setLiveActivityStatus("disabled");
368 const error = squashAtomCommandFailure(tokenResult);
369 Dialog.alert(
370 Platform.OS === "android"
371 ? gt("Ongoing activity unavailable")
372 : gt("Live Activities unavailable"),
373 error instanceof Error
374 ? (errorDisplayMessage(error, resolveMessage) ?? error.message)
375 : gt("Could not enable agent activity updates."),
376 );
377 return;
378 }
379 if (!tokenResult.value) {
380 promptSignIn();
381 setLiveActivityStatus("signed-out");
382 return;
383 }
384
385 const updateResult = await settleAsyncResult(() =>
386 runtime.runPromiseExit(
387 setLiveActivityUpdatesEnabled({
388 updateEnvironment: updateEnvironmentPreference,
389 linkEnvironment: linkEnvironmentWithPreference,
390 saveLocalPreference,
391 canConfigureEnvironment: (id) =>
392 canManageConnect(id, AuthRelayConfigureScope) &&
393 canManageConnect(id, AuthRelayWriteScope),
394 canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope),
395 enabled: true,
396 previousEnabled: liveActivitiesPreferenceEnabled,
397 clerkToken: tokenResult.value,
398 connections,
399 }),
400 ),
401 );
402 if (updateResult._tag === "Failure") {
403 setLiveActivityStatus("disabled");
404 if (!isAtomCommandInterrupted(updateResult)) {
405 const error = squashAtomCommandFailure(updateResult);
406 if (reportPartialEnvironmentUpdate(error)) return;
407 Dialog.alert(
408 Platform.OS === "android"
409 ? gt("Ongoing activity unavailable")
410 : gt("Live Activities unavailable"),
411 error instanceof Error
412 ? (errorDisplayMessage(error, resolveMessage) ?? error.message)
413 : gt("Could not enable agent activity updates."),
414 );
415 }
416 return;
417 }
418
419 refreshManagedRelayEnvironments();
420 setLiveActivityStatus("enabled");
421 // Environment linking can precede device registration; only registered devices can receive Live Activities.
422 if (updateResult.value) {
423 Dialog.alert(
424 gt("Some environments need an update"),
425 gt(
426 "The device preference was saved. Update older environment servers to apply the setting there.",
427 ),
428 );
429 } else if (getAgentAwarenessRegistrationStatus() === "registered") {
430 Dialog.alert(
431 Platform.OS === "android" ? gt("Ongoing activity enabled") : gt("Live Activities enabled"),
432 environmentCount > 0
433 ? gt("Agent activity updates are enabled for eligible environments.")
434 : gt(
435 "Agent activity updates are enabled. Add an environment to start receiving updates.",
436 ),
437 );
438 } else {
439 Dialog.alert(
440 gt("Couldn't finish enabling activity updates"),
441 gt(
442 "This device could not be registered with {product}, so activity updates won't appear yet. They'll start once registration succeeds.",
443 { product: "T3 Connect" },
444 ),
445 );
446 }
447 };
448
449 const handleDeviceNotificationsChange = (enabled: boolean) => {
450 if (enabled) {
451 if (!isSignedIn) {
452 promptSignIn();
453 return;
454 }
455 void requestNotifications();
456 return;
457 }
458
459 Dialog.alert(
460 gt("Disable notifications"),
461 gt("Open system Settings to disable notifications for {product}.", { product: "T3 Code" }),
462 [
463 { text: gt("Cancel"), style: "cancel" },
464 { text: gt("Open Settings"), onPress: () => void Linking.openSettings() },
465 ],
466 );
467 };
468
469 async function disableLiveActivities() {
470 let token: string | null = null;
471 if (isSignedIn) {
472 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
473 if (tokenResult._tag === "Failure") {
474 setLiveActivityStatus("enabled");
475 reportAtomCommandResult(tokenResult, {
476 label: "live activity disable token lookup",
477 });
478 return;
479 }
480 token = tokenResult.value;
481 }
482
483 const updateResult = await settleAsyncResult(() =>
484 runtime.runPromiseExit(
485 setLiveActivityUpdatesEnabled({
486 updateEnvironment: updateEnvironmentPreference,
487 linkEnvironment: linkEnvironmentWithPreference,
488 saveLocalPreference,
489 canConfigureEnvironment: (id) =>
490 canManageConnect(id, AuthRelayConfigureScope) &&
491 canManageConnect(id, AuthRelayWriteScope),
492 canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope),
493 enabled: false,
494 previousEnabled: liveActivitiesPreferenceEnabled,
495 clerkToken: token,
496 connections,
497 }),
498 ),
499 );
500 if (updateResult._tag === "Failure") {
501 setLiveActivityStatus(isSignedIn ? "enabled" : "signed-out");
502 if (!reportPartialEnvironmentUpdate(squashAtomCommandFailure(updateResult))) {
503 reportAtomCommandResult(updateResult, {
504 label: "live activity disable",
505 });
506 }
507 return;
508 }
509 refreshManagedRelayEnvironments();
510 setLiveActivityStatus("disabled");
511 if (updateResult.value) {
512 Dialog.alert(
513 gt("Some environments need an update"),
514 gt(
515 "The device preference was saved. Update older environment servers to apply the setting there.",
516 ),
517 );
518 }
519 }
520
521 function reportPartialEnvironmentUpdate(error: unknown): boolean {
522 if (!isLiveActivityEnvironmentUpdateError(error)) return false;
523 refreshManagedRelayEnvironments();
524 Dialog.alert(
525 gt("Some environments were updated"),
526 gt("The device setting was not saved. The new setting was applied to: {environments}.", {
527 environments: error.updatedEnvironments.join(", "),
528 }),
529 );
530 return true;
531 }
532
533 // Both writers settle their own failures, so awaiting them never throws.
534 const handleLiveActivitiesChange = async (enabled: boolean) => {
535 if (liveActivityWriteInFlight.current) return;
536 if (!enabled) {
537 liveActivityWriteInFlight.current = true;
538 setLiveActivityStatus("linking");
539 await disableLiveActivities();
540 liveActivityWriteInFlight.current = false;
541 return;
542 }
543
544 if (!isSignedIn) {
545 promptSignIn();
546 return;
547 }
548
549 liveActivityWriteInFlight.current = true;
550 await linkEnvironments();
551 liveActivityWriteInFlight.current = false;
552 };
553
554 return (
555 <SettingsScreen title={gt("Notifications")}>
556 <ScrollView
557 contentInsetAdjustmentBehavior="automatic"
558 showsVerticalScrollIndicator={false}
559 className="flex-1"
560 contentContainerClassName="gap-6 px-5 pt-4"
561 contentContainerStyle={{
562 paddingBottom: Math.max(insets.bottom, 18) + 18,
563 }}
564 >
565 <SettingsSection title={gt("Agent activity")}>
566 <SettingsSwitchRow
567 icon="bell.badge"
568 label={gt("Device Notifications")}
569 disabled={
570 !agentAwarenessPlatform.supported ||
571 !agentAwarenessPushAvailable ||
572 notificationStatus === "checking" ||
573 notificationStatus === "unsupported"
574 }
575 subtitle={agentAwarenessSubtitle}
576 value={
577 agentAwarenessPushAvailable && notificationStatus === "enabled" && notificationsReady
578 }
579 onValueChange={handleDeviceNotificationsChange}
580 />
581 <SettingsSwitchRow
582 disabled={
583 !agentAwarenessPlatform.supported ||
584 !agentAwarenessPushAvailable ||
585 !isLoaded ||
586 liveActivityStatus === "checking" ||
587 liveActivityStatus === "linking"
588 }
589 icon="bolt.circle"
590 label={
591 Platform.OS === "android"
592 ? supportsAndroidLiveUpdateSettings()
593 ? gt("Agent Live Updates")
594 : gt("Ongoing Agent Activity")
595 : gt("Live Activity Updates")
596 }
597 subtitle={agentAwarenessSubtitle}
598 value={
599 agentAwarenessPushAvailable &&
600 (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&
601 deviceRegistered
602 }
603 onValueChange={(enabled) => void handleLiveActivitiesChange(enabled)}
604 />
605 {liveActivityStatus === "signed-out" && canClearLiveActivitiesPreference ? (
606 <SettingsRow
607 icon="bolt.circle"
608 label={gt("Turn off Live Activity preference")}
609 onPress={() => void handleLiveActivitiesChange(false)}
610 />
611 ) : null}
612 {supportsAndroidLiveUpdateSettings() ? (
613 <SettingsRow
614 icon="bolt.circle"
615 label={gt("Live Update Settings")}
616 onPress={() => {
617 void openAndroidLiveUpdateSettings().catch(() => {
618 Dialog.alert(
619 gt("Couldn't open Settings"),
620 gt(
621 "Open Android Settings, select {product}, then enable Live Updates in Notifications.",
622 { product: "T3 Code" },
623 ),
624 );
625 });
626 }}
627 />
628 ) : null}
629 </SettingsSection>
630 </ScrollView>
631 </SettingsScreen>
632 );
633 }