Harden connection state handling across app

- adopt atom command results for connection and relay flows
- preserve relay error trace IDs and improve failure handling
- add coverage for auth, registration, and environment updates

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-16 23:47:55 -07:00
1 parent 55228d4119
commit 841bbd9a17
109 files changed
+4192 -2638

No files matched your search

+5
View File
@@ -131,6 +131,11 @@ const config: ExpoConfig = {
{
ios: {
deploymentTarget: "18.0",
// AppCheckCore 11.3+ includes Swift and needs module maps for these Objective-C dependencies.
extraPods: [
{ name: "GoogleUtilities", modular_headers: true },
{ name: "RecaptchaInterop", modular_headers: true },
],
},
},
],
+2 -1
View File
@@ -1,7 +1,8 @@
{
"cli": {
"version": ">= 18.4.0",
"appVersionSource": "remote"
"appVersionSource": "remote",
"promptToConfigurePushNotifications": false
},
"build": {
"development": {
+6 -5
View File
@@ -1,5 +1,6 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useState } from "react";
import { Alert, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -111,12 +112,12 @@ export default function ConnectionsNewRouteScreen() {
const handleSubmit = useCallback(async () => {
setIsSubmitting(true);
try {
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
await onConnectPress(pairingUrl);
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
const result = await onConnectPress(pairingUrl);
if (AsyncResult.isSuccess(result)) {
dismissRoute(router);
} catch {
} else {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
@@ -142,16 +142,12 @@ function ConfiguredCloudEnvironmentRows(props: {
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const handleConnectCloudEnvironment = useCallback(
(entry: RelayEnvironmentView) => {
void controller.connectRelayEnvironment(entry.environment);
},
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => {
void controller.removeEnvironment(environmentId);
},
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
+118 -68
View File
@@ -8,6 +8,13 @@ import type { ComponentProps, ReactNode } from "react";
import { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
isAtomCommandInterrupted,
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { AppText as Text } from "../../components/AppText";
import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences";
import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions";
@@ -87,8 +94,13 @@ function ConfiguredSettingsRouteScreen() {
setNotificationStatus("unsupported");
return;
}
const permission = await Notifications.getPermissionsAsync();
setNotificationStatus(permission.granted ? "enabled" : "disabled");
const result = await settlePromise(() => Notifications.getPermissionsAsync());
if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "notification permission refresh" });
setNotificationStatus("disabled");
return;
}
setNotificationStatus(result.value.granted ? "enabled" : "disabled");
}, []);
useEffect(() => {
@@ -104,60 +116,66 @@ function ConfiguredSettingsRouteScreen() {
setLiveActivityStatus("signed-out");
return;
}
void loadPreferences().then(
(preferences) => {
setLiveActivityStatus(preferences.liveActivitiesEnabled === false ? "disabled" : "enabled");
},
() => {
void (async () => {
const result = await settlePromise(() => loadPreferences());
if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "live activity preference load" });
setLiveActivityStatus("enabled");
},
);
return;
}
setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled");
})();
}, [isLoaded, isSignedIn]);
const requestNotifications = useCallback(async () => {
try {
const result = await runtime.runPromise(
const result = await settleAsyncResult(() =>
runtime.runPromiseExit(
requestAgentNotificationPermission.pipe(
Effect.tap((permission) =>
permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
),
),
);
if (result.type === "granted") {
setNotificationStatus("enabled");
Alert.alert(
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
);
return;
}
if (result.type === "unsupported") {
setNotificationStatus("unsupported");
),
);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
Alert.alert(
"Notifications unavailable",
"Live Activity notifications are only available on iOS.",
error instanceof Error ? error.message : "Could not request notification permission.",
);
return;
}
setNotificationStatus("disabled");
if (result.canAskAgain) {
Alert.alert("Notifications disabled", "Notifications were not enabled.");
return;
}
return;
}
if (result.value.type === "granted") {
setNotificationStatus("enabled");
Alert.alert(
"Notifications disabled",
"Notifications were denied for this app. Open Settings to enable them.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
);
} catch (error) {
return;
}
if (result.value.type === "unsupported") {
setNotificationStatus("unsupported");
Alert.alert(
"Notifications unavailable",
error instanceof Error ? error.message : "Could not request notification permission.",
"Live Activity notifications are only available on iOS.",
);
return;
}
setNotificationStatus("disabled");
if (result.value.canAskAgain) {
Alert.alert("Notifications disabled", "Notifications were not enabled.");
return;
}
Alert.alert(
"Notifications disabled",
"Notifications were denied for this app. Open Settings to enable them.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
);
}, []);
const promptSignIn = useCallback(() => {
@@ -178,36 +196,51 @@ function ConfiguredSettingsRouteScreen() {
}
setLiveActivityStatus("linking");
try {
const token = await getToken(resolveRelayClerkTokenOptions());
if (!token) {
promptSignIn();
setLiveActivityStatus("signed-out");
return;
}
await runtime.runPromise(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: token,
connections,
}),
);
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
} catch (error) {
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
if (tokenResult._tag === "Failure") {
setLiveActivityStatus("disabled");
const error = squashAtomCommandFailure(tokenResult);
Alert.alert(
"Live Activities unavailable",
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
);
return;
}
if (!tokenResult.value) {
promptSignIn();
setLiveActivityStatus("signed-out");
return;
}
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: tokenResult.value,
connections,
}),
),
);
if (updateResult._tag === "Failure") {
setLiveActivityStatus("disabled");
if (!isAtomCommandInterrupted(updateResult)) {
const error = squashAtomCommandFailure(updateResult);
Alert.alert(
"Live Activities unavailable",
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
);
}
return;
}
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
}, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
const handleDeviceNotificationsChange = useCallback(
@@ -234,19 +267,36 @@ function ConfiguredSettingsRouteScreen() {
if (!enabled) {
setLiveActivityStatus("disabled");
void (async () => {
try {
const token = isSignedIn ? await getToken(resolveRelayClerkTokenOptions()) : null;
await runtime.runPromise(
let token: string | null = null;
if (isSignedIn) {
const tokenResult = await settlePromise(() =>
getToken(resolveRelayClerkTokenOptions()),
);
if (tokenResult._tag === "Failure") {
reportAtomCommandResult(tokenResult, {
label: "live activity disable token lookup",
});
return;
}
token = tokenResult.value;
}
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: token,
connections,
}),
);
refreshManagedRelayEnvironments();
} catch {
// The switch is optimistic; a future refresh reconciles relay state.
),
);
if (updateResult._tag === "Failure") {
reportAtomCommandResult(updateResult, {
label: "live activity disable",
});
return;
}
refreshManagedRelayEnvironments();
})();
return;
}
+3 -10
View File
@@ -12,7 +12,7 @@ import {
ConnectionWakeups,
Connectivity,
} from "@t3tools/client-runtime/connection";
import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { AuthStandardClientScopes } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -81,15 +81,8 @@ const wakeupsLayer = Layer.succeed(
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
),
Stream.callback<"credentials-changed">((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
appAtomRegistry.subscribe(managedRelaySessionAtom, () => {
Queue.offerUnsafe(queue, "credentials-changed");
}),
),
(unsubscribe) => Effect.sync(unsubscribe),
).pipe(Effect.asVoid),
managedRelayAccountChanges(appAtomRegistry).pipe(
Stream.map(() => "credentials-changed" as const),
),
),
}),
@@ -4,7 +4,6 @@ import * as NodeCrypto from "node:crypto";
import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import Constants from "expo-constants";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -38,8 +37,7 @@ const widgetMocks = vi.hoisted(() => ({
const backgroundRuntime = vi.hoisted(() => ({
pending: [] as Array<{
readonly operation: unknown;
readonly resolve: (value: unknown) => void;
readonly reject: (error: unknown) => void;
readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
}>,
}));
@@ -105,9 +103,9 @@ vi.mock("react-native", () => ({
vi.mock("../../lib/runtime", () => ({
runtime: {
runPromise: (operation: unknown) =>
new Promise((resolve, reject) => {
backgroundRuntime.pending.push({ operation, resolve, reject });
runPromiseExit: (operation: unknown) =>
new Promise((resolve) => {
backgroundRuntime.pending.push({ operation, resolve });
}),
},
}));
@@ -147,21 +145,23 @@ const relayTestLayer = managedRelayClientLayer("https://relay.example.test").pip
const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
function* () {
let idlePasses = 0;
for (;;) {
yield* Effect.promise(() => Promise.resolve());
const pending = backgroundRuntime.pending.shift();
if (!pending) {
return;
idlePasses++;
if (idlePasses >= 3) {
return;
}
continue;
}
idlePasses = 0;
const exit = yield* Effect.exit(
pending.operation as Effect.Effect<unknown, unknown, ManagedRelayClient>,
);
yield* Effect.sync(() => {
if (Exit.isSuccess(exit)) {
pending.resolve(exit.value);
} else {
pending.reject(Cause.squash(exit.cause));
}
pending.resolve(exit);
});
}
},
@@ -409,6 +409,30 @@ describe("makeRelayDeviceRegistrationRequest", () => {
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("continues queued device registration after a failed auth lookup", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
const tokenProvider = vi
.fn<() => Promise<string | null>>()
.mockRejectedValueOnce(new Error("auth unavailable"))
.mockResolvedValue("clerk-token-user-a");
setAgentAwarenessRelayTokenProvider(tokenProvider);
const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
expect(tokenListener).toBeDefined();
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(backgroundRuntime.pending).toHaveLength(0);
expect(tokenProvider).toHaveBeenCalledTimes(2);
}).pipe(Effect.provide(relayTestLayer));
});
it("only registers again when the authenticated identity changes", () => {
expect(shouldRegisterAgentAwarenessDeviceForProvider(null, "user-a")).toBe(true);
expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-a")).toBe(false);
@@ -10,6 +10,11 @@ import {
} from "@t3tools/contracts/relay";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import {
isAtomCommandInterrupted,
settleAsyncResult,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { SavedRemoteConnection } from "../../lib/connection";
import { runtime } from "../../lib/runtime";
@@ -33,7 +38,7 @@ let relayTokenProviderIdentity: string | null = null;
let deviceRegistrationGeneration = 0;
let activeDeviceRegistration: {
readonly input: DeviceRegistrationInput;
readonly operation: Promise<void>;
operation: Promise<void>;
} | null = null;
let pendingDeviceRegistration: {
readonly input: DeviceRegistrationInput;
@@ -272,9 +277,12 @@ function runRegistrationInBackground(
operation: Effect.Effect<unknown, unknown, ManagedRelayClient>,
context: string,
): void {
void runtime.runPromise(operation).catch((error: unknown) => {
logRegistrationError(context, error);
});
void (async () => {
const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
logRegistrationError(context, squashAtomCommandFailure(result));
}
})();
}
function mergeDeviceRegistrationInput(
@@ -314,19 +322,24 @@ function startPendingDeviceRegistration(): void {
hasObservedPushToken: next.input.observedPushToken !== undefined,
hasPushToStartToken: next.input.pushToStartToken !== undefined,
});
const operation = runtime
.runPromise(registerDevice(next.input, generation))
.catch((error: unknown) => {
logRegistrationError(next.context, error);
})
.finally(() => {
logRegistrationDebug("device registration finished", { generation });
if (activeDeviceRegistration?.operation === operation) {
activeDeviceRegistration = null;
}
startPendingDeviceRegistration();
});
activeDeviceRegistration = { input: next.input, operation };
const registration = {
input: next.input,
operation: Promise.resolve(),
};
activeDeviceRegistration = registration;
registration.operation = (async () => {
const result = await settleAsyncResult(() =>
runtime.runPromiseExit(registerDevice(next.input, generation)),
);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
logRegistrationError(next.context, squashAtomCommandFailure(result));
}
logRegistrationDebug("device registration finished", { generation });
if (activeDeviceRegistration === registration) {
activeDeviceRegistration = null;
}
startPendingDeviceRegistration();
})();
}
function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: string): void {
@@ -16,12 +16,14 @@ vi.mock("@clerk/expo/token-cache", () => ({
vi.mock("../../lib/runtime", () => ({
runtime: {
runPromise: vi.fn(),
runPromiseExit: vi.fn(),
},
}));
vi.mock("../../state/environments", () => ({
useEnvironmentConnectionActions: vi.fn(),
vi.mock("../../connection/catalog", () => ({
environmentCatalog: {
removeRelayEnvironments: {},
},
}));
vi.mock("./publicConfig", () => ({
@@ -1,25 +1,29 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import { ManagedRelayClient, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
createManagedRelaySession,
ManagedRelayClient,
setManagedRelaySession,
} from "@t3tools/client-runtime/relay";
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import { type ReactNode, useEffect, useRef } from "react";
import { useEnvironmentConnectionActions } from "../../state/environments";
import { environmentCatalog } from "../../connection/catalog";
import { runtime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import { useAtomCommand } from "../../state/use-atom-command";
import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function resetManagedRelayTokenCache(): Promise<void> {
return runtime.runPromise(
ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
function resetManagedRelayTokenCache() {
return settleAsyncResult(() =>
runtime.runPromiseExit(
ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
),
);
}
@@ -33,24 +37,24 @@ export function activateCloudRelayAccount(
tokenProvider: () => Promise<string | null>,
): void {
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
setManagedRelaySession(
appAtomRegistry,
createManagedRelaySession({
accountId,
readClerkToken: tokenProvider,
}),
);
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken: tokenProvider,
});
}
function CloudAuthBridge(props: { readonly children: ReactNode }) {
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const { removeRelayEnvironments } = useEnvironmentConnectionActions();
const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
reportFailure: false,
reportDefect: false,
});
const previousTokenProviderRef = useRef<{
readonly userId: string;
readonly provider: () => Promise<string | null>;
} | null>(null);
const observedAccountRef = useRef<string | null | undefined>(undefined);
const accountTransitionRef = useRef(Promise.resolve());
const accountTransitionRef = useRef<Promise<void> | null>(null);
useEffect(() => {
let cancelled = false;
@@ -68,19 +72,24 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
readonly provider: () => Promise<string | null>;
} | null,
) => {
accountTransitionRef.current = accountTransitionRef.current.then(async () => {
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
accountTransitionRef.current = previousTransition.then(async () => {
const cleanup = [
resetManagedRelayTokenCache(),
removeRelayEnvironments(),
...(previous
? [runtime.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))]
? [
settleAsyncResult(() =>
runtime.runPromiseExit(
unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
),
),
]
: []),
];
const results = await Promise.allSettled(cleanup);
const results = await Promise.all(cleanup);
for (const result of results) {
if (result.status === "rejected") {
console.warn("[t3-cloud] cloud account cleanup failed", result.reason);
}
reportAtomCommandResult(result, { label: "cloud account cleanup" });
}
});
return accountTransitionRef.current;
@@ -105,6 +114,15 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
previousTokenProviderRef.current = { userId, provider: tokenProvider };
activateCloudRelayAccount(userId, tokenProvider);
};
const activateAfterTransition = (transition: Promise<void>) => {
void (async () => {
const result = await settlePromise(async () => {
await transition;
activateSession();
});
reportAtomCommandResult(result, { label: "cloud account activation" });
})();
};
if (
previousObservedAccount !== undefined &&
previousObservedAccount !== null &&
@@ -112,9 +130,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
) {
previousTokenProviderRef.current = null;
deactivateCloudRelayAccount();
void queueAccountCleanup(previous).then(activateSession);
activateAfterTransition(queueAccountCleanup(previous));
} else {
void accountTransitionRef.current.then(activateSession);
activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
}
return () => {
@@ -7,6 +7,7 @@ import { availableCloudEnvironmentPresentation } from "./cloudEnvironmentPresent
function relayStatus(
status: RelayEnvironmentStatusResponse["status"],
error?: string,
traceId?: string,
): RelayEnvironmentStatusResponse {
return {
environmentId: EnvironmentId.make("environment-cloud"),
@@ -18,6 +19,7 @@ function relayStatus(
status,
checkedAt: "2026-06-05T16:49:11.000Z",
...(error ? { error } : {}),
...(traceId ? { traceId } : {}),
};
}
@@ -58,13 +60,13 @@ describe("available cloud environment presentation", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: false,
status: relayStatus("offline", "Tunnel is unavailable."),
status: relayStatus("offline", "Tunnel is unavailable.", "trace-offline"),
statusError: null,
statusErrorTraceId: null,
}),
).toEqual({
connectionError: "Tunnel is unavailable.",
connectionErrorTraceId: null,
connectionErrorTraceId: "trace-offline",
connectionState: "error",
statusText: "Tunnel is unavailable.",
});
@@ -27,7 +27,7 @@ export function availableCloudEnvironmentPresentation(input: {
const connectionError = input.status.error ?? "Relay is offline.";
return {
connectionError,
connectionErrorTraceId: null,
connectionErrorTraceId: input.status.traceId ?? null,
connectionState: "error",
statusText: connectionError,
};
@@ -1,8 +1,11 @@
import { SymbolView } from "expo-symbols";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useState } from "react";
import { Pressable, View } from "react-native";
import { Alert, Pressable, View } from "react-native";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -29,7 +32,7 @@ export function ConnectionEnvironmentRow(props: {
readonly onUpdate: (
environmentId: EnvironmentId,
updates: { readonly label: string; readonly displayUrl: string },
) => Promise<void>;
) => Promise<AtomCommandResult<unknown, unknown>>;
}) {
const [label, setLabel] = useState(props.environment.environmentLabel);
const [url, setUrl] = useState(props.environment.displayUrl);
@@ -45,11 +48,19 @@ export function ConnectionEnvironmentRow(props: {
props.environment.connectionState === "connecting" ||
props.environment.connectionState === "reconnecting";
const handleSave = useCallback(async () => {
await props.onUpdate(props.environment.environmentId, {
const result = await props.onUpdate(props.environment.environmentId, {
label: label.trim(),
displayUrl: url.trim(),
});
props.onToggle();
if (AsyncResult.isSuccess(result)) {
props.onToggle();
return;
}
const error = Cause.squash(result.cause);
Alert.alert(
"Could not update environment",
error instanceof Error ? error.message : "The environment could not be updated.",
);
}, [label, url, props]);
return (
@@ -1,4 +1,8 @@
import { useAtomValue } from "@effect/atom-react";
import {
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import type {
RelayClientEnvironmentRecord,
@@ -7,8 +11,14 @@ import type {
import * as Option from "effect/Option";
import { useCallback, useMemo } from "react";
import { useEnvironmentActions, useEnvironments } from "../../state/environments";
import { environmentCatalog } from "../../connection/catalog";
import {
connectPairingUrl as connectPairingUrlAtom,
updateBearerConnection,
} from "../../connection/onboarding";
import { useEnvironments } from "../../state/environments";
import { relayEnvironmentDiscovery } from "../../state/relay";
import { useAtomCommand } from "../../state/use-atom-command";
import { projectWorkspaceEnvironment, type WorkspaceEnvironment } from "../../state/workspaceModel";
export interface RelayEnvironmentView {
@@ -21,8 +31,18 @@ export interface RelayEnvironmentView {
export function useConnectionController() {
const { environments } = useEnvironments();
const actions = useEnvironmentActions();
const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
const connectPairingUrlMutation = useAtomCommand(connectPairingUrlAtom, {
reportFailure: false,
});
const updateBearer = useAtomCommand(updateBearerConnection, { reportFailure: false });
const registerEnvironment = useAtomCommand(environmentCatalog.register, "environment register");
const removeEnvironmentMutation = useAtomCommand(environmentCatalog.remove, "environment remove");
const retryEnvironmentMutation = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const refreshRelayEnvironments = useAtomCommand(
relayEnvironmentDiscovery.refresh,
"relay environment refresh",
);
const connectedEnvironments = useMemo<ReadonlyArray<WorkspaceEnvironment>>(
() => environments.map(projectWorkspaceEnvironment),
@@ -49,32 +69,40 @@ export function useConnectionController() {
);
const connectPairingUrl = useCallback(
(pairingUrl: string) => actions.connectPairingUrl(pairingUrl),
[actions],
(pairingUrl: string) => connectPairingUrlMutation(pairingUrl),
[connectPairingUrlMutation],
);
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) => actions.connectRelayEnvironment(environment),
[actions],
(environment: RelayClientEnvironmentRecord) =>
registerEnvironment(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[registerEnvironment],
);
const removeEnvironment = useCallback(
(environmentId: EnvironmentId) => actions.removeEnvironment(environmentId),
[actions],
(environmentId: EnvironmentId) => removeEnvironmentMutation(environmentId),
[removeEnvironmentMutation],
);
const retryEnvironment = useCallback(
(environmentId: EnvironmentId) => actions.retryEnvironment(environmentId),
[actions],
(environmentId: EnvironmentId) => retryEnvironmentMutation(environmentId),
[retryEnvironmentMutation],
);
const updateEnvironment = useCallback(
(
environmentId: EnvironmentId,
updates: { readonly label: string; readonly displayUrl: string },
) =>
actions.updateBearer({
updateBearer({
environmentId,
label: updates.label,
httpBaseUrl: updates.displayUrl,
}),
[actions],
[updateBearer],
);
return {
@@ -92,6 +120,6 @@ export function useConnectionController() {
removeEnvironment,
retryEnvironment,
updateEnvironment,
refreshRelayEnvironments: actions.refreshRelayEnvironments,
refreshRelayEnvironments,
};
}
@@ -22,14 +22,15 @@ import {
isFilesystemBrowseQuery,
} from "@t3tools/client-runtime/state/projects";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useAtomSet } from "@effect/atom-react";
import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array";
import * as Cause from "effect/Cause";
import * as Order from "effect/Order";
import { AsyncResult } from "effect/unstable/reactivity";
import { useProjects, useServerConfigs } from "../../state/entities";
import { filesystemEnvironment } from "../../state/filesystem";
@@ -41,6 +42,7 @@ import { ErrorBanner } from "../../components/ErrorBanner";
import { SourceControlIcon } from "../../components/SourceControlIcon";
import { useThemeColor } from "../../lib/useThemeColor";
import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
interface EnvironmentOption {
@@ -438,7 +440,7 @@ export function AddProjectSourceScreen() {
function useCreateProject(environment: EnvironmentOption | null) {
const router = useRouter();
const createProject = useAtomSet(projectEnvironment.create, { mode: "promise" });
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
const projects = useProjects();
return useCallback(
@@ -470,10 +472,13 @@ function useCreateProject(environment: EnvironmentOption | null) {
workspaceRoot,
createdAt: new Date().toISOString(),
});
await createProject({
const result = await createProject({
environmentId: environment.environmentId,
input: command,
});
if (AsyncResult.isFailure(result)) {
return result;
}
router.replace({
pathname: "/new/draft",
params: {
@@ -482,6 +487,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
title: inferProjectTitleFromPath(workspaceRoot),
},
});
return result;
},
[createProject, environment, projects, router],
);
@@ -499,8 +505,8 @@ function useEnvironmentFromParam(): EnvironmentOption | null {
}
export function AddProjectRepositoryScreen() {
const lookupRepositoryMutation = useAtomSet(sourceControlEnvironment.lookupRepository, {
mode: "promise",
const lookupRepositoryMutation = useAtomCommand(sourceControlEnvironment.lookupRepository, {
reportFailure: false,
});
const router = useRouter();
const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
@@ -514,29 +520,33 @@ export function AddProjectRepositoryScreen() {
if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
setError(null);
setIsSubmitting(true);
try {
const provider = addProjectRemoteSourceProvider(source);
if (!provider) {
const remoteUrl = repositoryInput.trim();
router.push({
pathname: "/new/add-project/destination",
params: {
environmentId: environment.environmentId,
source,
remoteUrl,
repositoryTitle: remoteUrl,
},
});
return;
}
const repository = await lookupRepositoryMutation({
environmentId: environment.environmentId,
input: {
provider,
repository: repositoryInput.trim(),
const provider = addProjectRemoteSourceProvider(source);
if (!provider) {
const remoteUrl = repositoryInput.trim();
router.push({
pathname: "/new/add-project/destination",
params: {
environmentId: environment.environmentId,
source,
remoteUrl,
repositoryTitle: remoteUrl,
},
});
setIsSubmitting(false);
return;
}
const result = await lookupRepositoryMutation({
environmentId: environment.environmentId,
input: {
provider,
repository: repositoryInput.trim(),
},
});
if (AsyncResult.isFailure(result)) {
setError(errorMessage(Cause.squash(result.cause)));
} else {
const repository = result.value;
router.push({
pathname: "/new/add-project/destination",
params: {
@@ -546,11 +556,8 @@ export function AddProjectRepositoryScreen() {
repositoryTitle: repository.nameWithOwner,
},
});
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
}
setIsSubmitting(false);
}, [environment, isSubmitting, lookupRepositoryMutation, repositoryInput, router, source]);
return (
@@ -701,13 +708,11 @@ export function AddProjectLocalFolderScreen() {
}
setIsSubmitting(true);
try {
await createProject(resolved.path);
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
const result = await createProject(resolved.path);
if (result && AsyncResult.isFailure(result)) {
setError(errorMessage(Cause.squash(result.cause)));
}
setIsSubmitting(false);
}, [createProject, environment, isSubmitting, pathInput]);
return (
@@ -740,8 +745,8 @@ export function AddProjectLocalFolderScreen() {
}
export function AddProjectDestinationScreen() {
const cloneRepository = useAtomSet(sourceControlEnvironment.cloneRepository, {
mode: "promise",
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
reportFailure: false,
});
const params = useLocalSearchParams<{
environmentId?: string;
@@ -777,20 +782,22 @@ export function AddProjectDestinationScreen() {
}
setIsSubmitting(true);
try {
const result = await cloneRepository({
environmentId: environment.environmentId,
input: {
remoteUrl,
destinationPath: resolved.path,
},
});
await createProject(result.cwd);
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
const cloneResult = await cloneRepository({
environmentId: environment.environmentId,
input: {
remoteUrl,
destinationPath: resolved.path,
},
});
if (AsyncResult.isFailure(cloneResult)) {
setError(errorMessage(Cause.squash(cloneResult.cause)));
} else {
const createResult = await createProject(cloneResult.value.cwd);
if (createResult && AsyncResult.isFailure(createResult)) {
setError(errorMessage(Cause.squash(createResult.cause)));
}
}
setIsSubmitting(false);
}, [cloneRepository, createProject, environment, isSubmitting, pathInput, remoteUrl]);
return (
@@ -16,8 +16,9 @@ import {
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { useEnvironmentConnectionActions } from "../../state/environments";
import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { useAtomCommand } from "../../state/use-atom-command";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
@@ -119,7 +120,7 @@ export function ReviewSheet() {
threadId: ThreadId;
}>();
const environment = useEnvironmentPresentation(environmentId);
const environmentActions = useEnvironmentConnectionActions();
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
@@ -208,8 +209,8 @@ export function ReviewSheet() {
hasAnyCachedDiff,
});
const handleRetryEnvironment = useCallback(() => {
void environmentActions.retryNow(environmentId);
}, [environmentActions, environmentId]);
void retryEnvironment(environmentId);
}, [environmentId, retryEnvironment]);
const listHeader = useMemo(() => {
const children: ReactElement[] = [];
@@ -1,4 +1,3 @@
import { useAtomSet } from "@effect/atom-react";
import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
@@ -6,6 +5,7 @@ import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { terminalEnvironment } from "../../state/terminal";
import { useAtomCommand } from "../../state/use-atom-command";
import { useAttachedTerminalSession } from "../../state/use-terminal-session";
import { TerminalSurface } from "./NativeTerminalSurface";
import { hasNativeTerminalSurface } from "./nativeTerminalModule";
@@ -30,8 +30,8 @@ const DEFAULT_TERMINAL_ROWS = 24;
export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
props: ThreadTerminalPanelProps,
) {
const writeTerminal = useAtomSet(terminalEnvironment.write, { mode: "promise" });
const resizeTerminal = useAtomSet(terminalEnvironment.resize, { mode: "promise" });
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
const nativeTerminalAvailable = hasNativeTerminalSurface();
const terminalId = DEFAULT_TERMINAL_ID;
const lastGridSizeRef = useRef<TerminalGridSize>({
@@ -1,4 +1,3 @@
import { useAtomSet } from "@effect/atom-react";
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import { SymbolView } from "expo-symbols";
@@ -20,9 +19,10 @@ import {
import { EmptyState } from "../../components/EmptyState";
import { GlassSurface } from "../../components/GlassSurface";
import { LoadingScreen } from "../../components/LoadingScreen";
import { useEnvironmentConnectionActions } from "../../state/environments";
import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { terminalEnvironment } from "../../state/terminal";
import { useAtomCommand } from "../../state/use-atom-command";
import { useWorkspaceState } from "../../state/workspace";
import { buildThreadTerminalNavigation } from "../../lib/routes";
import {
@@ -154,10 +154,10 @@ function pickRunningTerminalSessionForBootstrap(
export function ThreadTerminalRouteScreen() {
const router = useRouter();
const writeTerminal = useAtomSet(terminalEnvironment.write, { mode: "promise" });
const resizeTerminal = useAtomSet(terminalEnvironment.resize, { mode: "promise" });
const clearTerminal = useAtomSet(terminalEnvironment.clear, { mode: "promise" });
const environmentActions = useEnvironmentConnectionActions();
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const { state: workspaceState } = useWorkspaceState();
const params = useLocalSearchParams<{
@@ -208,7 +208,7 @@ export function ThreadTerminalRouteScreen() {
terminalId,
}
: null,
[selectedThread?.environmentId, selectedThread?.id, terminalId],
[selectedThread, terminalId],
);
const launchTargetKey = launchTarget
? `${launchTarget.environmentId}:${launchTarget.threadId}:${launchTarget.terminalId}`
@@ -861,9 +861,9 @@ export function ThreadTerminalRouteScreen() {
}, []);
const handleRetryEnvironment = useCallback(() => {
if (routeEnvironmentId !== null) {
void environmentActions.retryNow(routeEnvironmentId);
void retryEnvironment(routeEnvironmentId);
}
}, [environmentActions, routeEnvironmentId]);
}, [retryEnvironment, routeEnvironmentId]);
if (!selectedThread) {
if (workspaceState.isLoadingConnections) {
@@ -1,11 +1,15 @@
import { Stack, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { InteractionManager, View, useColorScheme } from "react-native";
import { Alert, InteractionManager, View, useColorScheme } from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { EnvironmentId } from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import {
@@ -28,7 +32,7 @@ import {
import { buildThreadRoutePath } from "../../lib/routes";
import { useProjects } from "../../state/entities";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useProjectActions } from "./use-project-actions";
import { useCreateProjectThread } from "./use-project-actions";
function formatWorkspaceLabel(input: {
readonly workspaceMode: string;
@@ -49,7 +53,7 @@ export function NewTaskDraftScreen(props: {
};
}) {
const projects = useProjects();
const { onCreateThreadWithOptions } = useProjectActions();
const createProjectThread = useCreateProjectThread();
const flow = useNewTaskFlow();
const router = useRouter();
const insets = useSafeAreaInsets();
@@ -372,27 +376,33 @@ export function NewTaskDraftScreen(props: {
}
flow.setSubmitting(true);
try {
const createdThread = await onCreateThreadWithOptions({
project: flow.selectedProject,
modelSelection: flow.selectedModel,
envMode: flow.workspaceMode,
branch: flow.selectedBranchName,
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
});
const result = await createProjectThread({
project: flow.selectedProject,
modelSelection: flow.selectedModel,
envMode: flow.workspaceMode,
branch: flow.selectedBranchName,
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
});
flow.setSubmitting(false);
if (createdThread) {
flow.setPrompt("");
flow.clearAttachments();
router.replace(buildThreadRoutePath(createdThread));
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
Alert.alert(
"Could not start task",
error instanceof Error ? error.message : "The task could not be started.",
);
}
} finally {
flow.setSubmitting(false);
return;
}
flow.setPrompt("");
flow.clearAttachments();
router.replace(buildThreadRoutePath(result.value));
}
if (!selectedProject) {
@@ -10,7 +10,7 @@ export interface PendingApprovalCardProps {
readonly onRespond: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
) => Promise<unknown>;
}
export function PendingApprovalCard(props: PendingApprovalCardProps) {
@@ -20,7 +20,7 @@ export interface PendingUserInputCardProps {
questionId: string,
customAnswer: string,
) => void;
readonly onSubmit: () => Promise<void>;
readonly onSubmit: () => Promise<unknown>;
}
export function PendingUserInputCard(props: PendingUserInputCardProps) {
@@ -89,11 +89,11 @@ export interface ThreadComposerProps {
readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => Promise<void>;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<void>;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => Promise<void>;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => Promise<void>;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onReconnectEnvironment: () => void;
readonly onExpandedChange?: (expanded: boolean) => void;
}
@@ -466,7 +466,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
);
setComposerSelection({ start: result.cursor, end: result.cursor });
onChangeDraftMessage(result.text);
void onUpdateInteractionMode(item.command);
onUpdateInteractionMode(item.command);
return;
}
@@ -594,14 +594,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const modelKey = event.slice("model:".length);
const option = modelOptions.find((o) => o.key === modelKey);
if (option) {
void props.onUpdateModelSelection(option.selection);
props.onUpdateModelSelection(option.selection);
}
}
function handleOptionsMenuAction(event: string) {
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
void props.onUpdateModelSelection({
props.onUpdateModelSelection({
...currentModelSelection,
options: providerOptions,
});
@@ -609,12 +609,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}
if (event.startsWith("options:runtime:")) {
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
void props.onUpdateRuntimeMode(runtimeMode);
props.onUpdateRuntimeMode(runtimeMode);
return;
}
if (event.startsWith("options:interaction:")) {
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
void props.onUpdateInteractionMode(interactionMode);
props.onUpdateInteractionMode(interactionMode);
}
}
@@ -760,11 +760,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
{!isExpanded ? (
showStopAction ? (
<ControlPill
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
/>
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
) : (
<ControlPill
icon="arrow.up"
@@ -814,7 +810,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
<ComposerToolbarButton
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
onPress={props.onStopThread}
showChevron={false}
/>
) : null}
@@ -74,18 +74,16 @@ export interface ThreadDetailScreenProps {
readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => Promise<void>;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<void>;
readonly onReconnectEnvironment: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise<void>;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>;
readonly onUpdateThreadInteractionMode: (
interactionMode: ProviderInteractionMode,
) => Promise<void>;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onRespondToApproval: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
) => Promise<unknown>;
readonly onSelectUserInputOption: (
requestId: ApprovalRequestId,
questionId: string,
@@ -96,7 +94,7 @@ export interface ThreadDetailScreenProps {
questionId: string,
customAnswer: string,
) => void;
readonly onSubmitUserInput: () => Promise<void>;
readonly onSubmitUserInput: () => Promise<unknown>;
readonly showContent?: boolean;
}
@@ -1,7 +1,13 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import * as Option from "effect/Option";
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import {
EnvironmentId,
type ModelSelection,
type ProjectScript,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import { useWorkspaceState } from "../../state/workspace";
@@ -38,12 +44,13 @@ import { terminalDebugLog } from "../terminal/terminalDebugLog";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { threadEnvironment } from "../../state/threads";
import { projectThreadContentPresentation } from "./threadContentPresentation";
function firstRouteParam(value: string | string[] | undefined): string | null {
@@ -71,9 +78,19 @@ export function ThreadRouteScreen() {
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const commands = useSelectedThreadCommands({
refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus,
});
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread metadata update",
);
const setThreadRuntimeMode = useAtomCommand(
threadEnvironment.setRuntimeMode,
"thread runtime mode",
);
const setThreadInteractionMode = useAtomCommand(
threadEnvironment.setInteractionMode,
"thread interaction mode",
);
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const router = useRouter();
const params = useLocalSearchParams<{
environmentId?: string | string[];
@@ -139,6 +156,69 @@ export function ThreadRouteScreen() {
const handleOpenConnectionEditor = useCallback(() => {
void router.push("/connections");
}, [router]);
const handleUpdateThreadModelSelection = useCallback(
(modelSelection: ModelSelection) => {
if (!selectedThread) {
return;
}
return updateThreadMetadata({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
modelSelection,
},
});
},
[selectedThread, updateThreadMetadata],
);
const handleUpdateThreadRuntimeMode = useCallback(
(runtimeMode: RuntimeMode) => {
if (!selectedThread) {
return;
}
return setThreadRuntimeMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
runtimeMode,
},
});
},
[selectedThread, setThreadRuntimeMode],
);
const handleUpdateThreadInteractionMode = useCallback(
(interactionMode: ProviderInteractionMode) => {
if (!selectedThread) {
return;
}
return setThreadInteractionMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
interactionMode,
},
});
},
[selectedThread, setThreadInteractionMode],
);
const handleStopThread = useCallback(() => {
if (
!selectedThread ||
(selectedThread.session?.status !== "running" &&
selectedThread.session?.status !== "starting")
) {
return;
}
return interruptThreadTurn({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
...(selectedThread.session.activeTurnId
? { turnId: selectedThread.session.activeTurnId }
: {}),
},
});
}, [interruptThreadTurn, selectedThread]);
const handleOpenTerminal = useCallback(
(nextTerminalId?: string | null) => {
@@ -383,12 +463,12 @@ export function ThreadRouteScreen() {
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
serverConfig={serverConfig}
onStopThread={commands.onStopThread}
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode}
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
@@ -1,10 +1,9 @@
import { useAtomSet } from "@effect/atom-react";
import { useCallback } from "react";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { mapAtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import {
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
CommandId,
MessageId,
ThreadId,
@@ -13,12 +12,14 @@ import {
type RuntimeMode,
} from "@t3tools/contracts";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { threadEnvironment } from "../../state/threads";
import { useThreadShells } from "../../state/entities";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
function deriveThreadTitleFromPrompt(value: string): string {
@@ -31,11 +32,10 @@ function deriveThreadTitleFromPrompt(value: string): string {
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
}
export function useProjectActions() {
const startTurn = useAtomSet(threadEnvironment.startTurn, { mode: "promise" });
const threads = useThreadShells();
export function useCreateProjectThread() {
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const onCreateThreadWithOptions = useCallback(
return useCallback(
async (input: {
readonly project: EnvironmentProject;
readonly modelSelection: ModelSelection;
@@ -53,14 +53,18 @@ export function useProjectActions() {
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
if (initialMessageText.length === 0) {
return null;
const error = new Error("Enter a task before starting the thread.");
setPendingConnectionError(error.message);
return AsyncResult.failure(Cause.fail(error));
}
if (input.envMode === "worktree" && !input.branch) {
return null;
const error = new Error("Select a base branch before creating a worktree.");
setPendingConnectionError(error.message);
return AsyncResult.failure(Cause.fail(error));
}
const isWorktree = input.envMode === "worktree";
await startTurn({
const result = await startTurn({
environmentId: input.project.environmentId,
input: {
commandId: CommandId.make(metadata.commandId),
@@ -100,46 +104,19 @@ export function useProjectActions() {
createdAt: metadata.createdAt,
},
});
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
setPendingConnectionError(
error instanceof Error ? error.message : "The task could not be started.",
);
return AsyncResult.failure(result.cause);
}
setPendingConnectionError(null);
return {
environmentId: input.project.environmentId,
threadId,
};
return mapAtomCommandResult(result, () =>
scopeThreadRef(input.project.environmentId, threadId),
);
},
[startTurn],
);
const onCreateThread = useCallback(
async (project: EnvironmentProject) => {
const latestProjectThread =
threads.find(
(thread) =>
thread.environmentId === project.environmentId && thread.projectId === project.id,
) ?? null;
const modelSelection =
project.defaultModelSelection ?? latestProjectThread?.modelSelection ?? null;
if (!modelSelection) {
setPendingConnectionError("This project does not have a default model configured yet.");
return null;
}
return await onCreateThreadWithOptions({
project,
modelSelection,
envMode: "local",
branch: null,
worktreePath: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
initialMessageText: "",
initialAttachments: [],
});
},
[onCreateThreadWithOptions, threads],
);
return {
onCreateThread,
onCreateThreadWithOptions,
};
}
+2 -76
View File
@@ -1,24 +1,14 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import {
connectionCatalogDisplayUrl,
type EnvironmentPresentation as BaseEnvironmentPresentation,
} from "@t3tools/client-runtime/connection";
import {
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import { useCallback, useMemo } from "react";
import { useMemo } from "react";
import { environmentCatalog } from "../connection/catalog";
import {
connectPairingUrl as connectPairingUrlAtom,
updateBearerConnection,
} from "../connection/onboarding";
import { environmentPresentations } from "./presentation";
import { useEnvironmentQuery } from "./query";
import { relayEnvironmentDiscovery } from "./relay";
export interface EnvironmentPresentation extends BaseEnvironmentPresentation {
readonly environmentId: EnvironmentId;
@@ -64,67 +54,3 @@ export function useEnvironments() {
export function useEnvironmentConnectionState(environmentId: EnvironmentId) {
return useEnvironmentQuery(environmentCatalog.stateAtom(environmentId));
}
export function useEnvironmentConnectionActions() {
const register = useAtomSet(environmentCatalog.register, { mode: "promise" });
const remove = useAtomSet(environmentCatalog.remove, { mode: "promise" });
const removeRelayEnvironments = useAtomSet(environmentCatalog.removeRelayEnvironments, {
mode: "promise",
});
const retryNow = useAtomSet(environmentCatalog.retryNow, { mode: "promise" });
return useMemo(
() => ({
register,
remove,
removeRelayEnvironments,
retryNow,
}),
[register, remove, removeRelayEnvironments, retryNow],
);
}
export function useEnvironmentActions() {
const connectPairingUrl = useAtomSet(connectPairingUrlAtom, {
mode: "promise",
});
const updateBearer = useAtomSet(updateBearerConnection, {
mode: "promise",
});
const { register, remove, retryNow } = useEnvironmentConnectionActions();
const refreshRelayEnvironments = useAtomSet(relayEnvironmentDiscovery.refresh, {
mode: "promise",
});
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) =>
register(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[register],
);
return useMemo(
() => ({
connectPairingUrl,
updateBearer,
connectRelayEnvironment,
removeEnvironment: remove,
retryEnvironment: retryNow,
refreshRelayEnvironments,
}),
[
connectPairingUrl,
connectRelayEnvironment,
refreshRelayEnvironments,
remove,
retryNow,
updateBearer,
],
);
}
+24
View File
@@ -0,0 +1,24 @@
import { useAtomSet } from "@effect/atom-react";
import {
executeAtomCommand,
type AtomCommandOptions,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { AsyncResult, type Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
export function useAtomCommand<A, E, W>(
atom: Atom.Writable<AsyncResult.AsyncResult<A, E>, W>,
options?: string | AtomCommandOptions,
): (value: W) => Promise<AtomCommandResult<A, E>> {
const set = useAtomSet(atom, { mode: "promiseExit" });
const label =
typeof options === "string" ? options : (options?.label ?? atom.label?.[0] ?? "atom command");
const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true);
const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true);
return useCallback(
(value: W) => executeAtomCommand(() => set(value), { label, reportFailure, reportDefect }),
[label, reportDefect, reportFailure, set],
);
}
@@ -2,8 +2,9 @@ import { useAtomValue } from "@effect/atom-react";
import type { PreparedConnection } from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import type { ServerConfig } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
import { Atom } from "effect/unstable/reactivity";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import { Alert } from "react-native";
@@ -162,25 +163,24 @@ export function useRemoteConnections() {
const onConnectPress = useCallback(
async (pairingUrl?: string) => {
try {
const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
setPendingConnectionError(null);
await controller.connectPairingUrl(nextPairingUrl);
appAtomRegistry.set(connectionPairingUrlAtom, "");
} catch (error) {
const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
setPendingConnectionError(null);
const result = await controller.connectPairingUrl(nextPairingUrl);
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
const message =
error instanceof Error ? error.message : "Failed to pair with the environment.";
setPendingConnectionError(message);
throw error;
} else {
appAtomRegistry.set(connectionPairingUrlAtom, "");
}
return result;
},
[connectionPairingUrl, controller],
);
const onReconnectEnvironment = useCallback(
(environmentId: EnvironmentId) => {
void controller.retryEnvironment(environmentId);
},
(environmentId: EnvironmentId) => controller.retryEnvironment(environmentId),
[controller],
);
const onUpdateEnvironment = useCallback(
@@ -1,136 +0,0 @@
import { useAtomSet } from "@effect/atom-react";
import { useCallback } from "react";
import {
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { threadEnvironment } from "../state/threads";
import { useThreadSelection } from "./use-thread-selection";
export function useSelectedThreadCommands(input: {
readonly refreshSelectedThreadGitStatus: (options?: {
readonly quiet?: boolean;
readonly cwd?: string | null;
}) => Promise<unknown>;
}) {
const updateMetadata = useAtomSet(threadEnvironment.updateMetadata, { mode: "promise" });
const setRuntimeMode = useAtomSet(threadEnvironment.setRuntimeMode, { mode: "promise" });
const setInteractionMode = useAtomSet(threadEnvironment.setInteractionMode, { mode: "promise" });
const interruptTurn = useAtomSet(threadEnvironment.interruptTurn, { mode: "promise" });
const { refreshSelectedThreadGitStatus } = input;
const { selectedThread } = useThreadSelection();
const onRefresh = useCallback(async () => {
if (selectedThread) {
await refreshSelectedThreadGitStatus({ quiet: true });
}
}, [refreshSelectedThreadGitStatus, selectedThread]);
const onUpdateThreadModelSelection = useCallback(
async (modelSelection: ModelSelection) => {
if (!selectedThread) {
return;
}
await updateMetadata({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
modelSelection,
},
});
},
[selectedThread, updateMetadata],
);
const onUpdateThreadRuntimeMode = useCallback(
async (runtimeMode: RuntimeMode) => {
if (!selectedThread) {
return;
}
await setRuntimeMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
runtimeMode,
},
});
},
[selectedThread, setRuntimeMode],
);
const onUpdateThreadInteractionMode = useCallback(
async (interactionMode: ProviderInteractionMode) => {
if (!selectedThread) {
return;
}
await setInteractionMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
interactionMode,
},
});
},
[selectedThread, setInteractionMode],
);
const onStopThread = useCallback(async () => {
if (!selectedThread) {
return;
}
if (
selectedThread.session?.status !== "running" &&
selectedThread.session?.status !== "starting"
) {
return;
}
await interruptTurn({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
...(selectedThread.session?.activeTurnId
? { turnId: selectedThread.session.activeTurnId }
: {}),
},
});
}, [interruptTurn, selectedThread]);
const onRenameThread = useCallback(
async (title: string) => {
if (!selectedThread) {
return;
}
const trimmed = title.trim();
if (!trimmed || trimmed === selectedThread.title) {
return;
}
await updateMetadata({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
title: trimmed,
},
});
},
[selectedThread, updateMetadata],
);
return {
onRefresh,
onUpdateThreadModelSelection,
onUpdateThreadRuntimeMode,
onUpdateThreadInteractionMode,
onRenameThread,
onStopThread,
};
}
@@ -1,7 +1,7 @@
import { useAtomSet } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import {
type GitActionRequestInput,
type VcsActionOperation,
@@ -12,6 +12,8 @@ import {
dedupeRemoteBranchesWithLocalMatches,
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { useBranches } from "../state/queries";
import { threadEnvironment } from "../state/threads";
@@ -19,25 +21,28 @@ import { vcsActionManager, vcsEnvironment } from "../state/vcs";
import { uuidv4 } from "../lib/uuid";
import { appAtomRegistry } from "./atom-registry";
import { setPendingConnectionError } from "./use-remote-environment-registry";
import { useAtomCommand } from "./use-atom-command";
import { showGitActionResult } from "./use-vcs-action-state";
import { useThreadSelection } from "./use-thread-selection";
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
export function useSelectedThreadGitActions() {
const updateThreadMetadata = useAtomSet(threadEnvironment.updateMetadata, { mode: "promise" });
const refreshStatus = useAtomSet(vcsEnvironment.refreshStatus, { mode: "promise" });
const switchRef = useAtomSet(vcsEnvironment.switchRef, { mode: "promise" });
const createRef = useAtomSet(vcsEnvironment.createRef, { mode: "promise" });
const createWorktree = useAtomSet(vcsEnvironment.createWorktree, { mode: "promise" });
const pull = useAtomSet(vcsEnvironment.pull, { mode: "promise" });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const refreshStatus = useAtomCommand(vcsEnvironment.refreshStatus, { reportFailure: false });
const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
const createRef = useAtomCommand(vcsEnvironment.createRef, { reportFailure: false });
const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false });
const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
const { selectedThread, selectedThreadProject } = useThreadSelection();
const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
const runStackedAction = useAtomSet(
const runStackedAction = useAtomCommand(
vcsActionManager.runStackedAction({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
}),
{ mode: "promise" },
{ reportFailure: false },
);
const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
@@ -58,7 +63,7 @@ export function useSelectedThreadGitActions() {
readonly worktreePath?: string | null;
},
) => {
await updateThreadMetadata({
return updateThreadMetadata({
environmentId: thread.environmentId,
input: {
threadId: thread.id,
@@ -82,30 +87,30 @@ export function useSelectedThreadGitActions() {
}
const target = { environmentId: selectedThread.environmentId, cwd };
try {
const execute = () =>
refreshStatus({
environmentId: selectedThread.environmentId,
input: { cwd },
});
const result = options?.quiet
? await execute()
: await vcsActionManager.track(
appAtomRegistry,
target,
{
operation: "refresh_status",
label: "Refreshing source control status",
},
execute,
);
setPendingConnectionError(null);
return result;
} catch (error) {
const execute = () =>
refreshStatus({
environmentId: selectedThread.environmentId,
input: { cwd },
});
const result = options?.quiet
? await execute()
: await vcsActionManager.track(
appAtomRegistry,
target,
{
operation: "refresh_status",
label: "Refreshing source control status",
},
execute,
);
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
const message = error instanceof Error ? error.message : "Failed to refresh git status.";
setPendingConnectionError(message);
return null;
}
setPendingConnectionError(null);
return result.value;
},
[refreshStatus, selectedThread, selectedThreadCwd, selectedThreadProject],
);
@@ -118,14 +123,14 @@ export function useSelectedThreadGitActions() {
}, [refreshSelectedThreadGitStatus, selectedThread, selectedThreadProject]);
const runSelectedThreadGitMutation = useCallback(
async <T>(
async <T, E>(
operation: VcsActionOperation,
label: string,
execute: (input: {
readonly thread: EnvironmentThreadShell;
readonly project: EnvironmentProject;
readonly cwd: string;
}) => Promise<T>,
}) => Promise<AtomCommandResult<T, E>>,
options?: { readonly managedExternally?: boolean },
): Promise<T | null> => {
if (!selectedThread || !selectedThreadProject || !selectedThreadCwd) {
@@ -136,25 +141,25 @@ export function useSelectedThreadGitActions() {
environmentId: selectedThread.environmentId,
cwd: selectedThreadCwd,
};
try {
setPendingConnectionError(null);
const run = () =>
execute({
thread: selectedThread,
project: selectedThreadProject,
cwd: selectedThreadCwd,
});
const result =
options?.managedExternally === true
? await run()
: await vcsActionManager.track(appAtomRegistry, target, { operation, label }, run);
return result;
} catch (error) {
setPendingConnectionError(null);
const run = () =>
execute({
thread: selectedThread,
project: selectedThreadProject,
cwd: selectedThreadCwd,
});
const result =
options?.managedExternally === true
? await run()
: await vcsActionManager.track(appAtomRegistry, target, { operation, label }, run);
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
const message = error instanceof Error ? error.message : "Git action failed.";
setPendingConnectionError(message);
showGitActionResult({ type: "error", title: "Git action failed", description: message });
return null;
}
return result.value;
},
[selectedThread, selectedThreadCwd, selectedThreadProject],
);
@@ -174,12 +179,16 @@ export function useSelectedThreadGitActions() {
readonly branch?: string | null;
readonly worktreePath?: string | null;
};
}) => {
}): Promise<AtomCommandResult<void, unknown>> => {
if (input.nextThreadState) {
await updateThreadGitContext(input.thread, input.nextThreadState);
const updateResult = await updateThreadGitContext(input.thread, input.nextThreadState);
if (AsyncResult.isFailure(updateResult)) {
return AsyncResult.failure(updateResult.cause);
}
}
branchState.refresh();
await refreshSelectedThreadGitStatus({ quiet: true, cwd: input.cwd });
return AsyncResult.success(undefined);
},
[branchState, refreshSelectedThreadGitStatus, updateThreadGitContext],
);
@@ -194,14 +203,18 @@ export function useSelectedThreadGitActions() {
environmentId: thread.environmentId,
input: { cwd, refName: branch },
});
await syncSelectedThreadBranchState({
if (AsyncResult.isFailure(result)) {
return result;
}
const syncResult = await syncSelectedThreadBranchState({
thread,
cwd,
nextThreadState: {
branch: result.refName ?? thread.branch,
branch: result.value.refName ?? thread.branch,
worktreePath: selectedThreadWorktreePath,
},
});
return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
},
);
},
@@ -223,14 +236,18 @@ export function useSelectedThreadGitActions() {
environmentId: thread.environmentId,
input: { cwd, refName: branch, switchRef: true },
});
await syncSelectedThreadBranchState({
if (AsyncResult.isFailure(result)) {
return result;
}
const syncResult = await syncSelectedThreadBranchState({
thread,
cwd,
nextThreadState: {
branch: result.refName ?? thread.branch,
branch: result.value.refName ?? thread.branch,
worktreePath: selectedThreadWorktreePath,
},
});
return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
},
);
},
@@ -257,14 +274,18 @@ export function useSelectedThreadGitActions() {
path: null,
},
});
await syncSelectedThreadBranchState({
if (AsyncResult.isFailure(result)) {
return result;
}
const syncResult = await syncSelectedThreadBranchState({
thread,
cwd: result.worktree.path,
cwd: result.value.worktree.path,
nextThreadState: {
branch: result.worktree.refName,
worktreePath: result.worktree.path,
branch: result.value.worktree.refName,
worktreePath: result.value.worktree.path,
},
});
return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
},
);
},
@@ -280,14 +301,18 @@ export function useSelectedThreadGitActions() {
environmentId: thread.environmentId,
input: { cwd },
});
if (AsyncResult.isFailure(result)) {
return result;
}
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
showGitActionResult({
type: "success",
title:
result.status === "skipped_up_to_date"
result.value.status === "skipped_up_to_date"
? "Already up to date"
: `Pulled latest on ${result.refName}`,
: `Pulled latest on ${result.value.refName}`,
});
return result;
},
);
}, [pull, refreshSelectedThreadGitStatus, runSelectedThreadGitMutation]);
@@ -306,23 +331,30 @@ export function useSelectedThreadGitActions() {
...(input.featureBranch ? { featureBranch: input.featureBranch } : {}),
...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
});
if (AsyncResult.isFailure(result)) {
return result;
}
showGitActionResult({
type: "success",
title: result.toast.title,
description: result.toast.description,
prUrl: result.toast.cta.kind === "open_pr" ? result.toast.cta.url : undefined,
title: result.value.toast.title,
description: result.value.toast.description,
prUrl:
result.value.toast.cta.kind === "open_pr" ? result.value.toast.cta.url : undefined,
});
if (result.branch.status === "created" && result.branch.name) {
await syncSelectedThreadBranchState({
if (result.value.branch.status === "created" && result.value.branch.name) {
const syncResult = await syncSelectedThreadBranchState({
thread,
cwd,
nextThreadState: {
branch: result.branch.name,
branch: result.value.branch.name,
worktreePath: selectedThreadWorktreePath,
},
});
if (AsyncResult.isFailure(syncResult)) {
return AsyncResult.failure(syncResult.cause);
}
} else {
await refreshSelectedThreadGitStatus({ quiet: true, cwd });
}
@@ -1,4 +1,4 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
@@ -16,6 +16,7 @@ import {
import { appAtomRegistry } from "./atom-registry";
import { useSelectedThreadDetail } from "./use-thread-detail";
import { useThreadSelection } from "./use-thread-selection";
import { useAtomCommand } from "./use-atom-command";
const userInputDraftsByRequestKeyAtom = Atom.make<
Record<string, Record<string, PendingUserInputDraftAnswer>>
@@ -53,8 +54,14 @@ function setUserInputDraftCustomAnswer(
}
export function useSelectedThreadRequests() {
const respondToApproval = useAtomSet(threadEnvironment.respondToApproval, { mode: "promise" });
const respondToUserInput = useAtomSet(threadEnvironment.respondToUserInput, { mode: "promise" });
const respondToApproval = useAtomCommand(
threadEnvironment.respondToApproval,
"thread approval response",
);
const respondToUserInput = useAtomCommand(
threadEnvironment.respondToUserInput,
"thread user input response",
);
const { selectedThread: selectedThreadShell } = useThreadSelection();
const selectedThread = useSelectedThreadDetail();
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
@@ -114,18 +121,16 @@ export function useSelectedThreadRequests() {
}
setRespondingApprovalId(requestId);
try {
await respondToApproval({
environmentId: selectedThreadShell.environmentId,
input: {
threadId: selectedThreadShell.id,
requestId,
decision,
},
});
} finally {
setRespondingApprovalId((current) => (current === requestId ? null : current));
}
const result = await respondToApproval({
environmentId: selectedThreadShell.environmentId,
input: {
threadId: selectedThreadShell.id,
requestId,
decision,
},
});
setRespondingApprovalId((current) => (current === requestId ? null : current));
return result;
},
[respondToApproval, selectedThreadShell],
);
@@ -136,20 +141,18 @@ export function useSelectedThreadRequests() {
}
setRespondingUserInputId(activePendingUserInput.requestId);
try {
await respondToUserInput({
environmentId: selectedThreadShell.environmentId,
input: {
threadId: selectedThreadShell.id,
requestId: activePendingUserInput.requestId,
answers: activePendingUserInputAnswers,
},
});
} finally {
setRespondingUserInputId((current) =>
current === activePendingUserInput.requestId ? null : current,
);
}
const result = await respondToUserInput({
environmentId: selectedThreadShell.environmentId,
input: {
threadId: selectedThreadShell.id,
requestId: activePendingUserInput.requestId,
answers: activePendingUserInputAnswers,
},
});
setRespondingUserInputId((current) =>
current === activePendingUserInput.requestId ? null : current,
);
return result;
}, [
activePendingUserInput,
activePendingUserInputAnswers,
@@ -1,7 +1,8 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { type MessageId } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useEffect, useRef, useState } from "react";
import { scopedThreadKey } from "../lib/scopedEntities";
@@ -15,6 +16,7 @@ import {
type QueuedThreadMessage,
} from "./thread-outbox-model";
import { threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
import { useThreadOutboxMessages, useThreadOutboxShellStatuses } from "./use-thread-outbox";
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
@@ -43,7 +45,7 @@ function findThread(
}
export function useThreadOutboxDrain(): void {
const startTurn = useAtomSet(threadEnvironment.startTurn, { mode: "promise" });
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
const shellStatuses = useThreadOutboxShellStatuses();
@@ -66,30 +68,31 @@ export function useThreadOutboxDrain(): void {
const sendQueuedMessage = useCallback(
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
try {
await startTurn({
environmentId: queuedMessage.environmentId,
input: {
commandId: queuedMessage.commandId,
threadId: queuedMessage.threadId,
message: {
messageId: queuedMessage.messageId,
role: "user",
text: queuedMessage.text,
attachments: queuedMessage.attachments,
},
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
createdAt: queuedMessage.createdAt,
const deliveryResult = await startTurn({
environmentId: queuedMessage.environmentId,
input: {
commandId: queuedMessage.commandId,
threadId: queuedMessage.threadId,
message: {
messageId: queuedMessage.messageId,
role: "user",
text: queuedMessage.text,
attachments: queuedMessage.attachments,
},
});
} catch (error) {
const retry = shouldRetryThreadOutboxDelivery(error);
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(deliveryResult)) {
const error = Cause.squash(deliveryResult.cause);
const retry =
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
console.warn("[thread-outbox] queued message delivery failed", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
error,
cause: deliveryResult.cause,
retry,
});
if (retry) {
@@ -10,7 +10,10 @@ import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as RelayClient from "@t3tools/shared/relayClient";
import { makeCloudManagedEndpointRuntime } from "./ManagedEndpointRuntime.ts";
import {
classifyRelayClientOutput,
makeCloudManagedEndpointRuntime,
} from "./ManagedEndpointRuntime.ts";
const relayClientAvailableLayer = Layer.succeed(
RelayClient.RelayClient,
@@ -57,6 +60,20 @@ function makeHandle(input: {
}
describe("CloudManagedEndpointRuntime", () => {
it("classifies Cloudflare connection and warning output", () => {
expect(
classifyRelayClientOutput(
"2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
),
).toBe("connected");
expect(
classifyRelayClientOutput("2026-06-17T02:00:00Z ERR Failed to serve tunnel connection"),
).toBe("warning");
expect(classifyRelayClientOutput("2026-06-17T02:00:00Z INF Starting metrics server")).toBe(
"debug",
);
});
it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
Effect.gen(function* () {
const spawned: Array<ChildProcess.StandardCommand> = [];
@@ -113,8 +130,8 @@ describe("CloudManagedEndpointRuntime", () => {
"token-1",
"token-2",
]);
expect(spawned.map((command) => command.options.stdout)).toEqual(["ignore", "ignore"]);
expect(spawned.map((command) => command.options.stderr)).toEqual(["ignore", "ignore"]);
expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
expect(killed).toEqual([100, 101]);
@@ -9,6 +9,7 @@ import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -68,6 +69,13 @@ interface ActiveConnector {
readonly config: RelayManagedEndpointRuntimeConfig;
}
export function classifyRelayClientOutput(line: string): "connected" | "warning" | "debug" {
if (/\bRegistered tunnel connection\b/iu.test(line)) {
return "connected";
}
return /\b(?:ERR|WRN)\b/u.test(line) ? "warning" : "debug";
}
function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
return JSON.stringify({
providerKind: config.providerKind,
@@ -141,6 +149,39 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
);
const observeConnectorOutput = (connector: ActiveConnector) =>
connector.child.all.pipe(
Stream.decodeText(),
Stream.splitLines,
Stream.map((line) => line.trim()),
Stream.filter((line) => line.length > 0),
Stream.runForEach((line) => {
const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
const attributes = {
pid: Number(connector.child.pid),
tunnelId: connector.config.tunnelId,
tunnelName: connector.config.tunnelName,
output,
};
switch (classifyRelayClientOutput(line)) {
case "connected":
return Effect.logInfo("Relay client tunnel connection registered", attributes);
case "warning":
return Effect.logWarning("Relay client reported a transport warning", attributes);
case "debug":
return Effect.logDebug("Relay client output", attributes);
}
}),
Effect.catchCause((cause) =>
Effect.logWarning("Relay client output observer failed", {
cause,
pid: Number(connector.child.pid),
tunnelId: connector.config.tunnelId,
tunnelName: connector.config.tunnelName,
}),
),
);
reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
if (!config || config.providerKind !== "cloudflare_tunnel") {
yield* stopActive;
@@ -190,14 +231,15 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
TUNNEL_TOKEN: config.connectorToken,
},
shell: false,
stderr: "ignore",
stdout: "ignore",
stderr: "pipe",
stdout: "pipe",
}),
)
.pipe(
Effect.provideService(Scope.Scope, connectorScope),
Effect.tap(() =>
Effect.logInfo("Relay client started", {
Effect.tap((child) =>
Effect.logInfo("Relay client process started; waiting for tunnel connection", {
pid: Number(child.pid),
tunnelId: config.tunnelId,
tunnelName: config.tunnelName,
}),
@@ -232,6 +274,7 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
config,
} satisfies ActiveConnector;
yield* Ref.set(activeRef, connector);
yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
yield* Effect.forkIn(superviseConnector(connector), connectorScope);
return {
status: "running",
+38 -29
View File
@@ -1,9 +1,14 @@
import { useAtomSet } from "@effect/atom-react";
import {
mapAtomCommandResult,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import type { AssetCreateUrlResult, AssetResource, EnvironmentId } from "@t3tools/contracts";
import { AsyncResult } from "effect/unstable/reactivity";
import { useEffect, useMemo, useState } from "react";
import { assetEnvironment } from "~/state/assets";
import { usePreparedConnection } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
const REFRESH_MARGIN_MS = 30_000;
@@ -13,28 +18,30 @@ interface CachedAssetUrl {
}
const assetUrlCache = new Map<string, CachedAssetUrl>();
const assetUrlRequests = new Map<string, Promise<CachedAssetUrl>>();
const assetUrlRequests = new Map<string, Promise<AtomCommandResult<CachedAssetUrl, unknown>>>();
function assetCacheKey(environmentId: EnvironmentId, resource: AssetResource): string {
return `${environmentId}:${JSON.stringify(resource)}`;
}
export async function resolveAssetUrl(input: {
export async function resolveAssetUrl<E>(input: {
readonly environmentId: EnvironmentId;
readonly httpBaseUrl: string;
readonly resource: AssetResource;
readonly createUrl: (input: {
readonly environmentId: EnvironmentId;
readonly input: { readonly resource: AssetResource };
}) => Promise<AssetCreateUrlResult>;
}): Promise<CachedAssetUrl> {
}) => Promise<AtomCommandResult<AssetCreateUrlResult, E>>;
}): Promise<AtomCommandResult<CachedAssetUrl, E>> {
const key = assetCacheKey(input.environmentId, input.resource);
const cached = assetUrlCache.get(key);
if (cached && cached.expiresAt - REFRESH_MARGIN_MS > Date.now()) {
return cached;
return AsyncResult.success(cached);
}
const inFlight = assetUrlRequests.get(key);
const inFlight = assetUrlRequests.get(key) as
| Promise<AtomCommandResult<CachedAssetUrl, E>>
| undefined;
if (inFlight) {
return inFlight;
}
@@ -44,23 +51,25 @@ export async function resolveAssetUrl(input: {
environmentId: input.environmentId,
input: { resource: input.resource },
})
.then((result) => {
const cachedResult = {
url: new URL(result.relativeUrl, input.httpBaseUrl).toString(),
expiresAt: result.expiresAt,
};
assetUrlCache.set(key, cachedResult);
return cachedResult;
})
.then((result) =>
mapAtomCommandResult(result, (value) => {
const cachedResult = {
url: new URL(value.relativeUrl, input.httpBaseUrl).toString(),
expiresAt: value.expiresAt,
};
assetUrlCache.set(key, cachedResult);
return cachedResult;
}),
)
.finally(() => {
assetUrlRequests.delete(key);
});
assetUrlRequests.set(key, request);
assetUrlRequests.set(key, request as Promise<AtomCommandResult<CachedAssetUrl, unknown>>);
return request;
}
export function useAssetUrl(environmentId: EnvironmentId, resource: AssetResource): string | null {
const createUrl = useAtomSet(assetEnvironment.createUrl, { mode: "promise" });
const createUrl = useAtomCommand(assetEnvironment.createUrl);
const preparedConnection = usePreparedConnection(environmentId);
const resourceJson = JSON.stringify(resource);
const stableResource = useMemo(() => JSON.parse(resourceJson) as AssetResource, [resourceJson]);
@@ -82,18 +91,18 @@ export function useAssetUrl(environmentId: EnvironmentId, resource: AssetResourc
httpBaseUrl,
resource: stableResource,
createUrl,
})
.then((result) => {
if (cancelled) return;
setUrl(result.url);
refreshTimer = setTimeout(
load,
Math.max(0, result.expiresAt - Date.now() - REFRESH_MARGIN_MS),
);
})
.catch(() => {
if (!cancelled) setUrl(null);
});
}).then((result) => {
if (cancelled) return;
if (result._tag === "Failure") {
setUrl(null);
return;
}
setUrl(result.value.url);
refreshTimer = setTimeout(
load,
Math.max(0, result.value.expiresAt - Date.now() - REFRESH_MARGIN_MS),
);
});
};
load();
+41 -17
View File
@@ -6,6 +6,13 @@ import type {
PreviewSessionSnapshot,
ScopedThreadRef,
} from "@t3tools/contracts";
import {
type AtomCommandResult,
mapAtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import { AsyncResult } from "effect/unstable/reactivity";
import { resolveAssetUrl } from "~/assets/assetUrls";
import { isPreviewSupportedInRuntime, usePreviewStateStore } from "~/previewStateStore";
@@ -14,39 +21,53 @@ import { useRightPanelStore } from "~/rightPanelStore";
export const isBrowserPreviewFile = (path: string): boolean =>
/\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
export type OpenPreviewMutation = (input: {
export class BrowserPreviewUnavailableError extends Data.TaggedError(
"BrowserPreviewUnavailableError",
)<{
readonly message: string;
}> {}
export type OpenPreviewMutation<E = unknown> = (input: {
readonly environmentId: EnvironmentId;
readonly input: PreviewOpenInput;
}) => Promise<PreviewSessionSnapshot>;
}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
export async function openUrlInPreview(input: {
export async function openUrlInPreview<E>(input: {
readonly threadRef: ScopedThreadRef;
readonly url: string;
readonly openPreview: OpenPreviewMutation;
}): Promise<void> {
const snapshot = await input.openPreview({
readonly openPreview: OpenPreviewMutation<E>;
}): Promise<AtomCommandResult<void, E>> {
const result = await input.openPreview({
environmentId: input.threadRef.environmentId,
input: { threadId: input.threadRef.threadId, url: input.url },
});
usePreviewStateStore.getState().applyServerSnapshot(input.threadRef, snapshot);
usePreviewStateStore.getState().rememberUrl(input.threadRef, input.url);
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
return mapAtomCommandResult(result, (snapshot) => {
usePreviewStateStore.getState().applyServerSnapshot(input.threadRef, snapshot);
usePreviewStateStore.getState().rememberUrl(input.threadRef, input.url);
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
}
export async function openFileInPreview(input: {
export async function openFileInPreview<AssetError, PreviewError>(input: {
readonly threadRef: ScopedThreadRef;
readonly filePath: string;
readonly httpBaseUrl: string;
readonly createAssetUrl: (input: {
readonly environmentId: EnvironmentId;
readonly input: { readonly resource: AssetResource };
}) => Promise<AssetCreateUrlResult>;
readonly openPreview: OpenPreviewMutation;
}): Promise<void> {
}) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
readonly openPreview: OpenPreviewMutation<PreviewError>;
}): Promise<AtomCommandResult<void, AssetError | PreviewError | BrowserPreviewUnavailableError>> {
if (!isPreviewSupportedInRuntime()) {
throw new Error("The integrated browser is unavailable in this runtime.");
return AsyncResult.failure(
Cause.fail(
new BrowserPreviewUnavailableError({
message: "The integrated browser is unavailable in this runtime.",
}),
),
);
}
const asset = await resolveAssetUrl({
const assetResult = await resolveAssetUrl({
environmentId: input.threadRef.environmentId,
httpBaseUrl: input.httpBaseUrl,
resource: {
@@ -56,9 +77,12 @@ export async function openFileInPreview(input: {
},
createUrl: input.createAssetUrl,
});
await openUrlInPreview({
if (assetResult._tag === "Failure") {
return AsyncResult.failure(assetResult.cause);
}
return openUrlInPreview({
threadRef: input.threadRef,
url: asset.url,
url: assetResult.value.url,
openPreview: input.openPreview,
});
}
+10 -15
View File
@@ -1,8 +1,4 @@
import {
createManagedRelaySession,
managedRelaySessionAtom,
setManagedRelaySession,
} from "@t3tools/client-runtime/relay";
import { managedRelaySessionAtom, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -18,12 +14,14 @@ vi.mock("@clerk/react", () => ({
vi.mock("../lib/runtime", () => ({
runtime: {
runPromise: vi.fn(),
runPromiseExit: vi.fn(),
},
}));
vi.mock("../state/environments", () => ({
useEnvironmentConnectionActions: vi.fn(),
vi.mock("../connection/catalog", () => ({
environmentCatalog: {
removeRelayEnvironments: {},
},
}));
afterEach(() => {
@@ -45,13 +43,10 @@ describe("managed relay authentication", () => {
});
it("replaces an existing account session atomically", () => {
setManagedRelaySession(
appAtomRegistry,
createManagedRelaySession({
accountId: "account-1",
readClerkToken: async () => "account-1-token",
}),
);
setManagedRelaySession(appAtomRegistry, {
accountId: "account-1",
readClerkToken: async () => "account-1-token",
});
activateManagedRelayAuthentication("account-2", async () => "account-2-token");
+37 -24
View File
@@ -1,15 +1,17 @@
import { useAuth } from "@clerk/react";
import { ManagedRelayClient, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
createManagedRelaySession,
ManagedRelayClient,
setManagedRelaySession,
} from "@t3tools/client-runtime/relay";
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import { useEffect, useRef, type ReactNode } from "react";
import { useEnvironmentConnectionActions } from "../state/environments";
import { environmentCatalog } from "../connection/catalog";
import { runtime } from "../lib/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { useAtomCommand } from "../state/use-atom-command";
import { resolveRelayClerkTokenOptions } from "./publicConfig";
let relayTokenProvider: (() => Promise<string | null>) | null = null;
@@ -28,22 +30,22 @@ export function activateManagedRelayAuthentication(
readClerkToken: () => Promise<string | null>,
): void {
relayTokenProvider = readClerkToken;
setManagedRelaySession(
appAtomRegistry,
createManagedRelaySession({
accountId,
readClerkToken,
}),
);
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken,
});
}
export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
const { getToken, isLoaded, isSignedIn, userId } = useAuth({
treatPendingAsSignedOut: false,
});
const { removeRelayEnvironments } = useEnvironmentConnectionActions();
const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
reportFailure: false,
reportDefect: false,
});
const observedAccountRef = useRef<string | null | undefined>(undefined);
const accountTransitionRef = useRef(Promise.resolve());
const accountTransitionRef = useRef<Promise<void> | null>(null);
useEffect(() => {
if (!isLoaded) {
@@ -56,17 +58,18 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac
observedAccountRef.current = nextAccount;
const queueAccountCleanup = () => {
accountTransitionRef.current = accountTransitionRef.current.then(async () => {
const results = await Promise.allSettled([
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
accountTransitionRef.current = previousTransition.then(async () => {
const results = await Promise.all([
removeRelayEnvironments(),
runtime.runPromise(
ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
settleAsyncResult(() =>
runtime.runPromiseExit(
ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
),
),
]);
for (const result of results) {
if (result.status === "rejected") {
console.warn("[t3-cloud] cloud account cleanup failed", result.reason);
}
reportAtomCommandResult(result, { label: "cloud account cleanup" });
}
});
return accountTransitionRef.current;
@@ -84,18 +87,28 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac
activateManagedRelayAuthentication(userId, tokenProvider);
}
};
const activateAfterTransition = (transition: Promise<void>) => {
void (async () => {
const result = await settlePromise(async () => {
await transition;
activateSession();
});
reportAtomCommandResult(result, { label: "cloud account activation" });
})();
};
if (previousAccount !== undefined && previousAccount !== null && previousAccount !== userId) {
deactivateManagedRelayAuthentication();
void queueAccountCleanup().then(activateSession);
activateAfterTransition(queueAccountCleanup());
} else {
void accountTransitionRef.current.then(activateSession);
activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
}
}
return () => {
cancelled = true;
deactivateManagedRelayAuthentication();
};
}, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
useEffect(() => () => deactivateManagedRelayAuthentication(), []);
return children;
}
@@ -1,6 +1,9 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import { useAtomSet } from "@effect/atom-react";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { ChevronDownIcon, GitBranchIcon, SearchIcon } from "lucide-react";
import {
@@ -20,6 +23,7 @@ import { usePaginatedBranches } from "../state/queries";
import { useProject, useThreadDetail } from "../state/entities";
import { useEnvironmentQuery } from "../state/query";
import { threadEnvironment } from "../state/threads";
import { useAtomCommand } from "../state/use-atom-command";
import { vcsEnvironment } from "../state/vcs";
import { cn } from "../lib/utils";
import { parsePullRequestReference } from "../pullRequestReference";
@@ -89,12 +93,17 @@ export function BranchToolbarBranchSelector({
onCheckoutPullRequestRequest,
onComposerFocusRequest,
}: BranchToolbarBranchSelectorProps) {
const stopThreadSession = useAtomSet(threadEnvironment.stopSession, { mode: "promise" });
const updateThreadMetadata = useAtomSet(threadEnvironment.updateMetadata, {
mode: "promise",
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread metadata update",
);
const switchRef = useAtomCommand(vcsEnvironment.switchRef, {
reportFailure: false,
});
const createRefMutation = useAtomCommand(vcsEnvironment.createRef, {
reportFailure: false,
});
const switchRef = useAtomSet(vcsEnvironment.switchRef, { mode: "promise" });
const createRefMutation = useAtomSet(vcsEnvironment.createRef, { mode: "promise" });
// ---------------------------------------------------------------------------
// Thread / project state (pushed down from parent to colocate with mutation)
// ---------------------------------------------------------------------------
@@ -143,7 +152,7 @@ export function BranchToolbarBranchSelector({
void stopThreadSession({
environmentId,
input: { threadId: activeThreadId },
}).catch(() => undefined);
});
}
if (hasServerThread) {
void updateThreadMetadata({
@@ -296,7 +305,7 @@ export function BranchToolbarBranchSelector({
// ---------------------------------------------------------------------------
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await action();
branchRefState.refresh();
branchStatusQuery.refresh();
});
@@ -335,26 +344,28 @@ export function BranchToolbarBranchSelector({
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(selectedBranchName);
try {
const checkoutResult = await switchRef({
environmentId,
input: {
cwd: selectionTarget.checkoutCwd,
refName: refName.name,
},
});
const checkoutResult = await switchRef({
environmentId,
input: {
cwd: selectionTarget.checkoutCwd,
refName: refName.name,
},
});
if (checkoutResult._tag === "Success") {
const nextBranchName = refName.isRemote
? (checkoutResult.refName ?? selectedBranchName)
? (checkoutResult.value.refName ?? selectedBranchName)
: selectedBranchName;
setOptimisticBranch(nextBranchName);
setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
return;
}
setOptimisticBranch(previousBranch);
if (!isAtomCommandInterrupted(checkoutResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to switch ref.",
description: toBranchActionErrorMessage(error),
description: toBranchActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
}),
);
}
@@ -371,24 +382,26 @@ export function BranchToolbarBranchSelector({
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(name);
try {
const createBranchResult = await createRefMutation({
environmentId,
input: {
cwd: branchCwd,
refName: name,
switchRef: true,
},
});
setOptimisticBranch(createBranchResult.refName);
setThreadBranch(createBranchResult.refName, activeWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
const createBranchResult = await createRefMutation({
environmentId,
input: {
cwd: branchCwd,
refName: name,
switchRef: true,
},
});
if (createBranchResult._tag === "Success") {
setOptimisticBranch(createBranchResult.value.refName);
setThreadBranch(createBranchResult.value.refName, activeWorktreePath);
return;
}
setOptimisticBranch(previousBranch);
if (!isAtomCommandInterrupted(createBranchResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to create and switch ref.",
description: toBranchActionErrorMessage(error),
description: toBranchActionErrorMessage(squashAtomCommandFailure(createBranchResult)),
}),
);
}
@@ -1,7 +1,8 @@
import "../index.css";
import { AsyncResult } from "effect/unstable/reactivity";
import { page } from "vite-plus/test/browser";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { render } from "vitest-browser-react";
const {
@@ -12,9 +13,9 @@ const {
readLocalApiMock,
} = vi.hoisted(() => ({
contextMenuShowMock: vi.fn(),
openFileInPreviewMock: vi.fn(async () => undefined),
openInPreferredEditorMock: vi.fn(async () => "vscode"),
openUrlInPreviewMock: vi.fn(async () => undefined),
openFileInPreviewMock: vi.fn(),
openInPreferredEditorMock: vi.fn(),
openUrlInPreviewMock: vi.fn(),
readLocalApiMock: vi.fn(() => ({
contextMenu: { show: contextMenuShowMock },
server: { getConfig: vi.fn(async () => ({ availableEditors: ["vscode"] })) },
@@ -66,6 +67,12 @@ const threadRef = {
};
describe("ChatMarkdown", () => {
beforeEach(() => {
openInPreferredEditorMock.mockResolvedValue(AsyncResult.success("vscode"));
openFileInPreviewMock.mockResolvedValue(AsyncResult.success(undefined));
openUrlInPreviewMock.mockResolvedValue(AsyncResult.success(undefined));
});
afterEach(() => {
openInPreferredEditorMock.mockClear();
openFileInPreviewMock.mockClear();
+57 -13
View File
@@ -9,6 +9,13 @@ import {
WrapTextIcon,
} from "lucide-react";
import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import React, {
Children,
Suspense,
@@ -64,13 +71,14 @@ import { useEnvironmentQuery } from "../state/query";
import { serverEnvironment } from "../state/server";
import { assetEnvironment } from "../state/assets";
import { usePreparedConnection } from "../state/session";
import { usePreviewActions } from "../state/preview";
import { useAtomSet } from "@effect/atom-react";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import {
isBrowserPreviewFile,
openFileInPreview,
openUrlInPreview,
BrowserPreviewUnavailableError,
} from "../browser/openFileInPreview";
class CodeHighlightErrorBoundary extends React.Component<
@@ -683,8 +691,8 @@ interface MarkdownFileLinkProps {
copyMarkdown: string;
theme: "light" | "dark";
threadRef?: ScopedThreadRef | undefined;
onOpen: (targetPath: string) => Promise<unknown>;
onOpenInBrowser?: (() => Promise<void>) | undefined;
onOpen: (targetPath: string) => Promise<AtomCommandResult<unknown, unknown>>;
onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
className?: string | undefined;
}
@@ -967,7 +975,12 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
className,
}: MarkdownFileLinkProps) {
const handleOpenInEditor = useCallback(() => {
void onOpen(targetPath).catch((error) => {
void (async () => {
const result = await onOpen(targetPath);
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -975,7 +988,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
});
})();
}, [onOpen, targetPath]);
const handleOpenInFilePreview = useCallback(() => {
@@ -987,7 +1000,15 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
}, [handleOpenInEditor, line, threadRef, workspaceRelativePath]);
const handleOpenInBrowser = useCallback(() => {
void onOpenInBrowser?.().catch((error) => {
if (!onOpenInBrowser) {
return;
}
void (async () => {
const result = await onOpenInBrowser();
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -995,7 +1016,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
});
})();
}, [onOpenInBrowser]);
const handleCopy = useCallback((value: string, title: string) => {
@@ -1136,8 +1157,12 @@ function ChatMarkdown({
lineBreaks = false,
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const createAssetUrl = useAtomSet(assetEnvironment.createUrl, { mode: "promise" });
const { open: openPreview } = usePreviewActions();
const createAssetUrl = useAtomCommand(assetEnvironment.createUrl, {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const preparedConnection = usePreparedConnection(threadRef?.environmentId ?? null);
const environmentId = useActiveEnvironmentId();
const serverConfig = useEnvironmentQuery(
@@ -1183,7 +1208,17 @@ function ChatMarkdown({
}, []);
const openExternalLinkInPreview = useCallback(
(url: string) => {
if (!threadRef) return Promise.reject(new Error("Thread context is unavailable."));
if (!threadRef) {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
Cause.fail(
new BrowserPreviewUnavailableError({
message: "Thread context is unavailable.",
}),
),
),
);
}
return openUrlInPreview({ threadRef, url, openPreview });
},
[openPreview, threadRef],
@@ -1191,7 +1226,15 @@ function ChatMarkdown({
const openMarkdownFileInPreview = useCallback(
(path: string) => {
if (!threadRef || preparedConnection._tag === "None") {
return Promise.reject(new Error("Environment is not connected."));
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
Cause.fail(
new BrowserPreviewUnavailableError({
message: "Environment is not connected.",
}),
),
),
);
}
return openFileInPreview({
threadRef,
@@ -1283,7 +1326,8 @@ function ChatMarkdown({
)
.then((clicked) => {
if (clicked === "open-in-browser") {
return openExternalLinkInPreview(href);
void openExternalLinkInPreview(href);
return;
}
if (clicked === "open-external") return api.shell.openExternal(href);
})
File diff suppressed because it is too large. Load diff
+117 -76
View File
@@ -1,6 +1,11 @@
"use client";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import {
DEFAULT_MODEL,
type EnvironmentId,
@@ -36,7 +41,7 @@ import {
type KeyboardEvent,
type ReactNode,
} from "react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useSettings } from "../hooks/useSettings";
@@ -45,6 +50,7 @@ import { filesystemEnvironment } from "../state/filesystem";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { sourceControlEnvironment } from "../state/sourceControl";
import { useAtomCommand } from "../state/use-atom-command";
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
import {
@@ -390,12 +396,14 @@ function OpenCommandPaletteDialog() {
const isActionsOnly = deferredQuery.startsWith(">");
const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
const settings = useSettings();
const createProject = useAtomSet(projectEnvironment.create, { mode: "promise" });
const lookupRepository = useAtomSet(sourceControlEnvironment.lookupRepository, {
mode: "promise",
const createProject = useAtomCommand(projectEnvironment.create, {
reportFailure: false,
});
const cloneRepository = useAtomSet(sourceControlEnvironment.cloneRepository, {
mode: "promise",
const lookupRepository = useAtomCommand(sourceControlEnvironment.lookupRepository, {
reportFailure: false,
});
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
reportFailure: false,
});
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
@@ -1041,34 +1049,62 @@ function OpenCommandPaletteDialog() {
),
});
} else {
await handleNewThread(scopeProjectRef(existing.environmentId, existing.id), {
envMode: settings.defaultThreadEnvMode,
}).catch(() => undefined);
const navigationResult = await settlePromise(() =>
handleNewThread(scopeProjectRef(existing.environmentId, existing.id), {
envMode: settings.defaultThreadEnvMode,
}),
);
if (navigationResult._tag === "Failure") {
const error = squashAtomCommandFailure(navigationResult);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to open project",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
return;
}
}
setOpen(false);
return;
}
try {
const projectId = newProjectId();
await createProject({
environmentId: browseEnvironmentId,
input: {
projectId,
title: inferProjectTitleFromPath(cwd),
workspaceRoot: cwd,
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: DEFAULT_MODEL,
},
const projectId = newProjectId();
const createResult = await createProject({
environmentId: browseEnvironmentId,
input: {
projectId,
title: inferProjectTitleFromPath(cwd),
workspaceRoot: cwd,
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: DEFAULT_MODEL,
},
});
await handleNewThread(scopeProjectRef(browseEnvironmentId, projectId), {
},
});
if (createResult._tag === "Failure") {
if (!isAtomCommandInterrupted(createResult)) {
const error = squashAtomCommandFailure(createResult);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to add project",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
const navigationResult = await settlePromise(() =>
handleNewThread(scopeProjectRef(browseEnvironmentId, projectId), {
envMode: settings.defaultThreadEnvMode,
}).catch(() => undefined);
setOpen(false);
} catch (error) {
}),
);
if (navigationResult._tag === "Failure") {
const error = squashAtomCommandFailure(navigationResult);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1076,7 +1112,9 @@ function OpenCommandPaletteDialog() {
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
return;
}
setOpen(false);
},
[
browseEnvironmentId,
@@ -1126,37 +1164,39 @@ function OpenCommandPaletteDialog() {
}
setIsRemoteProjectLookingUp(true);
try {
const repository = await lookupRepository({
environmentId: addProjectCloneFlow.environmentId,
input: {
provider,
repository: rawRepository,
},
});
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow({
step: "confirm",
environmentId: addProjectCloneFlow.environmentId,
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository,
remoteUrl: repository.sshUrl,
});
setHighlightedItemValue(null);
setQuery(destinationPath);
setBrowseGeneration((generation) => generation + 1);
} catch (error) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Repository lookup failed",
description: errorMessage(error),
}),
);
} finally {
setIsRemoteProjectLookingUp(false);
const lookupResult = await lookupRepository({
environmentId: addProjectCloneFlow.environmentId,
input: {
provider,
repository: rawRepository,
},
});
setIsRemoteProjectLookingUp(false);
if (lookupResult._tag === "Failure") {
if (!isAtomCommandInterrupted(lookupResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Repository lookup failed",
description: errorMessage(squashAtomCommandFailure(lookupResult)),
}),
);
}
return;
}
const repository = lookupResult.value;
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow({
step: "confirm",
environmentId: addProjectCloneFlow.environmentId,
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository,
remoteUrl: repository.sshUrl,
});
setHighlightedItemValue(null);
setQuery(destinationPath);
setBrowseGeneration((generation) => generation + 1);
return;
}
@@ -1196,26 +1236,27 @@ function OpenCommandPaletteDialog() {
}
setIsRemoteProjectCloning(true);
try {
const result = await cloneRepository({
environmentId: addProjectCloneFlow.environmentId,
input: {
remoteUrl: addProjectCloneFlow.remoteUrl,
destinationPath,
},
});
await handleAddProject(result.cwd);
} catch (error) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: errorMessage(error),
}),
);
} finally {
setIsRemoteProjectCloning(false);
const cloneResult = await cloneRepository({
environmentId: addProjectCloneFlow.environmentId,
input: {
remoteUrl: addProjectCloneFlow.remoteUrl,
destinationPath,
},
});
setIsRemoteProjectCloning(false);
if (cloneResult._tag === "Failure") {
if (!isAtomCommandInterrupted(cloneResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: errorMessage(squashAtomCommandFailure(cloneResult)),
}),
);
}
return;
}
await handleAddProject(cloneResult.value.cwd);
}
function browseTo(name: string): void {
+10 -3
View File
@@ -1,6 +1,10 @@
import { Virtualizer } from "@pierre/diffs/react";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
import {
ChevronDownIcon,
@@ -317,9 +321,12 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
const openDiffFile = useCallback(
(filePath: string) => {
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
void openInPreferredEditor(targetPath).catch((error) => {
console.warn("Failed to open diff file in editor.", error);
});
void (async () => {
const result = await openInPreferredEditor(targetPath);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
console.warn("Failed to open diff file in editor.", squashAtomCommandFailure(result));
}
})();
},
[activeCwd, openInPreferredEditor],
);
+154 -103
View File
@@ -1,4 +1,8 @@
import { type ScopedThreadRef } from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type {
GitActionProgressEvent,
GitRunStackedActionResult,
@@ -76,8 +80,8 @@ import { useEnvironmentQuery } from "~/state/query";
import { serverEnvironment } from "~/state/server";
import { sourceControlEnvironment } from "~/state/sourceControl";
import { threadEnvironment } from "~/state/threads";
import { useAtomCommand } from "~/state/use-atom-command";
import { vcsEnvironment } from "~/state/vcs";
import { useAtomSet } from "@effect/atom-react";
import { randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
@@ -475,23 +479,28 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
setPublishError(null);
void publishRepositoryAction
.run({
void (async () => {
const result = await publishRepositoryAction.run({
provider: publishProvider,
repository: publishRepository.trim(),
visibility: publishVisibility,
remoteName: publishRemoteName.trim() || "origin",
protocol: publishProtocol,
})
.then((result) => {
flushSync(() => {
setPublishResult(result);
setPublishWizardStep(2);
});
})
.catch((err: unknown) => {
setPublishError(err instanceof Error ? err.message : "An error occurred.");
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
setPublishError(error instanceof Error ? error.message : "An error occurred.");
}
return;
}
flushSync(() => {
setPublishResult(result.value);
setPublishWizardStep(2);
});
})();
}, [
canSubmitPublishRepository,
props.environmentId,
@@ -957,9 +966,10 @@ export default function GitActionsControl({
activeThreadRef,
draftId,
}: GitActionsControlProps) {
const updateThreadMetadata = useAtomSet(threadEnvironment.updateMetadata, {
mode: "promise",
});
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread branch metadata update",
);
const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
const serverConfig = useEnvironmentQuery(
activeEnvironmentId === null
@@ -1030,7 +1040,7 @@ export default function GitActionsControl({
branch,
worktreePath,
},
}).catch(() => undefined);
});
return;
}
@@ -1364,7 +1374,7 @@ export default function GitActionsControl({
// elapsed description visible until the final success state renders.
return;
case "action_failed":
// Let the rejected mutation publish the error toast to avoid a
// Let the settled mutation publish the error toast to avoid a
// transient intermediate state before the final failure message.
return;
}
@@ -1372,7 +1382,7 @@ export default function GitActionsControl({
updateActiveProgressToast();
};
const promise = runImmediateGitAction.run({
const result = await runImmediateGitAction.run({
actionId,
action,
...(commitMessage ? { commitMessage } : {}),
@@ -1381,78 +1391,84 @@ export default function GitActionsControl({
onProgress: applyProgressEvent,
});
try {
const result = await promise;
activeGitActionProgressRef.current = null;
syncThreadBranchAfterGitAction(result);
const closeResultToast = () => {
activeGitActionProgressRef.current = null;
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
toastManager.close(resolvedProgressToastId);
};
const toastCta = result.toast.cta;
let toastActionProps: {
children: string;
onClick: () => void;
} | null = null;
if (toastCta.kind === "run_action") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: toastCta.action.kind,
});
},
};
} else if (toastCta.kind === "open_pr") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
const api = readLocalApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(toastCta.url);
},
};
return;
}
const successToastData = {
...scopedToastData,
dismissAfterVisibleMs: 10_000,
};
if (toastActionProps) {
toastManager.update(
resolvedProgressToastId,
stackedThreadToast({
type: "success",
title: result.toast.title,
description: result.toast.description,
timeout: 0,
actionProps: toastActionProps,
data: successToastData,
}),
);
} else {
toastManager.update(resolvedProgressToastId, {
type: "success",
title: result.toast.title,
description: result.toast.description,
timeout: 0,
data: successToastData,
});
}
} catch (err) {
activeGitActionProgressRef.current = null;
const error = squashAtomCommandFailure(result);
toastManager.update(
resolvedProgressToastId,
stackedThreadToast({
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
description: error instanceof Error ? error.message : "An error occurred.",
...(scopedToastData !== undefined ? { data: scopedToastData } : {}),
}),
);
return;
}
const actionResult = result.value;
syncThreadBranchAfterGitAction(actionResult);
const closeResultToast = () => {
toastManager.close(resolvedProgressToastId);
};
const toastCta = actionResult.toast.cta;
let toastActionProps: {
children: string;
onClick: () => void;
} | null = null;
if (toastCta.kind === "run_action") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: toastCta.action.kind,
});
},
};
} else if (toastCta.kind === "open_pr") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
const api = readLocalApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(toastCta.url);
},
};
}
const successToastData = {
...scopedToastData,
dismissAfterVisibleMs: 10_000,
};
if (toastActionProps) {
toastManager.update(
resolvedProgressToastId,
stackedThreadToast({
type: "success",
title: actionResult.toast.title,
description: actionResult.toast.description,
timeout: 0,
actionProps: toastActionProps,
data: successToastData,
}),
);
} else {
toastManager.update(resolvedProgressToastId, {
type: "success",
title: actionResult.toast.title,
description: actionResult.toast.description,
timeout: 0,
data: successToastData,
});
}
},
);
@@ -1512,27 +1528,43 @@ export default function GitActionsControl({
return;
}
if (quickAction.kind === "run_pull") {
const promise = pullAction.run();
void toastManager.promise<Awaited<ReturnType<typeof pullAction.run>>, ThreadToastData>(
promise,
{
loading: { title: "Pulling...", data: threadToastData },
success: (result) => ({
title: result.status === "pulled" ? "Pulled" : "Already up to date",
description:
result.status === "pulled"
? `Updated ${result.refName} from ${result.upstreamRef ?? "upstream"}`
: `${result.refName} is already synchronized.`,
data: threadToastData,
}),
error: (err) => ({
title: "Pull failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
}),
},
);
void promise.catch(() => undefined);
const toastId = toastManager.add({
type: "loading",
title: "Pulling...",
timeout: 0,
data: threadToastData,
});
void (async () => {
const result = await pullAction.run();
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
toastManager.close(toastId);
return;
}
const error = squashAtomCommandFailure(result);
toastManager.update(
toastId,
stackedThreadToast({
type: "error",
title: "Pull failed",
description: error instanceof Error ? error.message : "An error occurred.",
...(threadToastData !== undefined ? { data: threadToastData } : {}),
}),
);
return;
}
const pullResult = result.value;
toastManager.update(toastId, {
type: "success",
title: pullResult.status === "pulled" ? "Pulled" : "Already up to date",
description:
pullResult.status === "pulled"
? `Updated ${pullResult.refName} from ${pullResult.upstreamRef ?? "upstream"}`
: `${pullResult.refName} is already synchronized.`,
data: threadToastData,
});
})();
return;
}
if (quickAction.kind === "show_hint") {
@@ -1593,7 +1625,12 @@ export default function GitActionsControl({
return;
}
const target = resolvePathLinkTarget(filePath, gitCwd);
void openInPreferredEditor(target).catch((error) => {
void (async () => {
const result = await openInPreferredEditor(target);
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1602,7 +1639,7 @@ export default function GitActionsControl({
...(threadToastData !== undefined ? { data: threadToastData } : {}),
}),
);
});
})();
},
[gitCwd, openInPreferredEditor, threadToastData],
);
@@ -1619,7 +1656,21 @@ export default function GitActionsControl({
size="xs"
disabled={initAction.isPending}
onClick={() => {
void initAction.run();
void (async () => {
const result = await initAction.run();
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Git initialization failed",
description: error instanceof Error ? error.message : "An error occurred.",
...(threadToastData !== undefined ? { data: threadToastData } : {}),
}),
);
})();
}}
>
<GitBranchPlusIcon className="size-3.5" aria-hidden />
+26 -19
View File
@@ -1,5 +1,8 @@
import { memo, useState, useCallback } from "react";
import { useAtomSet } from "@effect/atom-react";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { Badge } from "./ui/badge";
@@ -28,6 +31,7 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
import { projectEnvironment } from "~/state/projects";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useAtomCommand } from "~/state/use-atom-command";
function stepStatusIcon(status: string): React.ReactNode {
if (status === "completed") {
@@ -76,7 +80,9 @@ const PlanSidebar = memo(function PlanSidebar({
}: PlanSidebarProps) {
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
const writeProjectFile = useAtomSet(projectEnvironment.writeFile, { mode: "promise" });
const writeProjectFile = useAtomCommand(projectEnvironment.writeFile, {
reportFailure: false,
});
const { copyToClipboard, isCopied } = useCopyToClipboard();
const planMarkdown = activeProposedPlan?.planMarkdown ?? null;
@@ -98,22 +104,26 @@ const PlanSidebar = memo(function PlanSidebar({
if (!workspaceRoot || !planMarkdown) return;
const filename = buildProposedPlanMarkdownFilename(planMarkdown);
setIsSavingToWorkspace(true);
void writeProjectFile({
environmentId,
input: {
cwd: workspaceRoot,
relativePath: filename,
contents: normalizePlanMarkdownForExport(planMarkdown),
},
})
.then((result) => {
void (async () => {
const result = await writeProjectFile({
environmentId,
input: {
cwd: workspaceRoot,
relativePath: filename,
contents: normalizePlanMarkdownForExport(planMarkdown),
},
});
setIsSavingToWorkspace(false);
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Plan saved",
description: result.relativePath,
description: result.value.relativePath,
});
})
.catch((error) => {
return;
}
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -121,11 +131,8 @@ const PlanSidebar = memo(function PlanSidebar({
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
})
.then(
() => setIsSavingToWorkspace(false),
() => setIsSavingToWorkspace(false),
);
}
})();
}, [environmentId, planMarkdown, workspaceRoot, writeProjectFile]);
return (
@@ -3,6 +3,11 @@ import type {
ProjectScriptIcon,
ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
BugIcon,
ChevronDownIcon,
@@ -91,14 +96,19 @@ export interface NewProjectScriptInput {
autoOpenPreview: boolean;
}
export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
interface ProjectScriptsControlProps {
scripts: ReadonlyArray<ProjectScript>;
keybindings: ResolvedKeybindingsConfig;
preferredScriptId?: string | null;
onRunScript: (script: ProjectScript) => void;
onAddScript: (input: NewProjectScriptInput) => Promise<void> | void;
onUpdateScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void> | void;
onDeleteScript: (scriptId: string) => Promise<void> | void;
onAddScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
onUpdateScript: (
scriptId: string,
input: NewProjectScriptInput,
) => Promise<ProjectScriptActionResult>;
onDeleteScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
}
export default function ProjectScriptsControl({
@@ -161,6 +171,7 @@ export default function ProjectScriptsControl({
}
setValidationError(null);
let payload: NewProjectScriptInput;
try {
const scriptIdForValidation =
editingScriptId ??
@@ -173,7 +184,7 @@ export default function ProjectScriptsControl({
command: commandForProjectScript(scriptIdForValidation),
});
const trimmedPreviewUrl = previewUrl.trim();
const payload = {
payload = {
name: trimmedName,
command: trimmedCommand,
icon,
@@ -182,16 +193,23 @@ export default function ProjectScriptsControl({
previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
} satisfies NewProjectScriptInput;
if (editingScriptId) {
await onUpdateScript(editingScriptId, payload);
} else {
await onAddScript(payload);
}
setDialogOpen(false);
setIconPickerOpen(false);
} catch (error) {
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
return;
}
const result = editingScriptId
? await onUpdateScript(editingScriptId, payload)
: await onAddScript(payload);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
}
return;
}
setDialogOpen(false);
setIconPickerOpen(false);
};
const openAddDialog = () => {
@@ -1,11 +1,13 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import {
canOneClickUpdateProviderCandidate,
collectProviderUpdateCandidates,
collectUpdatedProviderSnapshots,
firstRejectedProviderUpdateMessage,
firstFailedProviderUpdateMessage,
getProviderUpdateInitialToastView,
getProviderUpdateProgressToastView,
getProviderUpdateRejectedToastView,
@@ -246,12 +248,9 @@ describe("provider update launch notification logic", () => {
expect(
collectUpdatedProviderSnapshots({
results: [
{
status: "fulfilled",
value: {
providers: [updatedPersonal, currentDefaultSibling],
},
},
AsyncResult.success({
providers: [updatedPersonal, currentDefaultSibling],
}),
],
providerInstanceIds: new Set([targetInstanceId]),
}),
@@ -435,11 +434,9 @@ describe("provider update launch notification logic", () => {
});
it("falls back to a rejected RPC message for transport-level failures", () => {
const results: PromiseSettledResult<unknown>[] = [
{ status: "rejected", reason: new Error("WebSocket closed") },
];
const results = [AsyncResult.failure(Cause.die(new Error("WebSocket closed")))];
expect(firstRejectedProviderUpdateMessage(results)).toBe("WebSocket closed");
expect(firstFailedProviderUpdateMessage(results)).toBe("WebSocket closed");
expect(getProviderUpdateRejectedToastView(2, "WebSocket closed")).toMatchObject({
phase: "failed",
title: "Provider updates failed",
@@ -450,9 +447,7 @@ describe("provider update launch notification logic", () => {
it("collects only attempted provider snapshots from update responses", () => {
const codex = provider({ driver: driver("codex") });
const cursor = provider({ driver: driver("cursor") });
const results: PromiseSettledResult<{ readonly providers: ReadonlyArray<ServerProvider> }>[] = [
{ status: "fulfilled", value: { providers: [codex, cursor] } },
];
const results = [AsyncResult.success({ providers: [codex, cursor] })];
expect(
collectUpdatedProviderSnapshots({
@@ -5,6 +5,10 @@ import {
type ProviderInstanceId,
type ServerProvider,
} from "@t3tools/contracts";
import {
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
export type ProviderUpdateCandidate = ServerProvider & {
readonly versionAdvisory: NonNullable<ServerProvider["versionAdvisory"]> & {
@@ -328,14 +332,14 @@ export function getSingleProviderUpdateProgressToastView(
export function collectUpdatedProviderSnapshots(input: {
readonly results: ReadonlyArray<
PromiseSettledResult<{ readonly providers: ReadonlyArray<ServerProvider> }>
AtomCommandResult<{ readonly providers: ReadonlyArray<ServerProvider> }, unknown>
>;
readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
}): ServerProvider[] {
const matchedProviders: ServerProvider[] = [];
for (const result of input.results) {
if (result.status !== "fulfilled") {
if (result._tag === "Failure") {
continue;
}
for (const provider of result.value.providers) {
@@ -348,14 +352,15 @@ export function collectUpdatedProviderSnapshots(input: {
return dedupeProvidersByInstanceId(matchedProviders);
}
export function firstRejectedProviderUpdateMessage(
results: ReadonlyArray<PromiseSettledResult<unknown>>,
export function firstFailedProviderUpdateMessage(
results: ReadonlyArray<AtomCommandResult<unknown, unknown>>,
): string | null {
const rejected = results.find((result) => result.status === "rejected");
if (!rejected) {
const failed = results.find((result) => result._tag === "Failure");
if (!failed || failed._tag !== "Failure") {
return null;
}
return rejected.reason instanceof Error ? rejected.reason.message : "Provider update failed.";
const error = squashAtomCommandFailure(failed);
return error instanceof Error ? error.message : "Provider update failed.";
}
function getUpdateFinishedAt(provider: ServerProvider): string | null {
@@ -1,5 +1,5 @@
import { useNavigate } from "@tanstack/react-router";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import { DownloadIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
@@ -12,7 +12,7 @@ import {
canOneClickUpdateProviderCandidate,
collectProviderUpdateCandidates,
collectUpdatedProviderSnapshots,
firstRejectedProviderUpdateMessage,
firstFailedProviderUpdateMessage,
getProviderUpdateInitialToastView,
getProviderUpdateProgressToastView,
getProviderUpdateRejectedToastView,
@@ -21,6 +21,7 @@ import {
type ProviderUpdateToastView,
} from "./ProviderUpdateLaunchNotification.logic";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { useAtomCommand } from "../state/use-atom-command";
const seenProviderUpdateNotificationKeys = new Set<string>();
type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
@@ -104,7 +105,9 @@ export function ProviderUpdateLaunchNotification() {
const navigate = useNavigate();
const providers = useAtomValue(primaryServerProvidersAtom);
const primaryEnvironment = usePrimaryEnvironment();
const updateProvider = useAtomSet(serverEnvironment.updateProvider, { mode: "promise" });
const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
reportFailure: false,
});
const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
const { dismissedNotificationKeys, dismissNotificationKey } =
useDismissedProviderUpdateNotificationKeys();
@@ -209,27 +212,30 @@ export function ProviderUpdateLaunchNotification() {
openSettings,
});
void Promise.allSettled(
oneClickProviders.map(async (provider) =>
updateProvider({
environmentId: primaryEnvironment.environmentId,
input: {
provider: provider.driver,
instanceId: provider.instanceId,
},
}),
),
).then((results) => {
void (async () => {
const results = [];
for (const provider of oneClickProviders) {
results.push(
await updateProvider({
environmentId: primaryEnvironment.environmentId,
input: {
provider: provider.driver,
instanceId: provider.instanceId,
},
}),
);
}
const activeUpdateToast = activeToastRef.current;
if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
return;
}
const rejectedMessage = firstRejectedProviderUpdateMessage(results);
if (rejectedMessage) {
const failedMessage = firstFailedProviderUpdateMessage(results);
if (failedMessage) {
updateProviderUpdateToast({
toastId,
view: getProviderUpdateRejectedToastView(providerCount, rejectedMessage),
view: getProviderUpdateRejectedToastView(providerCount, failedMessage),
openSettings,
});
activeToastRef.current = null;
@@ -253,7 +259,7 @@ export function ProviderUpdateLaunchNotification() {
if (isTerminalProviderUpdateToastView(view)) {
activeToastRef.current = null;
}
});
})();
};
toastId = toastManager.add(
@@ -1,4 +1,5 @@
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -145,20 +146,23 @@ export function PullRequestThreadDialog({
return;
}
setPreparingMode(mode);
try {
const result = await preparePullRequestThreadAction.run({
reference: parsedReference,
mode,
...(mode === "worktree" ? { threadId } : {}),
});
await onPrepared({
branch: result.branch,
worktreePath: result.worktreePath,
});
onOpenChange(false);
} finally {
setPreparingMode(null);
const result = await preparePullRequestThreadAction.run({
reference: parsedReference,
mode,
...(mode === "worktree" ? { threadId } : {}),
});
setPreparingMode(null);
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
preparePullRequestThreadAction.resetError();
}
return;
}
await onPrepared({
branch: result.value.branch,
worktreePath: result.value.worktreePath,
});
onOpenChange(false);
},
[
cwd,
+196 -74
View File
@@ -19,7 +19,7 @@ import {
ThreadStatusLabel,
} from "./ThreadStatusIndicators";
import { ProjectFavicon } from "./ProjectFavicon";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import { autoAnimate } from "@formkit/auto-animate";
import React, { useCallback, useEffect, memo, useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";
@@ -55,6 +55,11 @@ import {
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { Link, useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router";
import {
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
@@ -78,7 +83,8 @@ import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../termina
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { useThreadDiscoveredPorts } from "../portDiscoveryState";
import { openDiscoveredPort } from "./preview/openDiscoveredPort";
import { usePreviewActions } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { previewEnvironment } from "../state/preview";
import { useUiStateStore } from "../uiStateStore";
import {
resolveShortcutCommand,
@@ -367,7 +373,9 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
environmentId: thread.environmentId,
threadId: thread.id,
});
const { open: openPreview } = usePreviewActions();
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const environment = useEnvironment(thread.environmentId);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const isRemoteThread =
@@ -401,7 +409,21 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
event.preventDefault();
event.stopPropagation();
navigateToThread(threadRef);
void openDiscoveredPort({ threadRef, port, openPreview });
void (async () => {
const result = await openDiscoveredPort({ threadRef, port, openPreview });
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open preview",
description:
error instanceof Error ? error.message : "The preview could not be opened.",
}),
);
})();
},
[discoveredPorts, navigateToThread, openPreview, threadRef],
);
@@ -477,20 +499,48 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
event.preventDefault();
const hasSelection = useThreadSelectionStore.getState().hasSelection();
if (hasSelection && isSelected) {
void handleMultiSelectContextMenu({
x: event.clientX,
y: event.clientY,
});
void (async () => {
const result = await settlePromise(() =>
handleMultiSelectContextMenu({
x: event.clientX,
y: event.clientY,
}),
);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Thread action failed",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
})();
return;
}
if (hasSelection) {
clearSelection();
}
void handleThreadContextMenu(threadRef, {
x: event.clientX,
y: event.clientY,
});
void (async () => {
const result = await settlePromise(() =>
handleThreadContextMenu(threadRef, {
x: event.clientX,
y: event.clientY,
}),
);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Thread action failed",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
})();
},
[clearSelection, handleMultiSelectContextMenu, handleThreadContextMenu, isSelected, threadRef],
);
@@ -985,7 +1035,7 @@ interface SidebarProjectItemProps {
isThreadListExpanded: boolean;
activeRouteThreadKey: string | null;
newThreadShortcutLabel: string | null;
handleNewThread: ReturnType<typeof useNewThreadHandler>["handleNewThread"];
handleNewThread: ReturnType<typeof useNewThreadHandler>;
archiveThread: ReturnType<typeof useThreadActions>["archiveThread"];
deleteThread: ReturnType<typeof useThreadActions>["deleteThread"];
threadJumpLabelByKey: ReadonlyMap<string, string>;
@@ -1031,12 +1081,16 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
(settings) => settings.defaultThreadEnvMode,
);
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const deleteProject = useAtomSet(projectEnvironment.delete, { mode: "promise" });
const updateProject = useAtomSet(projectEnvironment.update, { mode: "promise" });
const updateThreadMetadata = useAtomSet(threadEnvironment.updateMetadata, {
mode: "promise",
const deleteProject = useAtomCommand(projectEnvironment.delete, {
reportFailure: false,
});
const { updateSettings } = useUpdateSettings();
const updateProject = useAtomCommand(projectEnvironment.update, {
reportFailure: false,
});
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const updateSettings = useUpdateSettings();
const sidebarThreadPreviewCount = useSettings<SidebarThreadPreviewCount>(
(settings) => settings.sidebarThreadPreviewCount,
);
@@ -1372,22 +1426,25 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
const removeProject = useCallback(
async (member: SidebarProjectGroupMember, options: { force?: boolean } = {}): Promise<void> => {
async (member: SidebarProjectGroupMember, options: { force?: boolean } = {}) => {
const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
const draftStore = useComposerDraftStore.getState();
const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef);
if (projectDraftThread) {
draftStore.clearDraftThread(projectDraftThread.draftId);
}
draftStore.clearProjectDraftThreadId(memberProjectRef);
await deleteProject({
const result = await deleteProject({
environmentId: member.environmentId,
input: {
projectId: member.id,
...(options.force === true ? { force: true } : {}),
},
});
if (result._tag === "Failure") {
return result;
}
const draftStore = useComposerDraftStore.getState();
const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef);
if (projectDraftThread) {
draftStore.clearDraftThread(projectDraftThread.draftId);
}
draftStore.clearProjectDraftThreadId(memberProjectRef);
return result;
},
[deleteProject],
);
@@ -1451,7 +1508,20 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
await removeProject(member, { force: true });
const result = await removeProject(member, { force: true });
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: `Failed to remove "${member.title}"`,
description:
error instanceof Error
? error.message
: "Unknown error removing project.",
}),
);
}
})().catch((error) => {
const message =
error instanceof Error ? error.message : "Unknown error removing project.";
@@ -1486,9 +1556,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
try {
await removeProject(member);
} catch (error) {
const result = await removeProject(member);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
const message = error instanceof Error ? error.message : "Unknown error removing project.";
console.error("Failed to remove project", {
projectId: member.id,
@@ -1727,9 +1797,22 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
for (const threadKey of threadKeys) {
const thread = sidebarThreadByKeyRef.current.get(threadKey);
if (!thread) continue;
await deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
const result = await deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
deletedThreadKeys,
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete threads",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
}
removeFromSelection(threadKeys);
},
@@ -1784,13 +1867,27 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
if (isMobile) {
setOpenMobile(false);
}
void handleNewThread(scopeProjectRef(member.environmentId, member.id), {
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
...(seedContext.worktreePath !== undefined
? { worktreePath: seedContext.worktreePath }
: {}),
envMode: seedContext.envMode,
});
void (async () => {
const result = await settlePromise(() =>
handleNewThread(scopeProjectRef(member.environmentId, member.id), {
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
...(seedContext.worktreePath !== undefined
? { worktreePath: seedContext.worktreePath }
: {}),
envMode: seedContext.envMode,
}),
);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not create thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
})();
},
[defaultThreadEnvMode, handleNewThread, isMobile, router, setOpenMobile],
);
@@ -1810,16 +1907,30 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
if (!api) {
return;
}
const clicked = await api.contextMenu.show(
project.memberProjects.map((member) => ({
id: member.physicalProjectKey,
label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
})),
{
x: event.clientX,
y: event.clientY,
},
const clickedResult = await settlePromise(() =>
api.contextMenu.show(
project.memberProjects.map((member) => ({
id: member.physicalProjectKey,
label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
})),
{
x: event.clientX,
y: event.clientY,
},
),
);
if (clickedResult._tag === "Failure") {
const error = squashAtomCommandFailure(clickedResult);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not choose environment",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
return;
}
const clicked = clickedResult.value;
if (!clicked) {
return;
}
@@ -1837,9 +1948,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const attemptArchiveThread = useCallback(
async (threadRef: ScopedThreadRef) => {
try {
await archiveThread(threadRef);
} catch (error) {
const result = await archiveThread(threadRef);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1887,15 +1998,15 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
finishRename();
return;
}
try {
await updateThreadMetadata({
environmentId: threadRef.environmentId,
input: {
threadId: threadRef.threadId,
title: trimmed,
},
});
} catch (error) {
const result = await updateThreadMetadata({
environmentId: threadRef.environmentId,
input: {
threadId: threadRef.threadId,
title: trimmed,
},
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1933,16 +2044,17 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
try {
await updateProject({
environmentId: projectRenameTarget.environmentId,
input: {
projectId: projectRenameTarget.id,
title: trimmed,
},
});
const result = await updateProject({
environmentId: projectRenameTarget.environmentId,
input: {
projectId: projectRenameTarget.id,
title: trimmed,
},
});
if (result._tag === "Success") {
closeProjectRenameDialog();
} catch (error) {
} else if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -2046,7 +2158,17 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
}
await deleteThread(threadRef);
const result = await deleteThread(threadRef);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
},
[
appSettingsConfirmThreadDelete,
@@ -2617,7 +2739,7 @@ interface SidebarProjectsContentProps {
threadSortOrder: SidebarThreadSortOrder;
projectGroupingMode: SidebarProjectGroupingMode;
threadPreviewCount: SidebarThreadPreviewCount;
updateSettings: ReturnType<typeof useUpdateSettings>["updateSettings"];
updateSettings: ReturnType<typeof useUpdateSettings>;
openAddProject: () => void;
isManualProjectSorting: boolean;
projectDnDSensors: ReturnType<typeof useSensors>;
@@ -2625,7 +2747,7 @@ interface SidebarProjectsContentProps {
handleProjectDragStart: (event: DragStartEvent) => void;
handleProjectDragEnd: (event: DragEndEvent) => void;
handleProjectDragCancel: (event: DragCancelEvent) => void;
handleNewThread: ReturnType<typeof useNewThreadHandler>["handleNewThread"];
handleNewThread: ReturnType<typeof useNewThreadHandler>;
archiveThread: ReturnType<typeof useThreadActions>["archiveThread"];
deleteThread: ReturnType<typeof useThreadActions>["deleteThread"];
sortedProjects: readonly SidebarProjectSnapshot[];
@@ -2891,8 +3013,8 @@ export default function Sidebar() {
const sidebarProjectGroupingMode = useSettings((s) => s.sidebarProjectGroupingMode);
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const sidebarThreadPreviewCount = useSettings((s) => s.sidebarThreadPreviewCount);
const { updateSettings } = useUpdateSettings();
const { handleNewThread } = useNewThreadHandler();
const updateSettings = useUpdateSettings();
const handleNewThread = useNewThreadHandler();
const { archiveThread, deleteThread } = useThreadActions();
const { isMobile, setOpenMobile } = useSidebar();
const routeThreadRef = useParams({
@@ -1,4 +1,8 @@
import { FitAddon } from "@xterm/addon-fit";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import {
Plus,
SquareSplitHorizontal,
@@ -56,8 +60,9 @@ import { readLocalApi } from "~/localApi";
import { useTerminalController } from "../state/terminalSessions";
import { useEnvironmentQuery } from "../state/query";
import { serverEnvironment } from "../state/server";
import { usePreviewActions } from "../state/preview";
import { previewEnvironment } from "../state/preview";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -310,7 +315,9 @@ export function TerminalViewport({
serverConfig.data?.availableEditors ?? [],
);
const openTerminalPath = useEffectEvent((target: string) => openInPreferredEditor(target));
const { open: openPreview } = usePreviewActions();
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const hasHandledExitRef = useRef(false);
const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
const selectionGestureActiveRef = useRef(false);
@@ -457,9 +464,9 @@ export function TerminalViewport({
const sendTerminalInput = async (data: string, fallbackError: string) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
await writeTerminal(data);
} catch (error) {
const result = await writeTerminal(data);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
}
};
@@ -568,12 +575,17 @@ export function TerminalViewport({
}
const target = resolvePathLinkTarget(match.text, cwd);
void openTerminalPath(target).catch((error) => {
void (async () => {
const result = await openTerminalPath(target);
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open path",
);
});
})();
},
})),
);
@@ -581,9 +593,17 @@ export function TerminalViewport({
});
const inputDisposable = terminal.onData((data) => {
void writeTerminal(data).catch((err) =>
writeSystemMessage(terminal, err instanceof Error ? err.message : "Terminal write failed"),
);
void (async () => {
const result = await writeTerminal(data);
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
writeSystemMessage(
terminal,
error instanceof Error ? error.message : "Terminal write failed",
);
})();
});
const selectionDisposable = terminal.onSelectionChange(() => {
@@ -639,7 +659,7 @@ export function TerminalViewport({
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void resizeTerminal(activeTerminal.cols, activeTerminal.rows).catch(() => undefined);
void resizeTerminal(activeTerminal.cols, activeTerminal.rows);
}, 30);
return () => {
@@ -744,7 +764,7 @@ export function TerminalViewport({
if (wasAtBottom) {
terminal.scrollToBottom();
}
void resizeTerminal(terminal.cols, terminal.rows).catch(() => undefined);
void resizeTerminal(terminal.cols, terminal.rows);
});
return () => {
window.cancelAnimationFrame(frame);
@@ -1,8 +1,9 @@
import type { AuthSessionState } from "@t3tools/contracts";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import React, { startTransition, useEffect, useRef, useState, useCallback } from "react";
import { APP_DISPLAY_NAME } from "../../branding";
import { useEnvironmentActions } from "../../state/environments";
import { connectPairing } from "../../connection/onboarding";
import {
peekPairingTokenFromUrl,
stripPairingTokenFromUrl,
@@ -11,6 +12,7 @@ import {
import { readHostedPairingRequest } from "../../hostedPairing";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { useAtomCommand } from "../../state/use-atom-command";
export function PairingPendingSurface() {
return (
@@ -162,7 +164,9 @@ export function PairingRouteSurface({
}
export function HostedPairingRouteSurface() {
const { connectPairing } = useEnvironmentActions();
const connectPairingEnvironment = useAtomCommand(connectPairing, {
reportFailure: false,
});
const hostedPairingRequestRef = useRef(readHostedPairingRequest());
const [status, setStatus] = useState<"pairing" | "paired" | "error">(() =>
hostedPairingRequestRef.current ? "pairing" : "error",
@@ -198,22 +202,23 @@ export function HostedPairingRouteSurface() {
setCanRetry(false);
tokenSubmittedRef.current = true;
try {
await connectPairing({
host: request.host,
pairingCode: request.token,
});
const result = await connectPairingEnvironment({
host: request.host,
pairingCode: request.token,
});
if (result._tag === "Success") {
setStatus("paired");
setMessage(`${request.label || "The environment"} is saved in this browser.`);
} catch (error) {
tokenSubmittedRef.current = false;
setStatus("error");
setCanRetry(true);
setMessage(
`${errorMessageFromUnknown(error)} If the backend accepted this one-time token, request a new pairing link before retrying.`,
);
return;
}
}, [connectPairing]);
tokenSubmittedRef.current = false;
setStatus("error");
setCanRetry(true);
setMessage(
`${errorMessageFromUnknown(squashAtomCommandFailure(result))} If the backend accepted this one-time token, request a new pairing link before retrying.`,
);
}, [connectPairingEnvironment]);
useEffect(() => {
if (submitAttemptedRef.current) {
@@ -513,7 +513,7 @@ export interface ChatComposerProps {
onRespondToApproval: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
) => Promise<unknown>;
onSelectActivePendingUserInputOption: (questionId: string, optionLabel: string) => void;
onAdvanceActivePendingUserInput: () => void;
onPreviousActivePendingUserInputQuestion: () => void;
+12 -66
View File
@@ -9,14 +9,14 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { memo } from "react";
import GitActionsControl from "../GitActionsControl";
import { type DraftId } from "~/composerDraftStore";
import { PanelBottomIcon, PanelRightIcon } from "lucide-react";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
import { Toggle } from "../ui/toggle";
import ProjectScriptsControl, {
type NewProjectScriptInput,
type ProjectScriptActionResult,
} from "../ProjectScriptsControl";
import { SidebarTrigger } from "../ui/sidebar";
import { OpenInPicker } from "./OpenInPicker";
import { usePrimaryEnvironment } from "../../state/environments";
import { shortcutLabelForCommand } from "../../keybindings";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { cn } from "~/lib/utils";
interface ChatHeaderProps {
@@ -30,17 +30,15 @@ interface ChatHeaderProps {
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
terminalAvailable: boolean;
terminalOpen: boolean;
rightPanelAvailable: boolean;
rightPanelOpen: boolean;
gitCwd: string | null;
onRunProjectScript: (script: ProjectScript) => void;
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
onDeleteProjectScript: (scriptId: string) => Promise<void>;
onToggleTerminal: () => void;
onToggleRightPanel: () => void;
onAddProjectScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
onUpdateProjectScript: (
scriptId: string,
input: NewProjectScriptInput,
) => Promise<ProjectScriptActionResult>;
onDeleteProjectScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
}
export function shouldShowOpenInPicker(input: {
@@ -66,27 +64,19 @@ export const ChatHeader = memo(function ChatHeader({
preferredScriptId,
keybindings,
availableEditors,
terminalAvailable,
terminalOpen,
rightPanelAvailable,
rightPanelOpen,
gitCwd,
onRunProjectScript,
onAddProjectScript,
onUpdateProjectScript,
onDeleteProjectScript,
onToggleTerminal,
onToggleRightPanel,
}: ChatHeaderProps) {
const primaryEnvironmentId = usePrimaryEnvironment()?.environmentId ?? null;
const primaryEnvironmentId = usePrimaryEnvironmentId();
const showOpenInPicker = shouldShowOpenInPicker({
activeProjectName,
activeThreadEnvironmentId,
primaryEnvironmentId,
});
const terminalShortcutLabel = shortcutLabelForCommand(keybindings, "terminal.toggle");
const rightPanelShortcutLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle");
return (
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
@@ -138,50 +128,6 @@ export const ChatHeader = memo(function ChatHeader({
{...(draftId ? { draftId } : {})}
/>
)}
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0"
pressed={terminalOpen}
onPressedChange={onToggleTerminal}
aria-label="Toggle terminal drawer"
variant="ghost"
size="xs"
disabled={!terminalAvailable}
>
<PanelBottomIcon className="size-3.5" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{terminalAvailable
? `Toggle terminal drawer${terminalShortcutLabel ? ` (${terminalShortcutLabel})` : ""}`
: "Terminal drawer is unavailable"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0"
pressed={rightPanelOpen}
onPressedChange={onToggleRightPanel}
aria-label="Toggle right panel"
variant="ghost"
size="xs"
disabled={!rightPanelAvailable}
>
<PanelRightIcon className="size-3.5" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{rightPanelAvailable
? `Toggle right panel${rightPanelShortcutLabel ? ` (${rightPanelShortcutLabel})` : ""}`
: "Right panel is unavailable"}
</TooltipPopup>
</Tooltip>
</div>
</div>
);
@@ -8,7 +8,7 @@ interface ComposerPendingApprovalActionsProps {
onRespondToApproval: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
) => Promise<unknown>;
}
export const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActions({
@@ -113,7 +113,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
() => providedKeybindings ?? [],
[providedKeybindings],
);
const { updateSettings } = useUpdateSettings();
const updateSettings = useUpdateSettings();
const focusSearchInput = useCallback(() => {
searchInputRef.current?.focus({ preventScroll: true });
@@ -1,5 +1,4 @@
import { EditorId, type EnvironmentId, type ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { useAtomSet } from "@effect/atom-react";
import { memo, useCallback, useEffect, useMemo } from "react";
import { isOpenFavoriteEditorShortcut, shortcutLabelForCommand } from "../../keybindings";
import { usePreferredEditor } from "../../editorPreferences";
@@ -34,6 +33,7 @@ import {
} from "../JetBrainsIcons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { shellEnvironment } from "~/state/shell";
import { useAtomCommand } from "~/state/use-atom-command";
const resolveOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
const baseOptions: ReadonlyArray<{ label: string; Icon: Icon; value: EditorId }> = [
@@ -166,9 +166,7 @@ export const OpenInPicker = memo(function OpenInPicker({
compact?: boolean;
enableShortcut?: boolean;
}) {
const openInEditorMutation = useAtomSet(shellEnvironment.openInEditor, {
mode: "promise",
});
const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
const [preferredEditor, setPreferredEditor] = usePreferredEditor(availableEditors);
const options = useMemo(
() => resolveOptions(navigator.platform, availableEditors),
@@ -181,7 +179,7 @@ export const OpenInPicker = memo(function OpenInPicker({
if (!openInCwd) return;
const editor = editorId ?? preferredEditor;
if (!editor) return;
void openInEditorMutation({
const result = openInEditorMutation({
environmentId,
input: {
cwd: openInCwd,
@@ -189,6 +187,7 @@ export const OpenInPicker = memo(function OpenInPicker({
},
});
setPreferredEditor(editor);
return result;
},
[environmentId, openInCwd, openInEditorMutation, preferredEditor, setPreferredEditor],
);
@@ -1,5 +1,8 @@
import { memo, useState, useId } from "react";
import { useAtomSet } from "@effect/atom-react";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import {
buildCollapsedProposedPlanPreviewMarkdown,
@@ -28,6 +31,7 @@ import {
import { stackedThreadToast, toastManager } from "../ui/toast";
import { projectEnvironment } from "~/state/projects";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useAtomCommand } from "~/state/use-atom-command";
export const ProposedPlanCard = memo(function ProposedPlanCard({
planMarkdown,
@@ -46,7 +50,9 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
const [savePath, setSavePath] = useState("");
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
const writeProjectFile = useAtomSet(projectEnvironment.writeFile, { mode: "promise" });
const writeProjectFile = useAtomCommand(projectEnvironment.writeFile, {
reportFailure: false,
});
const { copyToClipboard, isCopied } = useCopyToClipboard({
onError: (error) => {
toastManager.add(
@@ -106,23 +112,27 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
}
setIsSavingToWorkspace(true);
void writeProjectFile({
environmentId,
input: {
cwd: workspaceRoot,
relativePath,
contents: saveContents,
},
})
.then((result) => {
void (async () => {
const result = await writeProjectFile({
environmentId,
input: {
cwd: workspaceRoot,
relativePath,
contents: saveContents,
},
});
setIsSavingToWorkspace(false);
if (result._tag === "Success") {
setIsSaveDialogOpen(false);
toastManager.add({
type: "success",
title: "Plan saved to workspace",
description: result.relativePath,
description: result.value.relativePath,
});
})
.catch((error) => {
return;
}
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -130,15 +140,8 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
description: error instanceof Error ? error.message : "An error occurred while saving.",
}),
);
})
.then(
() => {
setIsSavingToWorkspace(false);
},
() => {
setIsSavingToWorkspace(false);
},
);
}
})();
};
return (
@@ -6,8 +6,11 @@ import type {
} from "@t3tools/contracts";
import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs";
import { Editor } from "@pierre/diffs/editor";
import { useAtomSet } from "@effect/atom-react";
import { EditorProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -27,8 +30,9 @@ import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { buildFileReviewComment } from "~/reviewCommentContext";
import { assetEnvironment } from "~/state/assets";
import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments";
import { usePreviewActions } from "~/state/preview";
import { previewEnvironment } from "~/state/preview";
import { projectEnvironment } from "~/state/projects";
import { useAtomCommand } from "~/state/use-atom-command";
import FileBrowserPanel from "./FileBrowserPanel";
import {
@@ -259,18 +263,17 @@ function useFileSaveCoordinator({
EditableFileSurfaceProps,
"environmentId" | "cwd" | "relativePath" | "onPendingChange"
>): FileSaveCoordinator {
const writeFile = useAtomSet(projectEnvironment.writeFile, { mode: "promise" });
const writeFile = useAtomCommand(projectEnvironment.writeFile);
const coordinator = useMemo(
() =>
new FileSaveCoordinator({
debounceMs: FILE_SAVE_DEBOUNCE_MS,
onPendingChange: (pending) => onPendingChange(relativePath, pending),
persist: async (nextContents) => {
await writeFile({
persist: (nextContents) =>
writeFile({
environmentId,
input: { cwd, relativePath, contents: nextContents },
});
},
}),
onConfirmed: (confirmedContents) => {
confirmProjectFileQueryData(environmentId, cwd, relativePath, confirmedContents);
},
@@ -608,8 +611,12 @@ export default function FilePreviewPanel({
const { resolvedTheme } = useTheme();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
const createAssetUrl = useAtomSet(assetEnvironment.createUrl, { mode: "promise" });
const { open: openPreview } = usePreviewActions();
const createAssetUrl = useAtomCommand(assetEnvironment.createUrl, {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const file = useProjectFileQuery(environmentId, cwd, relativePath);
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
const [markdownView, setMarkdownView] = useState<{
@@ -650,13 +657,18 @@ export default function FilePreviewPanel({
const handleOpenInBrowser = useCallback(() => {
if (!absolutePath || !environmentHttpBaseUrl) return;
void openFileInPreview({
threadRef,
filePath: absolutePath,
httpBaseUrl: environmentHttpBaseUrl,
createAssetUrl,
openPreview,
}).catch((error) => {
void (async () => {
const result = await openFileInPreview({
threadRef,
filePath: absolutePath,
httpBaseUrl: environmentHttpBaseUrl,
createAssetUrl,
openPreview,
});
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -664,7 +676,7 @@ export default function FilePreviewPanel({
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
});
})();
}, [absolutePath, createAssetUrl, environmentHttpBaseUrl, openPreview, threadRef]);
return (
@@ -1,10 +1,13 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { FileSaveCoordinator } from "./fileSaveCoordinator";
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>((resolvePromise) => {
let resolve!: (result: AtomCommandResult<void, never>) => void;
const promise = new Promise<AtomCommandResult<void, never>>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
@@ -17,7 +20,9 @@ describe("FileSaveCoordinator", () => {
it("debounces edits and persists only the latest contents", async () => {
vi.useFakeTimers();
const persist = vi.fn<(contents: string) => Promise<void>>().mockResolvedValue(undefined);
const persist = vi
.fn<(contents: string) => Promise<AtomCommandResult<void, never>>>()
.mockResolvedValue(AsyncResult.success(undefined));
const onPendingChange = vi.fn();
const onConfirmed = vi.fn();
const coordinator = new FileSaveCoordinator({
@@ -44,9 +49,9 @@ describe("FileSaveCoordinator", () => {
vi.useFakeTimers();
const firstWrite = deferred();
const persist = vi
.fn<(contents: string) => Promise<void>>()
.fn<(contents: string) => Promise<AtomCommandResult<void, never>>>()
.mockReturnValueOnce(firstWrite.promise)
.mockResolvedValueOnce(undefined);
.mockResolvedValueOnce(AsyncResult.success(undefined));
const onPendingChange = vi.fn();
const coordinator = new FileSaveCoordinator({
debounceMs: 500,
@@ -61,7 +66,7 @@ describe("FileSaveCoordinator", () => {
await vi.advanceTimersByTimeAsync(500);
expect(persist).toHaveBeenCalledTimes(1);
firstWrite.resolve();
firstWrite.resolve(AsyncResult.success(undefined));
await vi.runAllTimersAsync();
expect(persist).toHaveBeenCalledTimes(2);
expect(persist).toHaveBeenLastCalledWith("latest");
@@ -73,7 +78,9 @@ describe("FileSaveCoordinator", () => {
const onPendingChange = vi.fn();
const coordinator = new FileSaveCoordinator({
debounceMs: 500,
persist: vi.fn().mockRejectedValue(new Error("write failed")),
persist: vi
.fn()
.mockResolvedValue(AsyncResult.failure(Cause.fail(new Error("write failed")))),
onPendingChange,
onConfirmed: vi.fn(),
});
@@ -1,11 +1,13 @@
export interface FileSaveCoordinatorOptions {
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
export interface FileSaveCoordinatorOptions<A, E> {
readonly debounceMs: number;
readonly persist: (contents: string) => Promise<void>;
readonly persist: (contents: string) => Promise<AtomCommandResult<A, E>>;
readonly onPendingChange: (pending: boolean) => void;
readonly onConfirmed: (contents: string) => void;
}
export class FileSaveCoordinator {
export class FileSaveCoordinator<A = unknown, E = unknown> {
private timer: ReturnType<typeof setTimeout> | null = null;
private latestContents = "";
private latestRevision = 0;
@@ -13,7 +15,7 @@ export class FileSaveCoordinator {
private saving = false;
private disposed = false;
constructor(private readonly options: FileSaveCoordinatorOptions) {}
constructor(private readonly options: FileSaveCoordinatorOptions<A, E>) {}
change(contents: string): void {
this.latestContents = contents;
@@ -49,12 +51,11 @@ export class FileSaveCoordinator {
this.saving = true;
const contents = this.latestContents;
const revision = this.latestRevision;
let succeeded = false;
try {
await this.options.persist(contents);
succeeded = true;
const result = await this.options.persist(contents);
const succeeded = result._tag === "Success";
if (succeeded) {
this.options.onConfirmed(contents);
} catch {}
}
this.saving = false;
if (revision === this.latestRevision) {
@@ -1,6 +1,7 @@
"use client";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type {
PreviewAutomationNavigateInput,
PreviewAutomationOpenInput,
@@ -19,9 +20,10 @@ import {
stopBrowserRecording,
useBrowserRecordingStore,
} from "~/browser/browserRecording";
import { previewEnvironment, usePreviewActions } from "~/state/preview";
import { previewEnvironment } from "~/state/preview";
import { useEnvironmentQuery } from "~/state/query";
import { useEnvironmentConnectionState } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
import { previewBridge } from "./previewBridge";
@@ -143,8 +145,21 @@ export function PreviewAutomationOwner(props: {
const connectionState = useEnvironmentConnectionState(threadRef.environmentId).data;
const connectedGeneration =
connectionState?.phase === "connected" ? connectionState.generation : null;
const { open, respondToAutomation, reportAutomationOwner, clearAutomationOwner } =
usePreviewActions();
const open = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const respondToAutomation = useAtomCommand(
previewEnvironment.respondToAutomation,
"preview automation response",
);
const reportAutomationOwner = useAtomCommand(
previewEnvironment.reportAutomationOwner,
"preview automation owner report",
);
const clearAutomationOwner = useAtomCommand(
previewEnvironment.clearAutomationOwner,
"preview automation owner clear",
);
const ownerStateRef = useRef({ threadRef, visible });
const connectedGenerationRef = useRef<number | null>(null);
const handlerRef = useRef<(request: PreviewAutomationRequest) => Promise<unknown>>(
@@ -174,13 +189,17 @@ export function PreviewAutomationOwner(props: {
let activeTabId =
(input.reuseExistingTab ?? true) ? (state.snapshot?.tabId ?? null) : null;
if (!activeTabId) {
const snapshot = await open({
const result = await open({
environmentId: threadRef.environmentId,
input: {
threadId: threadRef.threadId,
...(input.url ? { url: input.url } : {}),
},
});
if (result._tag === "Failure") {
throw squashAtomCommandFailure(result);
}
const snapshot = result.value;
usePreviewStateStore.getState().applyServerSnapshot(threadRef, snapshot);
activeTabId = snapshot.tabId;
} else if (input.url && previewBridge) {
@@ -10,7 +10,8 @@ import { ensureLocalApi } from "~/localApi";
import { selectThreadPreviewState, usePreviewStateStore } from "~/previewStateStore";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { useEnvironment, useEnvironmentHttpBaseUrl } from "~/state/environments";
import { usePreviewActions } from "~/state/preview";
import { previewEnvironment } from "~/state/preview";
import { useAtomCommand } from "~/state/use-atom-command";
import { previewBridge } from "./previewBridge";
import { subscribePreviewAction } from "./previewActionBus";
@@ -62,7 +63,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
const addImage = useComposerDraftStore((store) => store.addImage);
const environment = useEnvironment(threadRef.environmentId);
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
const { open } = usePreviewActions();
const open = useAtomCommand(previewEnvironment.open);
usePreviewSession(threadRef);
@@ -1,4 +1,8 @@
import type { DiscoveredLocalServer, ScopedThreadRef } from "@t3tools/contracts";
import {
mapAtomCommandResult,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
@@ -6,19 +10,21 @@ import { usePreviewStateStore } from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
import { openPreviewSession } from "./openPreviewSession";
export async function openDiscoveredPort(input: {
export async function openDiscoveredPort<E>(input: {
readonly threadRef: ScopedThreadRef;
readonly port: DiscoveredLocalServer;
readonly openPreview: OpenPreviewMutation;
}): Promise<void> {
readonly openPreview: OpenPreviewMutation<E>;
}): Promise<AtomCommandResult<void, E>> {
const resolvedUrl = resolveDiscoveredServerUrl(input.threadRef.environmentId, input.port.url);
const previewState = usePreviewStateStore.getState();
const snapshot = await openPreviewSession({
const result = await openPreviewSession({
openPreview: input.openPreview,
threadRef: input.threadRef,
url: resolvedUrl,
applyServerSnapshot: previewState.applyServerSnapshot,
rememberUrl: previewState.rememberUrl,
});
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
return mapAtomCommandResult(result, (snapshot) => {
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
}
@@ -1,4 +1,6 @@
import type { PreviewOpenInput, PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { describe, expect, it, vi } from "vite-plus/test";
import { openPreviewSession } from "./openPreviewSession";
@@ -23,7 +25,7 @@ const snapshot: PreviewSessionSnapshot = {
describe("openPreviewSession", () => {
it("applies the RPC response without waiting for a preview event", async () => {
const open = vi.fn(async (_input: PreviewOpenInput) => snapshot);
const open = vi.fn(async (_input: PreviewOpenInput) => AsyncResult.success(snapshot));
const applyServerSnapshot = vi.fn();
const rememberUrl = vi.fn();
@@ -39,4 +41,22 @@ describe("openPreviewSession", () => {
expect(applyServerSnapshot).toHaveBeenCalledWith(threadRef, snapshot);
expect(rememberUrl).toHaveBeenCalledWith(threadRef, "https://t3.chat/");
});
it("returns failures without mutating preview state", async () => {
const failure = new Error("preview unavailable");
const applyServerSnapshot = vi.fn();
const rememberUrl = vi.fn();
const result = await openPreviewSession({
openPreview: async () => AsyncResult.failure(Cause.fail(failure)),
threadRef,
url: "t3.chat",
applyServerSnapshot,
rememberUrl,
});
expect(result._tag).toBe("Failure");
expect(applyServerSnapshot).not.toHaveBeenCalled();
expect(rememberUrl).not.toHaveBeenCalled();
});
});
@@ -4,34 +4,39 @@ import type {
PreviewSessionSnapshot,
ScopedThreadRef,
} from "@t3tools/contracts";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import type { PreviewStateStoreState } from "~/previewStateStore";
interface OpenPreviewSessionInput {
interface OpenPreviewSessionInput<E> {
openPreview: (input: {
readonly environmentId: EnvironmentId;
readonly input: PreviewOpenInput;
}) => Promise<PreviewSessionSnapshot>;
}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
threadRef: ScopedThreadRef;
url: string;
applyServerSnapshot: PreviewStateStoreState["applyServerSnapshot"];
rememberUrl: PreviewStateStoreState["rememberUrl"];
}
export async function openPreviewSession(
input: OpenPreviewSessionInput,
): Promise<PreviewSessionSnapshot> {
const snapshot = await input.openPreview({
export async function openPreviewSession<E>(
input: OpenPreviewSessionInput<E>,
): Promise<AtomCommandResult<PreviewSessionSnapshot, E>> {
const result = await input.openPreview({
environmentId: input.threadRef.environmentId,
input: {
threadId: input.threadRef.threadId,
url: input.url,
},
});
if (result._tag === "Failure") {
return result;
}
const snapshot = result.value;
input.applyServerSnapshot(input.threadRef, snapshot);
input.rememberUrl(
input.threadRef,
snapshot.navStatus._tag === "Idle" ? input.url : snapshot.navStatus.url,
);
return snapshot;
return result;
}
@@ -5,17 +5,17 @@ import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
import { isPreviewSupportedInRuntime, usePreviewStateStore } from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
interface OpenTerminalLinkInPreviewInput {
interface OpenTerminalLinkInPreviewInput<E> {
readonly url: string;
readonly position: { x: number; y: number };
readonly threadRef: ScopedThreadRef;
readonly openPreview: OpenPreviewMutation;
readonly openPreview: OpenPreviewMutation<E>;
readonly localApi: LocalApi;
readonly fallbackToBrowser: () => void;
}
export async function openTerminalLinkInPreview(
input: OpenTerminalLinkInPreviewInput,
export async function openTerminalLinkInPreview<E>(
input: OpenTerminalLinkInPreviewInput<E>,
): Promise<void> {
const supportsPreview =
isPreviewableUrl(input.url) &&
@@ -42,16 +42,16 @@ export async function openTerminalLinkInPreview(
}
if (choice === "open-in-preview") {
try {
const snapshot = await input.openPreview({
environmentId: input.threadRef.environmentId,
input: { threadId: input.threadRef.threadId, url: input.url },
});
usePreviewStateStore.getState().applyServerSnapshot(input.threadRef, snapshot);
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
} catch {
const result = await input.openPreview({
environmentId: input.threadRef.environmentId,
input: { threadId: input.threadRef.threadId, url: input.url },
});
if (result._tag === "Failure") {
input.fallbackToBrowser();
return;
}
usePreviewStateStore.getState().applyServerSnapshot(input.threadRef, result.value);
useRightPanelStore.getState().openBrowser(input.threadRef, result.value.tabId);
return;
}
@@ -10,7 +10,8 @@ import { useEffect, useRef } from "react";
import { useBrowserPointerStore } from "~/browser/browserPointerStore";
import { type DesktopPreviewOverlay, usePreviewStateStore } from "~/previewStateStore";
import { usePreviewActions } from "~/state/preview";
import { previewEnvironment } from "~/state/preview";
import { useAtomCommand } from "~/state/use-atom-command";
import { previewBridge } from "./previewBridge";
@@ -22,7 +23,7 @@ export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: str
const { threadRef, tabId } = input;
const applyDesktopState = usePreviewStateStore((state) => state.applyDesktopState);
const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
const { reportStatus } = usePreviewActions();
const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
const bridge = previewBridge;
// One bridge subscription does both jobs (mirror state + forward to
@@ -55,7 +56,7 @@ export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: str
void reportStatus({
environmentId: threadRef.environmentId,
input: reported.input,
}).catch(() => undefined);
});
});
return unsubscribe;
}, [applyDesktopState, bridge, clearBrowserPointer, reportStatus, tabId, threadRef]);
@@ -5,8 +5,9 @@ import type { ScopedThreadRef } from "@t3tools/contracts";
import { useEffect } from "react";
import { readPreviewStateRevision, usePreviewStateStore } from "~/previewStateStore";
import { previewEnvironment, usePreviewActions } from "~/state/preview";
import { previewEnvironment } from "~/state/preview";
import { useEnvironmentQuery } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
import { refreshPreviewSessionState, usePreviewSessionState } from "./previewSessionState";
@@ -18,7 +19,7 @@ export function usePreviewSession(threadRef: ScopedThreadRef): void {
input: {},
}),
);
const { open } = usePreviewActions();
const open = useAtomCommand(previewEnvironment.open);
const applyServerSnapshot = usePreviewStateStore((state) => state.applyServerSnapshot);
const applyServerEvent = usePreviewStateStore((state) => state.applyServerEvent);
@@ -50,13 +51,14 @@ export function usePreviewSession(threadRef: ScopedThreadRef): void {
void open({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, url: recoverableUrl },
})
.then((snapshot) => {
if (cancelled) return;
applyServerSnapshot(threadRef, snapshot);
refreshPreviewSessionState(threadRef);
})
.catch(() => undefined);
}).then((result) => {
if (cancelled) return;
if (result._tag === "Failure") {
return;
}
applyServerSnapshot(threadRef, result.value);
refreshPreviewSessionState(threadRef);
});
return () => {
cancelled = true;
@@ -115,7 +115,7 @@ interface AddProviderInstanceDialogProps {
export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderInstanceDialogProps) {
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const updateSettings = useUpdateSettings();
const [wizardStep, setWizardStep] = useState(0);
const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
@@ -8,7 +8,6 @@ import {
TriangleAlertIcon,
} from "lucide-react";
import { useAuth } from "@clerk/react";
import { useAtomSet } from "@effect/atom-react";
import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from "react";
import {
AuthAccessReadScope,
@@ -30,8 +29,17 @@ import {
type DesktopServerExposureState,
type EnvironmentId,
} from "@t3tools/contracts";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import {
connectionStatusText,
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
@@ -112,14 +120,20 @@ import {
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
} from "~/cloud/linkEnvironmentAtoms";
import { authEnvironment } from "~/state/auth";
import { environmentCatalog } from "~/connection/catalog";
import {
connectPairing as connectPairingAtom,
connectSshEnvironment as connectSshEnvironmentAtom,
} from "~/connection/onboarding";
import { useEnvironmentQuery } from "~/state/query";
import {
type EnvironmentPresentation,
useEnvironmentActions,
useEnvironments,
usePrimaryEnvironment,
useRelayEnvironmentDiscovery,
} from "~/state/environments";
import { relayEnvironmentDiscovery } from "~/state/relay";
import { useAtomCommand } from "../../state/use-atom-command";
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
@@ -1586,70 +1600,99 @@ function CloudLinkSwitch({
function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
const { getToken, isSignedIn } = useAuth();
const { refreshRelayEnvironments } = useEnvironmentActions();
const linkPrimaryEnvironment = useAtomSet(linkPrimaryEnvironmentAtom, { mode: "promise" });
const unlinkPrimaryEnvironment = useAtomSet(unlinkPrimaryEnvironmentAtom, {
mode: "promise",
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const primaryCloudLinkState = usePrimaryCloudLinkState();
const [operationError, setOperationError] = useState<string | null>(null);
const [isUpdating, setIsUpdating] = useState(false);
const reportUpdateFailure = (cause: unknown) => {
const message = cause instanceof Error ? cause.message : "Could not update T3 Cloud access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-cloud] Could not update T3 Cloud", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Cloud",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
const updateLink = async (enabled: boolean) => {
setIsUpdating(true);
setOperationError(null);
try {
const clerkToken = await getToken(resolveRelayClerkTokenOptions());
if (enabled) {
if (!primaryCloudLinkState.target) {
throw new Error("Local environment is not ready yet.");
}
if (!clerkToken) {
throw new Error("Sign in from T3 Cloud settings before linking this environment.");
}
await linkPrimaryEnvironment({
target: primaryCloudLinkState.target,
clerkToken,
});
} else {
if (!primaryCloudLinkState.target) {
throw new Error("Local environment is not ready yet.");
}
await unlinkPrimaryEnvironment({
target: primaryCloudLinkState.target,
clerkToken: clerkToken ?? null,
});
}
primaryCloudLinkState.refresh();
await refreshRelayEnvironments();
toastManager.add({
type: "success",
title: enabled ? "T3 Cloud linked" : "T3 Cloud unlinked",
description: enabled
? "This environment is available through T3 Cloud."
: "This environment is no longer available through T3 Cloud.",
});
} catch (cause) {
const message = cause instanceof Error ? cause.message : "Could not update T3 Cloud access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-cloud] Could not update T3 Cloud", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Cloud",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
} finally {
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
if (tokenResult._tag === "Failure") {
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
setIsUpdating(false);
return;
}
const target = primaryCloudLinkState.target;
if (!target) {
reportUpdateFailure(new Error("Local environment is not ready yet."));
setIsUpdating(false);
return;
}
if (enabled && !tokenResult.value) {
reportUpdateFailure(
new Error("Sign in from T3 Cloud settings before linking this environment."),
);
setIsUpdating(false);
return;
}
const linkResult =
enabled && tokenResult.value
? await linkPrimaryEnvironment({
target,
clerkToken: tokenResult.value,
})
: await unlinkPrimaryEnvironment({
target,
clerkToken: tokenResult.value ?? null,
});
if (linkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(linkResult)) {
reportUpdateFailure(squashAtomCommandFailure(linkResult));
}
setIsUpdating(false);
return;
}
primaryCloudLinkState.refresh();
const refreshResult = await refreshRelayEnvironments();
if (refreshResult._tag === "Failure") {
if (!isAtomCommandInterrupted(refreshResult)) {
reportUpdateFailure(squashAtomCommandFailure(refreshResult));
}
setIsUpdating(false);
return;
}
toastManager.add({
type: "success",
title: enabled ? "T3 Cloud linked" : "T3 Cloud unlinked",
description: enabled
? "This environment is available through T3 Cloud."
: "This environment is no longer available through T3 Cloud.",
});
setIsUpdating(false);
};
const disabledReason = !isSignedIn
? "Sign in from T3 Cloud settings to manage this environment."
@@ -1723,48 +1766,66 @@ function ConfiguredCloudRemoteEnvironmentRows({
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
const environmentsState = useRelayEnvironmentDiscovery();
const { connectRelayEnvironment, refreshRelayEnvironments } = useEnvironmentActions();
const registerEnvironment = useAtomCommand(environmentCatalog.register, {
reportFailure: false,
});
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) =>
registerEnvironment(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[registerEnvironment],
);
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
useEffect(() => {
void refreshRelayEnvironments().catch(() => {
// The discovery state carries the typed failure for presentation.
});
void refreshRelayEnvironments();
}, [refreshRelayEnvironments]);
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
setConnectingEnvironmentId(environment.environmentId);
try {
await connectRelayEnvironment(environment);
const result = await connectRelayEnvironment(environment);
setConnectingEnvironmentId(null);
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Cloud.`,
});
} catch (cause) {
const message =
cause instanceof Error ? cause.message : "Could not connect the T3 Cloud environment.";
const traceId = findErrorTraceId(cause);
console.error("[t3-cloud] Could not connect environment", { message, traceId, cause });
toastManager.add({
type: "error",
title: "Could not connect environment",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
} finally {
setConnectingEnvironmentId(null);
return;
}
if (isAtomCommandInterrupted(result)) {
return;
}
const cause = squashAtomCommandFailure(result);
const message =
cause instanceof Error ? cause.message : "Could not connect the T3 Cloud environment.";
const traceId = findErrorTraceId(cause);
console.error("[t3-cloud] Could not connect environment", { message, traceId, cause });
toastManager.add({
type: "error",
title: "Could not connect environment",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
const connectableEnvironments = [...environmentsState.environments.values()].filter(
@@ -1861,8 +1922,12 @@ export function ConnectionsSettings() {
const desktopBridge = window.desktopBridge;
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const { connectPairing, connectSshEnvironment, removeEnvironment, retryEnvironment } =
useEnvironmentActions();
const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
const connectSshEnvironment = useAtomCommand(connectSshEnvironmentAtom, {
reportFailure: false,
});
const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
const primarySessionState = usePrimarySessionState();
const currentSessionScopes = desktopBridge
@@ -2203,42 +2268,28 @@ export function ConnectionsSettings() {
if (savedBackendMode === "ssh") {
setIsAddingSavedBackend(true);
setSavedBackendError(null);
let target: DesktopSshEnvironmentTarget;
try {
const target = parseManualDesktopSshTarget({
target = parseManualDesktopSshTarget({
host: savedBackendSshHost,
username: savedBackendSshUsername,
port: savedBackendSshPort,
});
await connectSshEnvironment({ target, label: "" });
setSavedBackendHost("");
setSavedBackendPairingCode("");
setSavedBackendSshHost("");
setSavedBackendSshUsername("");
setSavedBackendSshPort("");
setAddBackendDialogOpen(false);
toastManager.add({
type: "success",
title: "Environment connected",
description: `${target.alias} is ready over an SSH-managed tunnel.`,
});
} catch (error) {
const message = formatDesktopSshConnectionError(error);
setSavedBackendError(message);
} finally {
setSavedBackendError(formatDesktopSshConnectionError(error));
setIsAddingSavedBackend(false);
return;
}
const result = await connectSshEnvironment({ target, label: "" });
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
setSavedBackendError(formatDesktopSshConnectionError(squashAtomCommandFailure(result)));
}
setIsAddingSavedBackend(false);
return;
}
return;
}
setIsAddingSavedBackend(true);
setSavedBackendError(null);
try {
const remotePairingInput = parseRemotePairingFields({
host: savedBackendHost,
pairingCode: savedBackendPairingCode,
});
await connectPairing(remotePairingInput);
setSavedBackendHost("");
setSavedBackendPairingCode("");
setSavedBackendSshHost("");
@@ -2247,8 +2298,20 @@ export function ConnectionsSettings() {
setAddBackendDialogOpen(false);
toastManager.add({
type: "success",
title: "Backend added",
description: "The environment is saved and will reconnect on app startup.",
title: "Environment connected",
description: `${target.alias} is ready over an SSH-managed tunnel.`,
});
setIsAddingSavedBackend(false);
return;
}
setIsAddingSavedBackend(true);
setSavedBackendError(null);
let remotePairingInput: ReturnType<typeof parseRemotePairingFields>;
try {
remotePairingInput = parseRemotePairingFields({
host: savedBackendHost,
pairingCode: savedBackendPairingCode,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to add backend.";
@@ -2260,9 +2323,40 @@ export function ConnectionsSettings() {
description: message,
}),
);
} finally {
setIsAddingSavedBackend(false);
return;
}
const result = await connectPairing(remotePairingInput);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
const message = error instanceof Error ? error.message : "Failed to add backend.";
setSavedBackendError(message);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not add backend",
description: message,
}),
);
}
setIsAddingSavedBackend(false);
return;
}
setSavedBackendHost("");
setSavedBackendPairingCode("");
setSavedBackendSshHost("");
setSavedBackendSshUsername("");
setSavedBackendSshPort("");
setAddBackendDialogOpen(false);
toastManager.add({
type: "success",
title: "Backend added",
description: "The environment is saved and will reconnect on app startup.",
});
setIsAddingSavedBackend(false);
}, [
connectPairing,
connectSshEnvironment,
@@ -2277,9 +2371,9 @@ export function ConnectionsSettings() {
const handleConnectSavedBackend = useCallback(
async (environmentId: EnvironmentId) => {
setSavedBackendError(null);
try {
await retryEnvironment(environmentId);
} catch (error) {
const result = await retryEnvironment(environmentId);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
const message = error instanceof Error ? error.message : "Failed to connect backend.";
setSavedBackendError(message);
toastManager.add(
@@ -2298,9 +2392,10 @@ export function ConnectionsSettings() {
async (environmentId: EnvironmentId) => {
setRemovingSavedEnvironmentId(environmentId);
setSavedBackendError(null);
try {
await removeEnvironment(environmentId);
} catch (error) {
const result = await removeEnvironment(environmentId);
setRemovingSavedEnvironmentId(null);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
const message = error instanceof Error ? error.message : "Failed to remove backend.";
setSavedBackendError(message);
toastManager.add(
@@ -2310,8 +2405,6 @@ export function ConnectionsSettings() {
description: message,
}),
);
} finally {
setRemovingSavedEnvironmentId(null);
}
},
[removeEnvironment],
@@ -2348,11 +2441,12 @@ export function ConnectionsSettings() {
} else {
setDiscoveredSshHostsError(null);
}
try {
await connectSshEnvironment({
target,
...(label === undefined ? {} : { label }),
});
const result = await connectSshEnvironment({
target,
...(label === undefined ? {} : { label }),
});
setConnectingSshHostAlias(null);
if (result._tag === "Success") {
setSavedBackendSshHost("");
setSavedBackendSshUsername("");
setSavedBackendSshPort("");
@@ -2364,15 +2458,16 @@ export function ConnectionsSettings() {
: "Environment connected",
description: `${label?.trim() || target.alias} is ready over an SSH-managed tunnel.`,
});
} catch (error) {
return;
}
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
const message = formatDesktopSshConnectionError(error);
if (savedBackendMode === "ssh") {
setSavedBackendError(message);
} else {
setDiscoveredSshHostsError(message);
}
} finally {
setConnectingSshHostAlias(null);
}
},
[connectSshEnvironment, savedBackendMode, savedDesktopSshEnvironmentsByAlias],
@@ -7,7 +7,11 @@ import {
InfoIcon,
RefreshCwIcon,
} from "lucide-react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { useCallback, useMemo, useState, type ReactNode } from "react";
import type {
ServerProcessDiagnosticsEntry,
@@ -33,6 +37,7 @@ import { ScrollArea } from "../ui/scroll-area";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
import { useAtomCommand } from "../../state/use-atom-command";
const NUMBER_FORMAT = new Intl.NumberFormat();
@@ -809,8 +814,12 @@ export function DiagnosticsSettingsPanel() {
const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
const primaryEnvironment = usePrimaryEnvironment();
const environmentId = primaryEnvironment?.environmentId ?? null;
const signalServerProcess = useAtomSet(serverEnvironment.signalProcess, { mode: "promise" });
const openInEditor = useAtomSet(shellEnvironment.openInEditor, { mode: "promise" });
const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {
reportFailure: false,
});
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
reportFailure: false,
});
const [resourceWindowMs, setResourceWindowMs] = useState(15 * 60_000);
const selectedResourceWindow =
RESOURCE_HISTORY_WINDOWS.find((option) => option.windowMs === resourceWindowMs) ??
@@ -866,21 +875,22 @@ export function DiagnosticsSettingsPanel() {
setIsOpeningLogsDirectory(true);
setOpenLogsDirectoryError(null);
void openInEditor({
environmentId,
input: {
cwd: logsDirectoryPath,
editor,
},
})
.catch((error: unknown) => {
void (async () => {
const result = await openInEditor({
environmentId,
input: {
cwd: logsDirectoryPath,
editor,
},
});
setIsOpeningLogsDirectory(false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
setOpenLogsDirectoryError(
error instanceof Error ? error.message : "Unable to open logs folder.",
);
})
.finally(() => {
setIsOpeningLogsDirectory(false);
});
}
})();
}, [availableEditors, environmentId, observability?.logsDirectoryPath, openInEditor]);
const isInitialLoading = isPending && data === null;
@@ -898,43 +908,45 @@ export function DiagnosticsSettingsPanel() {
}
setSignalingPid(pid);
void signalServerProcess({
environmentId,
input: { pid, signal },
})
.then((result) => {
if (!result.signaled) {
const message = Option.getOrUndefined(result.message);
refreshProcesses();
if (isStaleProcessSignalMessage(message)) {
toastManager.add({
type: "info",
title: "Process already exited",
description:
"The process is not a child of the T3 Server. It might already have exited.",
});
return;
}
void (async () => {
const result = await signalServerProcess({
environmentId,
input: { pid, signal },
});
setSignalingPid(null);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add({
type: "error",
title: `Could not send ${signal}`,
description: message ?? `Failed to send ${signal}.`,
description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
});
}
return;
}
if (!result.value.signaled) {
const message = Option.getOrUndefined(result.value.message);
refreshProcesses();
if (isStaleProcessSignalMessage(message)) {
toastManager.add({
type: "info",
title: "Process already exited",
description:
"The process is not a child of the T3 Server. It might already have exited.",
});
return;
}
refreshProcesses();
})
.catch((error: unknown) => {
toastManager.add({
type: "error",
title: `Could not send ${signal}`,
description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
description: message ?? `Failed to send ${signal}.`,
});
})
.finally(() => {
setSignalingPid(null);
});
return;
}
refreshProcesses();
})();
},
[environmentId, refreshProcesses, signalServerProcess],
);
@@ -27,7 +27,11 @@ import {
type ServerRemoveKeybindingInput,
type ServerUpsertKeybindingInput,
} from "@t3tools/contracts";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { isElectron } from "../../env";
import { useOpenInPreferredEditor } from "../../editorPreferences";
@@ -67,6 +71,7 @@ import {
} from "./KeybindingsSettings.logic";
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { useAtomCommand } from "../../state/use-atom-command";
function KeybindingPill({ value }: { value: string }) {
const parts = value.split("+");
@@ -1079,11 +1084,11 @@ export function KeybindingsSettingsPanel() {
const keybindingsConfigPath = useAtomValue(primaryServerKeybindingsConfigPathAtom);
const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
const primaryEnvironment = usePrimaryEnvironment();
const upsertKeybinding = useAtomSet(serverEnvironment.upsertKeybinding, {
mode: "promise",
const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
reportFailure: false,
});
const removeKeybindingMutation = useAtomSet(serverEnvironment.removeKeybinding, {
mode: "promise",
const removeKeybindingMutation = useAtomCommand(serverEnvironment.removeKeybinding, {
reportFailure: false,
});
const openInPreferredEditor = useOpenInPreferredEditor(
primaryEnvironment?.environmentId ?? null,
@@ -1125,14 +1130,19 @@ export function KeybindingsSettingsPanel() {
const openKeybindingsFile = useCallback(() => {
if (!keybindingsConfigPath) return;
void openInPreferredEditor(keybindingsConfigPath).catch((error: unknown) => {
void (async () => {
const result = await openInPreferredEditor(keybindingsConfigPath);
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add({
title: "Unable to open keybindings file",
description:
error instanceof Error ? error.message : "The keybindings file was not opened.",
type: "error",
});
});
})();
}, [keybindingsConfigPath, openInPreferredEditor]);
const saveKeybinding = useCallback(
@@ -1145,23 +1155,25 @@ export function KeybindingsSettingsPanel() {
...(input.when?.trim() ? { when: input.when.trim() } : {}),
...(input.replace ? { replace: input.replace } : {}),
};
void upsertKeybinding({
environmentId: primaryEnvironment.environmentId,
input: payload,
})
.then(() => {
void (async () => {
const result = await upsertKeybinding({
environmentId: primaryEnvironment.environmentId,
input: payload,
});
setSavingCommand(null);
if (result._tag === "Success") {
setIsAddingBinding(false);
})
.catch((error: unknown) => {
return;
}
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add({
title: "Unable to save keybinding",
description: error instanceof Error ? error.message : "The keybinding was not saved.",
type: "error",
});
})
.finally(() => {
setSavingCommand(null);
});
}
})();
},
[primaryEnvironment, upsertKeybinding],
);
@@ -1170,20 +1182,21 @@ export function KeybindingsSettingsPanel() {
(row: KeybindingRow) => {
if (!primaryEnvironment) return;
setSavingCommand(row.command);
void removeKeybindingMutation({
environmentId: primaryEnvironment.environmentId,
input: rowKeybindingTarget(row),
})
.catch((error: unknown) => {
void (async () => {
const result = await removeKeybindingMutation({
environmentId: primaryEnvironment.environmentId,
input: rowKeybindingTarget(row),
});
setSavingCommand(null);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add({
title: "Unable to remove keybinding",
description: error instanceof Error ? error.message : "The keybinding was not removed.",
type: "error",
});
})
.finally(() => {
setSavingCommand(null);
});
}
})();
},
[primaryEnvironment, removeKeybindingMutation],
);
@@ -187,7 +187,13 @@ const mockUpdateProvider = vi.hoisted(() =>
);
const directAtomMocks = vi.hoisted(() => ({
authAccessQuery: Symbol("auth-access-query"),
connectPairingAction: Symbol("connect-pairing-action"),
connectSshEnvironmentAction: Symbol("connect-ssh-environment-action"),
environmentRegisterAction: Symbol("environment-register-action"),
environmentRemoveAction: Symbol("environment-remove-action"),
environmentRetryAction: Symbol("environment-retry-action"),
openInEditorAction: Symbol("open-in-editor-action"),
refreshRelayEnvironmentsAction: Symbol("refresh-relay-environments-action"),
removeKeybindingAction: Symbol("remove-keybinding-action"),
refreshProvidersAction: Symbol("refresh-providers-action"),
signalProcessAction: Symbol("signal-process-action"),
@@ -216,6 +222,24 @@ vi.mock("@effect/atom-react", async (importOriginal) => {
if (atom === directAtomMocks.refreshProvidersAction) {
return mockRefreshProviders;
}
if (atom === directAtomMocks.connectPairingAction) {
return mockConnectPairingEnvironment;
}
if (atom === directAtomMocks.connectSshEnvironmentAction) {
return mockConnectDesktopSshEnvironment;
}
if (atom === directAtomMocks.environmentRegisterAction) {
return mockConnectRelayEnvironment;
}
if (atom === directAtomMocks.environmentRemoveAction) {
return mockRemoveEnvironment;
}
if (atom === directAtomMocks.environmentRetryAction) {
return mockRetryEnvironment;
}
if (atom === directAtomMocks.refreshRelayEnvironmentsAction) {
return mockRefreshRelayEnvironments;
}
if (atom === directAtomMocks.updateProviderAction) {
return mockUpdateProvider;
}
@@ -265,6 +289,25 @@ vi.mock("../../cloud/linkEnvironmentAtoms", async () => {
};
});
vi.mock("../../connection/catalog", () => ({
environmentCatalog: {
register: directAtomMocks.environmentRegisterAction,
remove: directAtomMocks.environmentRemoveAction,
retryNow: directAtomMocks.environmentRetryAction,
},
}));
vi.mock("../../connection/onboarding", () => ({
connectPairing: directAtomMocks.connectPairingAction,
connectSshEnvironment: directAtomMocks.connectSshEnvironmentAction,
}));
vi.mock("../../state/relay", () => ({
relayEnvironmentDiscovery: {
refresh: directAtomMocks.refreshRelayEnvironmentsAction,
},
}));
vi.mock("../../lib/archivedThreadsState", () => ({
refreshArchivedThreadsForEnvironment: vi.fn(),
useArchivedThreadSnapshots: () => ({
@@ -645,14 +688,6 @@ vi.mock("../../state/environments", async () => {
offline: false,
error: EffectOption.none(),
}),
useEnvironmentActions: () => ({
connectPairing: mockConnectPairingEnvironment,
connectSshEnvironment: mockConnectDesktopSshEnvironment,
connectRelayEnvironment: mockConnectRelayEnvironment,
removeEnvironment: mockRemoveEnvironment,
retryEnvironment: mockRetryEnvironment,
refreshRelayEnvironments: mockRefreshRelayEnvironments,
}),
useEnvironmentHttpBaseUrl: () => "http://localhost:3000",
};
});
@@ -2,7 +2,7 @@ import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } from "luci
import { useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { useCallback, useMemo, useRef, useState } from "react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import {
defaultInstanceIdForDriver,
type DesktopUpdateChannel,
@@ -13,6 +13,11 @@ import {
type ScopedThreadRef,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { createModelSelection } from "@t3tools/shared/model";
import * as Arr from "effect/Array";
@@ -84,6 +89,7 @@ import {
useRelativeTimeTick,
} from "./settingsLayout";
import { ProjectFavicon } from "../ProjectFavicon";
import { useAtomCommand } from "../../state/use-atom-command";
const THEME_OPTIONS = [
{
@@ -387,7 +393,7 @@ function AboutVersionSection() {
export function useSettingsRestore(onRestored?: () => void) {
const { theme, setTheme } = useTheme();
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const updateSettings = useUpdateSettings();
const isGitWritingModelDirty = !Equal.equals(
settings.textGenerationModelSelection ?? null,
@@ -487,7 +493,7 @@ export function useSettingsRestore(onRestored?: () => void) {
export function GeneralSettingsPanel() {
const { theme, setTheme } = useTheme();
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const updateSettings = useUpdateSettings();
const observability = useAtomValue(primaryServerObservabilityAtom);
const serverProviders = useAtomValue(primaryServerProvidersAtom);
const diagnosticsDescription = formatDiagnosticsDescription({
@@ -923,13 +929,15 @@ export function GeneralSettingsPanel() {
export function ProviderSettingsPanel() {
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const updateSettings = useUpdateSettings();
const serverProviders = useAtomValue(primaryServerProvidersAtom);
const primaryEnvironment = usePrimaryEnvironment();
const refreshServerProviders = useAtomSet(serverEnvironment.refreshProviders, {
mode: "promise",
const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
reportFailure: false,
});
const updateProvider = useAtomSet(serverEnvironment.updateProvider, { mode: "promise" });
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<
@@ -973,17 +981,17 @@ export function ProviderSettingsPanel() {
setIsRefreshingProviders(false);
return;
}
void refreshServerProviders({
environmentId: primaryEnvironment.environmentId,
input: {},
})
.catch((error: unknown) => {
console.warn("Failed to refresh providers", error);
})
.finally(() => {
refreshingRef.current = false;
setIsRefreshingProviders(false);
void (async () => {
const result = await refreshServerProviders({
environmentId: primaryEnvironment.environmentId,
input: {},
});
refreshingRef.current = false;
setIsRefreshingProviders(false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
console.warn("Failed to refresh providers", squashAtomCommandFailure(result));
}
})();
}, [primaryEnvironment, refreshServerProviders]);
const runProviderUpdate = useCallback(
@@ -1003,15 +1011,15 @@ export function ProviderSettingsPanel() {
return;
}
try {
await updateProvider({
environmentId: primaryEnvironment.environmentId,
input: {
provider: candidate.driver,
instanceId: candidate.instanceId,
},
});
} catch (error) {
const result = await updateProvider({
environmentId: primaryEnvironment.environmentId,
input: {
provider: candidate.driver,
instanceId: candidate.instanceId,
},
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1022,16 +1030,15 @@ export function ProviderSettingsPanel() {
: "The provider update command could not be started.",
}),
);
} finally {
setUpdatingProviderDrivers((previous) => {
if (!previous.has(candidate.driver)) {
return previous;
}
const next = new Set(previous);
next.delete(candidate.driver);
return next;
});
}
setUpdatingProviderDrivers((previous) => {
if (!previous.has(candidate.driver)) {
return previous;
}
const next = new Set(previous);
next.delete(candidate.driver);
return next;
});
},
[primaryEnvironment, updateProvider],
);
@@ -1439,10 +1446,11 @@ export function ArchivedThreadsPanel() {
);
if (clicked === "unarchive") {
try {
await unarchiveThread(threadRef);
const result = await unarchiveThread(threadRef);
if (result._tag === "Success") {
refreshArchivedThreads();
} catch (error) {
} else if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1455,8 +1463,19 @@ export function ArchivedThreadsPanel() {
}
if (clicked === "delete") {
await confirmAndDeleteThread(threadRef);
refreshArchivedThreads();
const result = await confirmAndDeleteThread(threadRef);
if (result._tag === "Success") {
refreshArchivedThreads();
} else if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
}
},
[confirmAndDeleteThread, refreshArchivedThreads, unarchiveThread],
@@ -1500,13 +1519,28 @@ export function ArchivedThreadsPanel() {
key={thread.id}
onContextMenu={(event) => {
event.preventDefault();
void handleArchivedThreadContextMenu(
scopeThreadRef(thread.environmentId, thread.id),
{
x: event.clientX,
y: event.clientY,
},
);
void (async () => {
const result = await settlePromise(() =>
handleArchivedThreadContextMenu(
scopeThreadRef(thread.environmentId, thread.id),
{
x: event.clientX,
y: event.clientY,
},
),
);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Archived thread action failed",
description:
error instanceof Error ? error.message : "An error occurred.",
}),
);
}
})();
}}
title={thread.title}
description={
@@ -1522,10 +1556,17 @@ export function ArchivedThreadsPanel() {
variant="outline"
size="sm"
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
onClick={() =>
void unarchiveThread(scopeThreadRef(thread.environmentId, thread.id))
.then(() => refreshArchivedThreads())
.catch((error) => {
onClick={() => {
void (async () => {
const result = await unarchiveThread(
scopeThreadRef(thread.environmentId, thread.id),
);
if (result._tag === "Success") {
refreshArchivedThreads();
return;
}
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1534,8 +1575,9 @@ export function ArchivedThreadsPanel() {
error instanceof Error ? error.message : "An error occurred.",
}),
);
})
}
}
})();
}}
>
<ArchiveX className="size-3.5" />
<span>Unarchive</span>
@@ -292,7 +292,7 @@ function DiscoveryItemRow({
function GitFetchIntervalSettings() {
const automaticGitFetchInterval = useSettings((settings) => settings.automaticGitFetchInterval);
const { updateSettings } = useUpdateSettings();
const updateSettings = useUpdateSettings();
const automaticGitFetchIntervalSeconds = durationToSeconds(automaticGitFetchInterval);
const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
+3 -10
View File
@@ -16,7 +16,7 @@ import {
PrimaryConnectionTarget,
} from "@t3tools/client-runtime/connection";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
import {
AuthStandardClientScopes,
@@ -93,15 +93,8 @@ const wakeupsLayer = Layer.succeed(
}),
).pipe(Effect.asVoid),
),
Stream.callback<"credentials-changed">((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
appAtomRegistry.subscribe(managedRelaySessionAtom, () => {
Queue.offerUnsafe(queue, "credentials-changed");
}),
),
(unsubscribe) => Effect.sync(unsubscribe),
).pipe(Effect.asVoid),
managedRelayAccountChanges(appAtomRegistry).pipe(
Stream.map(() => "credentials-changed" as const),
),
),
}),
+40 -7
View File
@@ -1,11 +1,25 @@
import { EDITORS, EditorId, type EnvironmentId } from "@t3tools/contracts";
import { useAtomSet } from "@effect/atom-react";
import {
mapAtomCommandResult,
type AtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import { AsyncResult } from "effect/unstable/reactivity";
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";
import { useCallback, useMemo } from "react";
import { shellEnvironment } from "./state/shell";
import { useAtomCommand } from "./state/use-atom-command";
const LAST_EDITOR_KEY = "t3code:last-editor";
export class PreferredEditorUnavailableError extends Data.TaggedError(
"PreferredEditorUnavailableError",
)<{
readonly message: string;
}> {}
export function usePreferredEditor(availableEditors: ReadonlyArray<EditorId>) {
const [lastEditor, setLastEditor] = useLocalStorage(LAST_EDITOR_KEY, null, EditorId);
@@ -32,25 +46,44 @@ export function useOpenInPreferredEditor(
environmentId: EnvironmentId | null,
availableEditors: readonly EditorId[],
) {
const openInEditor = useAtomSet(shellEnvironment.openInEditor, { mode: "promise" });
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
reportFailure: false,
});
type OpenInEditorError = AtomCommandFailure<Awaited<ReturnType<typeof openInEditor>>>;
return useCallback(
async (targetPath: string): Promise<EditorId> => {
async (
targetPath: string,
): Promise<
AtomCommandResult<EditorId, OpenInEditorError | PreferredEditorUnavailableError>
> => {
if (environmentId === null) {
throw new Error("No environment is selected.");
return AsyncResult.failure(
Cause.fail(
new PreferredEditorUnavailableError({
message: "No environment is selected.",
}),
),
);
}
const editor = resolveAndPersistPreferredEditor(availableEditors);
if (!editor) {
throw new Error("No available editors found.");
return AsyncResult.failure(
Cause.fail(
new PreferredEditorUnavailableError({
message: "No available editors found.",
}),
),
);
}
await openInEditor({
const result = await openInEditor({
environmentId,
input: {
cwd: targetPath,
editor,
},
});
return editor;
return mapAtomCommandResult(result, () => editor);
},
[availableEditors, environmentId, openInEditor],
);
+2 -10
View File
@@ -19,7 +19,7 @@ import { resolveThreadRouteTarget } from "../threadRoutes";
import { useUiStateStore } from "../uiStateStore";
import { useSettings } from "./useSettings";
function useNewThreadState() {
export function useNewThreadHandler() {
const projects = useProjects();
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const router = useRouter();
@@ -137,14 +137,6 @@ function useNewThreadState() {
);
}
export function useNewThreadHandler() {
const handleNewThread = useNewThreadState();
return {
handleNewThread,
};
}
export function useHandleNewThread() {
const projectOrder = useUiStateStore((store) => store.projectOrder);
const routeTarget = useParams({
@@ -169,7 +161,7 @@ export function useHandleNewThread() {
getId: getProjectOrderKey,
});
}, [projectOrder, projects]);
const handleNewThread = useNewThreadState();
const handleNewThread = useNewThreadHandler();
return {
activeDraftThread,
+7 -13
View File
@@ -10,19 +10,19 @@
* store.
*/
import { useCallback, useMemo, useSyncExternalStore } from "react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import { ServerSettings, type ServerSettingsPatch } from "@t3tools/contracts";
import {
type ClientSettingsPatch,
type ClientSettings,
DEFAULT_CLIENT_SETTINGS,
DEFAULT_UNIFIED_SETTINGS,
UnifiedSettings,
} from "@t3tools/contracts/settings";
import { ensureLocalApi } from "~/localApi";
import * as Struct from "effect/Struct";
import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
import { usePrimaryEnvironment } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -201,9 +201,10 @@ export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings)
* persisted via RPC. Client keys go through client persistence.
*/
export function useUpdateSettings() {
const persistServerSettings = useAtomSet(serverEnvironment.updateSettings, {
mode: "promise",
});
const persistServerSettings = useAtomCommand(
serverEnvironment.updateSettings,
"server settings update",
);
const primaryEnvironment = usePrimaryEnvironment();
const updateSettings = useCallback(
(patch: Partial<UnifiedSettings>) => {
@@ -228,14 +229,7 @@ export function useUpdateSettings() {
[persistServerSettings, primaryEnvironment],
);
const resetSettings = useCallback(() => {
updateSettings(DEFAULT_UNIFIED_SETTINGS);
}, [updateSettings]);
return {
updateSettings,
resetSettings,
};
return updateSettings;
}
export function __resetClientSettingsPersistenceForTests(): void {
+149 -74
View File
@@ -3,8 +3,11 @@ import {
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { useAtomSet } from "@effect/atom-react";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import { AsyncResult } from "effect/unstable/reactivity";
import { useRouter } from "@tanstack/react-router";
import { useCallback, useMemo, useRef } from "react";
@@ -22,15 +25,30 @@ import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { useSettings } from "./useSettings";
import { useAtomCommand } from "../state/use-atom-command";
export class ThreadArchiveBlockedError extends Data.TaggedError("ThreadArchiveBlockedError")<{
readonly message: string;
}> {}
export function useThreadActions() {
const closeTerminal = useAtomSet(terminalEnvironment.close, { mode: "promise" });
const archiveThreadMutation = useAtomSet(threadEnvironment.archive, { mode: "promise" });
const unarchiveThreadMutation = useAtomSet(threadEnvironment.unarchive, { mode: "promise" });
const deleteThreadMutation = useAtomSet(threadEnvironment.delete, { mode: "promise" });
const stopThreadSession = useAtomSet(threadEnvironment.stopSession, { mode: "promise" });
const removeWorktree = useAtomSet(vcsEnvironment.removeWorktree, { mode: "promise" });
const refreshVcsStatus = useAtomSet(vcsEnvironment.refreshStatus, { mode: "promise" });
const closeTerminal = useAtomCommand(terminalEnvironment.close);
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
reportFailure: false,
});
const unarchiveThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
reportFailure: false,
});
const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
reportFailure: false,
});
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
reportFailure: false,
});
const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
reportFailure: false,
});
const sidebarThreadSortOrder = useSettings((settings) => settings.sidebarThreadSortOrder);
const confirmThreadDelete = useSettings((settings) => settings.confirmThreadDelete);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
@@ -39,7 +57,7 @@ export function useThreadActions() {
);
const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
const router = useRouter();
const { handleNewThread } = useNewThreadHandler();
const handleNewThread = useNewThreadHandler();
// Keep a ref so archiveThread can call handleNewThread without appearing in
// its dependency array — handleNewThread is inherently unstable (depends on
// the projects list) and would otherwise cascade new references into every
@@ -65,38 +83,57 @@ export function useThreadActions() {
const archiveThread = useCallback(
async (target: ScopedThreadRef) => {
const resolved = resolveThreadTarget(target);
if (!resolved) return;
if (!resolved) return AsyncResult.success(undefined);
const { thread, threadRef } = resolved;
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
throw new Error("Cannot archive a running thread.");
return AsyncResult.failure(
Cause.fail(
new ThreadArchiveBlockedError({
message: "Cannot archive a running thread.",
}),
),
);
}
const currentRouteThreadRef = getCurrentRouteThreadRef();
const shouldNavigateToDraft =
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId;
const archiveCommand = archiveThreadMutation({
const archiveResult = await archiveThreadMutation({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId },
});
if (shouldNavigateToDraft) {
await handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId));
if (archiveResult._tag === "Failure") {
return archiveResult;
}
if (shouldNavigateToDraft) {
const navigationResult = await settlePromise(() =>
handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)),
);
if (navigationResult._tag === "Failure") {
return navigationResult;
}
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
return archiveResult;
}
await archiveCommand;
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
return archiveResult;
},
[archiveThreadMutation, getCurrentRouteThreadRef, resolveThreadTarget],
);
const unarchiveThread = useCallback(
async (target: ScopedThreadRef) => {
await unarchiveThreadMutation({
const result = await unarchiveThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
refreshArchivedThreadsForEnvironment(target.environmentId);
if (result._tag === "Success") {
refreshArchivedThreadsForEnvironment(target.environmentId);
}
return result;
},
[unarchiveThreadMutation],
);
@@ -106,12 +143,14 @@ export function useThreadActions() {
const resolved = resolveThreadTarget(target);
if (!resolved) {
// Thread not in main store (e.g. archived thread) — dispatch delete directly.
await deleteThreadMutation({
const result = await deleteThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
refreshArchivedThreadsForEnvironment(target.environmentId);
return;
if (result._tag === "Success") {
refreshArchivedThreadsForEnvironment(target.environmentId);
}
return result;
}
const { thread, threadRef } = resolved;
const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
@@ -144,33 +183,35 @@ export function useThreadActions() {
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;
const localApi = readLocalApi();
const shouldDeleteWorktree =
canDeleteWorktree &&
localApi &&
(await localApi.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
let shouldDeleteWorktree = false;
if (canDeleteWorktree && localApi) {
const confirmationResult = await settlePromise(() =>
localApi.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
),
);
if (confirmationResult._tag === "Failure") {
return confirmationResult;
}
shouldDeleteWorktree = confirmationResult.value;
}
if (thread.session && thread.session.status !== "stopped") {
await stopThreadSession({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId },
}).catch(() => undefined);
});
}
try {
await closeTerminal({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, deleteHistory: true },
});
} catch {
// Terminal may already be closed.
}
await closeTerminal({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, deleteHistory: true },
});
const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
const currentRouteThreadRef = getCurrentRouteThreadRef();
@@ -183,10 +224,13 @@ export function useThreadActions() {
deletedThreadIds,
sortOrder: sidebarThreadSortOrder,
});
await deleteThreadMutation({
const deleteResult = await deleteThreadMutation({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId },
});
if (deleteResult._tag === "Failure") {
return deleteResult;
}
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
clearComposerDraftForThread(threadRef);
clearProjectDraftThreadById(
@@ -201,39 +245,63 @@ export function useThreadActions() {
scopeThreadRef(threadRef.environmentId, fallbackThreadId),
);
if (fallbackThread) {
await router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(
scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
),
replace: true,
});
const navigationResult = await settlePromise(() =>
router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(
scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
),
replace: true,
}),
);
if (navigationResult._tag === "Failure") {
return navigationResult;
}
} else {
await router.navigate({ to: "/", replace: true });
const navigationResult = await settlePromise(() =>
router.navigate({ to: "/", replace: true }),
);
if (navigationResult._tag === "Failure") {
return navigationResult;
}
}
} else {
await router.navigate({ to: "/", replace: true });
const navigationResult = await settlePromise(() =>
router.navigate({ to: "/", replace: true }),
);
if (navigationResult._tag === "Failure") {
return navigationResult;
}
}
}
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
return deleteResult;
}
try {
await removeWorktree({
environmentId: threadRef.environmentId,
input: {
cwd: threadProject.workspaceRoot,
path: orphanedWorktreePath,
force: true,
},
});
await refreshVcsStatus({
environmentId: threadRef.environmentId,
input: { cwd: threadProject.workspaceRoot },
});
} catch (error) {
const removeResult = await removeWorktree({
environmentId: threadRef.environmentId,
input: {
cwd: threadProject.workspaceRoot,
path: orphanedWorktreePath,
force: true,
},
});
const refreshResult =
removeResult._tag === "Success"
? await refreshVcsStatus({
environmentId: threadRef.environmentId,
input: { cwd: threadProject.workspaceRoot },
})
: null;
const cleanupFailure =
removeResult._tag === "Failure"
? removeResult
: refreshResult?._tag === "Failure"
? refreshResult
: null;
if (cleanupFailure) {
const error = squashAtomCommandFailure(cleanupFailure);
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after thread deletion", {
threadId: threadRef.threadId,
@@ -248,7 +316,9 @@ export function useThreadActions() {
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
}),
);
return cleanupFailure;
}
return deleteResult;
},
[
clearComposerDraftForThread,
@@ -273,18 +343,23 @@ export function useThreadActions() {
if (confirmThreadDelete && localApi) {
const title = resolved?.thread.title ?? "this thread";
const confirmed = await localApi.dialogs.confirm(
[
`Delete thread "${title}"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
const confirmationResult = await settlePromise(() =>
localApi.dialogs.confirm(
[
`Delete thread "${title}"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
),
);
if (!confirmed) {
return;
if (confirmationResult._tag === "Failure") {
return confirmationResult;
}
if (!confirmationResult.value) {
return AsyncResult.success(undefined);
}
}
await deleteThread(target);
return deleteThread(target);
},
[confirmThreadDelete, deleteThread, resolveThreadTarget],
);
+19 -20
View File
@@ -6,6 +6,7 @@ import * as Tracer from "effect/Tracer";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { settleAsyncResult, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary";
import { isElectron } from "../env";
import { APP_VERSION } from "~/branding";
@@ -78,8 +79,8 @@ async function applyClientTracingConfig(config: ClientTracingConfig): Promise<vo
const runtime = ManagedRuntime.make(delegateRuntimeLayer);
const scope = runtime.runSync(Scope.make());
try {
const delegate = await runtime.runPromise(
const delegateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
Scope.provide(scope)(
OtlpTracer.make({
url: otlpTracesUrl,
@@ -87,26 +88,28 @@ async function applyClientTracingConfig(config: ClientTracingConfig): Promise<vo
resource: CLIENT_TRACING_RESOURCE,
}),
),
);
if (generation !== configurationGeneration) {
await disposeTracerRuntime(runtime, scope);
return;
}
activeDelegate = delegate;
activeRuntime = runtime;
activeScope = scope;
} catch (error) {
),
);
if (delegateResult._tag === "Failure") {
await disposeTracerRuntime(runtime, scope);
if (generation === configurationGeneration) {
console.warn("Failed to configure client tracing exporter", {
error: formatError(error),
error: formatError(squashAtomCommandFailure(delegateResult)),
otlpTracesUrl,
});
}
return;
}
if (generation !== configurationGeneration) {
await disposeTracerRuntime(runtime, scope);
return;
}
activeDelegate = delegateResult.value;
activeRuntime = runtime;
activeScope = scope;
}
async function disposeTracerRuntime(
@@ -117,12 +120,8 @@ async function disposeTracerRuntime(
return;
}
await runtime
.runPromise(Scope.close(scope, Exit.void))
.catch(() => undefined)
.finally(() => {
runtime.dispose();
});
await settleAsyncResult(() => runtime.runPromiseExit(Scope.close(scope, Exit.void)));
runtime.dispose();
}
function formatError(error: unknown): string {
+19 -10
View File
@@ -1,5 +1,6 @@
import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
Outlet,
createRootRouteWithContext,
@@ -37,7 +38,8 @@ import { configureClientTracing } from "../observability/clientTracing";
import { resolveInitialServerAuthGateState } from "../environments/primary";
import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
import { shellEnvironment } from "../state/shell";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import { useAtomCommand } from "../state/use-atom-command";
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
import {
primaryServerConfigAtom,
@@ -240,7 +242,9 @@ function EventRouter() {
const pathname = useLocation({ select: (loc) => loc.pathname });
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const primaryEnvironment = usePrimaryEnvironment();
const openInEditor = useAtomSet(shellEnvironment.openInEditor, { mode: "promise" });
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
reportFailure: false,
});
const serverConfig = useAtomValue(primaryServerConfigAtom);
const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
@@ -324,13 +328,18 @@ function EventRouter() {
if (!editor) {
return;
}
void openInEditor({
environmentId: primaryEnvironment.environmentId,
input: {
cwd: serverConfig.keybindingsConfigPath,
editor,
},
}).catch((error) => {
void (async () => {
const result = await openInEditor({
environmentId: primaryEnvironment.environmentId,
input: {
cwd: serverConfig.keybindingsConfigPath,
editor,
},
});
if (result._tag === "Success") {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
@@ -339,7 +348,7 @@ function EventRouter() {
error instanceof Error ? error.message : "Unknown error opening file.",
}),
);
});
})();
},
},
}),
+2 -75
View File
@@ -1,23 +1,14 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useAtomValue } from "@effect/atom-react";
import {
connectionCatalogDisplayUrl,
type EnvironmentPresentation as BaseEnvironmentPresentation,
} from "@t3tools/client-runtime/connection";
import {
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import { useMemo } from "react";
import { environmentCatalog } from "../connection/catalog";
import {
connectPairing as connectPairingAtom,
connectSshEnvironment as connectSshEnvironmentAtom,
} from "../connection/onboarding";
import { environmentPresentations, useEnvironmentPresentation } from "./presentation";
import { useEnvironmentQuery } from "./query";
import { relayEnvironmentDiscovery } from "./relay";
@@ -106,67 +97,3 @@ export function useRelayEnvironmentDiscovery() {
export function useEnvironmentConnectionState(environmentId: EnvironmentId) {
return useEnvironmentQuery(environmentCatalog.stateAtom(environmentId));
}
export function useEnvironmentConnectionActions() {
const register = useAtomSet(environmentCatalog.register, { mode: "promise" });
const remove = useAtomSet(environmentCatalog.remove, { mode: "promise" });
const removeRelayEnvironments = useAtomSet(environmentCatalog.removeRelayEnvironments, {
mode: "promise",
});
const retryNow = useAtomSet(environmentCatalog.retryNow, { mode: "promise" });
return useMemo(
() => ({
register,
remove,
removeRelayEnvironments,
retryNow,
}),
[register, remove, removeRelayEnvironments, retryNow],
);
}
export function useEnvironmentActions() {
const { register, remove, retryNow } = useEnvironmentConnectionActions();
const connectPairing = useAtomSet(connectPairingAtom, {
mode: "promise",
});
const connectSshEnvironment = useAtomSet(connectSshEnvironmentAtom, {
mode: "promise",
});
const refreshRelayEnvironments = useAtomSet(relayEnvironmentDiscovery.refresh, {
mode: "promise",
});
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) =>
register(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[register],
);
return useMemo(
() => ({
connectPairing,
connectSshEnvironment,
connectRelayEnvironment,
removeEnvironment: remove,
retryEnvironment: retryNow,
refreshRelayEnvironments,
}),
[
connectPairing,
connectRelayEnvironment,
connectSshEnvironment,
refreshRelayEnvironments,
remove,
retryNow,
],
);
}
-42
View File
@@ -1,47 +1,5 @@
import { useAtomSet } from "@effect/atom-react";
import { createPreviewEnvironmentAtoms } from "@t3tools/client-runtime/state/preview";
import { useMemo } from "react";
import { connectionAtomRuntime } from "../connection/runtime";
export const previewEnvironment = createPreviewEnvironmentAtoms(connectionAtomRuntime);
export function usePreviewActions() {
const open = useAtomSet(previewEnvironment.open, { mode: "promise" });
const navigate = useAtomSet(previewEnvironment.navigate, { mode: "promise" });
const refresh = useAtomSet(previewEnvironment.refresh, { mode: "promise" });
const close = useAtomSet(previewEnvironment.close, { mode: "promise" });
const reportStatus = useAtomSet(previewEnvironment.reportStatus, { mode: "promise" });
const respondToAutomation = useAtomSet(previewEnvironment.respondToAutomation, {
mode: "promise",
});
const reportAutomationOwner = useAtomSet(previewEnvironment.reportAutomationOwner, {
mode: "promise",
});
const clearAutomationOwner = useAtomSet(previewEnvironment.clearAutomationOwner, {
mode: "promise",
});
return useMemo(
() => ({
open,
navigate,
refresh,
close,
reportStatus,
respondToAutomation,
reportAutomationOwner,
clearAutomationOwner,
}),
[
clearAutomationOwner,
close,
navigate,
open,
refresh,
reportAutomationOwner,
reportStatus,
respondToAutomation,
],
);
}
+74 -32
View File
@@ -1,23 +1,31 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import type { VcsActionOperation } from "@t3tools/client-runtime/state/vcs";
import { useAtomValue } from "@effect/atom-react";
import type {
AtomCommandFailure,
AtomCommandResult,
AtomCommandSuccess,
} from "@t3tools/client-runtime/state/runtime";
import {
VcsActionUnavailableError,
type VcsActionOperation,
} from "@t3tools/client-runtime/state/vcs";
import type {
EnvironmentId,
GitActionProgressEvent,
GitResolvePullRequestResult,
GitRunStackedActionResult,
GitStackedAction,
SourceControlCloneProtocol,
SourceControlPublishRepositoryResult,
SourceControlRepositoryVisibility,
ThreadId,
VcsPullResult,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { gitEnvironment } from "./git";
import { useEnvironmentQuery } from "./query";
import { sourceControlEnvironment } from "./sourceControl";
import { useAtomCommand } from "./use-atom-command";
import { vcsActionManager, vcsEnvironment } from "./vcs";
export type SourceControlActionKind =
@@ -32,10 +40,17 @@ export interface SourceControlActionScope {
readonly cwd: string | null;
}
interface SourceControlActionState<TArgs extends ReadonlyArray<unknown>, TResult> {
interface SourceControlActionState<
TArgs extends ReadonlyArray<unknown>,
R extends AtomCommandResult<unknown, unknown>,
> {
readonly isPending: boolean;
readonly error: unknown;
readonly run: (...args: TArgs) => Promise<TResult>;
readonly run: (
...args: TArgs
) => Promise<
AtomCommandResult<AtomCommandSuccess<R>, AtomCommandFailure<R> | VcsActionUnavailableError>
>;
readonly resetError: () => void;
}
@@ -49,14 +64,17 @@ const ACTION_OPERATION = {
preparePullRequestThread: "prepare_pull_request_thread",
} as const satisfies Record<SourceControlActionKind, VcsActionOperation>;
function useAction<TArgs extends ReadonlyArray<unknown>, TResult>(input: {
function useAction<
TArgs extends ReadonlyArray<unknown>,
R extends AtomCommandResult<unknown, unknown>,
>(input: {
readonly kind: SourceControlActionKind;
readonly label: string;
readonly scope: SourceControlActionScope;
readonly action: (...args: TArgs) => Promise<TResult>;
readonly action: (...args: TArgs) => Promise<R>;
readonly onSuccess?: () => void;
readonly managedExternally?: boolean;
}): SourceControlActionState<TArgs, TResult> {
}): SourceControlActionState<TArgs, R> {
const operation = ACTION_OPERATION[input.kind];
const state = useAtomValue(vcsActionManager.stateAtom(input.scope));
const ownsState = state.operation === operation;
@@ -66,11 +84,15 @@ function useAction<TArgs extends ReadonlyArray<unknown>, TResult>(input: {
}, [input.scope, operation]);
const run = useCallback(
async (...args: TArgs): Promise<TResult> => {
const execute = async () => {
async (...args: TArgs) => {
const execute = async (): Promise<
AtomCommandResult<AtomCommandSuccess<R>, AtomCommandFailure<R>>
> => {
const result = await input.action(...args);
input.onSuccess?.();
return result;
if (AsyncResult.isSuccess(result)) {
input.onSuccess?.();
}
return result as AtomCommandResult<AtomCommandSuccess<R>, AtomCommandFailure<R>>;
};
return input.managedExternally === true
? execute()
@@ -95,9 +117,9 @@ function useAction<TArgs extends ReadonlyArray<unknown>, TResult>(input: {
};
}
function requireScope(scope: SourceControlActionScope, unavailableMessage: string) {
function resolveScope(scope: SourceControlActionScope) {
if (scope.environmentId === null || scope.cwd === null) {
throw new Error(unavailableMessage);
return null;
}
return {
environmentId: scope.environmentId,
@@ -105,6 +127,12 @@ function requireScope(scope: SourceControlActionScope, unavailableMessage: strin
};
}
function unavailableResult(message: string) {
return AsyncResult.failure<never, VcsActionUnavailableError>(
Cause.fail(new VcsActionUnavailableError({ message })),
);
}
export function useSourceControlActionRunning(
scope: SourceControlActionScope,
kinds: ReadonlyArray<SourceControlActionKind>,
@@ -118,9 +146,12 @@ export function useSourceControlActionRunning(
}
export function useVcsInitAction(scope: SourceControlActionScope) {
const init = useAtomSet(vcsEnvironment.init, { mode: "promise" });
const init = useAtomCommand(vcsEnvironment.init, { reportFailure: false });
const action = useCallback(async () => {
const target = requireScope(scope, "Git init is unavailable.");
const target = resolveScope(scope);
if (target === null) {
return unavailableResult("Git init is unavailable.");
}
return init({
environmentId: target.environmentId,
input: { cwd: target.cwd },
@@ -130,7 +161,7 @@ export function useVcsInitAction(scope: SourceControlActionScope) {
}
export function useVcsPullAction(scope: SourceControlActionScope) {
const pull = useAtomSet(vcsEnvironment.pull, { mode: "promise" });
const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
const status = useEnvironmentQuery(
scope.environmentId !== null && scope.cwd !== null
? vcsEnvironment.status({
@@ -139,8 +170,11 @@ export function useVcsPullAction(scope: SourceControlActionScope) {
})
: null,
);
const action = useCallback(async (): Promise<VcsPullResult> => {
const target = requireScope(scope, "Git pull is unavailable.");
const action = useCallback(async () => {
const target = resolveScope(scope);
if (target === null) {
return unavailableResult("Git pull is unavailable.");
}
return pull({
environmentId: target.environmentId,
input: { cwd: target.cwd },
@@ -156,8 +190,8 @@ export function useVcsPullAction(scope: SourceControlActionScope) {
}
export function useGitStackedAction(scope: SourceControlActionScope) {
const runStackedAction = useAtomSet(vcsActionManager.runStackedAction(scope), {
mode: "promise",
const runStackedAction = useAtomCommand(vcsActionManager.runStackedAction(scope), {
reportFailure: false,
});
const status = useEnvironmentQuery(
scope.environmentId !== null && scope.cwd !== null
@@ -176,8 +210,10 @@ export function useGitStackedAction(scope: SourceControlActionScope) {
featureBranch?: boolean;
filePaths?: string[];
onProgress?: (event: GitActionProgressEvent) => void;
}): Promise<GitRunStackedActionResult> => {
requireScope(scope, "Git action is unavailable.");
}) => {
if (resolveScope(scope) === null) {
return unavailableResult("Git action is unavailable.");
}
return runStackedAction({
actionId: input.actionId,
action: input.action,
@@ -201,8 +237,8 @@ export function useGitStackedAction(scope: SourceControlActionScope) {
}
export function useSourceControlPublishRepositoryAction(scope: SourceControlActionScope) {
const publishRepository = useAtomSet(sourceControlEnvironment.publishRepository, {
mode: "promise",
const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, {
reportFailure: false,
});
const status = useEnvironmentQuery(
scope.environmentId !== null && scope.cwd !== null
@@ -219,8 +255,11 @@ export function useSourceControlPublishRepositoryAction(scope: SourceControlActi
visibility: SourceControlRepositoryVisibility;
remoteName: string;
protocol: SourceControlCloneProtocol;
}): Promise<SourceControlPublishRepositoryResult> => {
const target = requireScope(scope, "Repository publishing is unavailable.");
}) => {
const target = resolveScope(scope);
if (target === null) {
return unavailableResult("Repository publishing is unavailable.");
}
return publishRepository({
environmentId: target.environmentId,
input: {
@@ -241,12 +280,15 @@ export function useSourceControlPublishRepositoryAction(scope: SourceControlActi
}
export function usePreparePullRequestThreadAction(scope: SourceControlActionScope) {
const preparePullRequestThread = useAtomSet(gitEnvironment.preparePullRequestThread, {
mode: "promise",
const preparePullRequestThread = useAtomCommand(gitEnvironment.preparePullRequestThread, {
reportFailure: false,
});
const action = useCallback(
async (input: { reference: string; mode: "local" | "worktree"; threadId?: ThreadId }) => {
const target = requireScope(scope, "Pull request thread preparation is unavailable.");
const target = resolveScope(scope);
if (target === null) {
return unavailableResult("Pull request thread preparation is unavailable.");
}
return preparePullRequestThread({
environmentId: target.environmentId,
input: {
+37 -9
View File
@@ -5,12 +5,26 @@ import {
type KnownTerminalSession,
type TerminalSessionState,
} from "@t3tools/client-runtime/state/terminal";
import {
type AtomCommandFailure,
type AtomCommandResult,
type AtomCommandSuccess,
} from "@t3tools/client-runtime/state/runtime";
import { ThreadId, type EnvironmentId, type TerminalAttachInput } from "@t3tools/contracts";
import { useAtomSet } from "@effect/atom-react";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import { useEnvironmentQuery } from "./query";
import { terminalEnvironment } from "./terminal";
import { useAtomCommand } from "./use-atom-command";
export class TerminalRestartUnavailableError extends Data.TaggedError(
"TerminalRestartUnavailableError",
)<{
readonly message: string;
}> {}
export function useAttachedTerminalSession(input: {
readonly environmentId: EnvironmentId | null;
@@ -95,11 +109,19 @@ export function useTerminalController(input: {
readonly environmentId: EnvironmentId;
readonly terminal: TerminalAttachInput;
}) {
const writeTerminal = useAtomSet(terminalEnvironment.write, { mode: "promise" });
const resizeTerminal = useAtomSet(terminalEnvironment.resize, { mode: "promise" });
const clearTerminal = useAtomSet(terminalEnvironment.clear, { mode: "promise" });
const restartTerminal = useAtomSet(terminalEnvironment.restart, { mode: "promise" });
const closeTerminal = useAtomSet(terminalEnvironment.close, { mode: "promise" });
const writeTerminal = useAtomCommand(terminalEnvironment.write, {
reportFailure: false,
});
const resizeTerminal = useAtomCommand(terminalEnvironment.resize, {
reportFailure: false,
});
const clearTerminal = useAtomCommand(terminalEnvironment.clear);
const restartTerminal = useAtomCommand(terminalEnvironment.restart, {
reportFailure: false,
});
const closeTerminal = useAtomCommand(terminalEnvironment.close);
type RestartTerminalError = AtomCommandFailure<Awaited<ReturnType<typeof restartTerminal>>>;
type RestartTerminalValue = AtomCommandSuccess<Awaited<ReturnType<typeof restartTerminal>>>;
const session = useAttachedTerminalSession(input);
const { environmentId, terminal } = input;
@@ -139,10 +161,16 @@ export function useTerminalController(input: {
}),
[clearTerminal, environmentId, terminal.terminalId, terminal.threadId],
);
const restart = useCallback(() => {
const restart = useCallback(async (): Promise<
AtomCommandResult<RestartTerminalValue, RestartTerminalError | TerminalRestartUnavailableError>
> => {
if (terminal.cwd === undefined || terminal.cols === undefined || terminal.rows === undefined) {
return Promise.reject(
new Error("Terminal restart requires the working directory and dimensions."),
return AsyncResult.failure(
Cause.fail(
new TerminalRestartUnavailableError({
message: "Terminal restart requires the working directory and dimensions.",
}),
),
);
}
return restartTerminal({
+24
View File
@@ -0,0 +1,24 @@
import { useAtomSet } from "@effect/atom-react";
import {
executeAtomCommand,
type AtomCommandOptions,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { AsyncResult, type Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
export function useAtomCommand<A, E, W>(
atom: Atom.Writable<AsyncResult.AsyncResult<A, E>, W>,
options?: string | AtomCommandOptions,
): (value: W) => Promise<AtomCommandResult<A, E>> {
const set = useAtomSet(atom, { mode: "promiseExit" });
const label =
typeof options === "string" ? options : (options?.label ?? atom.label?.[0] ?? "atom command");
const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true);
const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true);
return useCallback(
(value: W) => executeAtomCommand(() => set(value), { label, reportFailure, reportDefect }),
[label, reportDefect, reportFailure, set],
);
}
+5 -3
View File
@@ -88,20 +88,22 @@ describe("RelayTokens", () => {
proofKeyThumbprint: "proof-key-thumbprint",
jti: "access-token-1",
issuedAtEpochSeconds: 100,
expiresAtEpochSeconds: 200,
expiresAtEpochSeconds: 1_900,
clientId: "t3-mobile",
scopes: ["environment:connect", "environment:status", "mobile:registration"],
});
expect(
yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 }),
yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 700 }),
).toMatchObject({
sub: "user_123",
cnf: { jkt: "proof-key-thumbprint" },
client_id: "t3-mobile",
scope: ["environment:connect", "environment:status", "mobile:registration"],
});
expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 261 })).toBeNull();
expect(
yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 1_961 }),
).toBeNull();
}).pipe(Effect.provide(layer)),
);
+19
View File
@@ -26,6 +26,7 @@ import * as RelayConfiguration from "../Config.ts";
const LINK_CHALLENGE_TYP = "t3-link-challenge+jwt";
const ACCESS_TOKEN_TYP = "t3-relay-dpop-access+jwt";
const LINK_CHALLENGE_KIND = "environment_link_challenge";
export const RELAY_DPOP_ACCESS_TOKEN_TTL = "30 minutes";
const LinkChallengeClaims = Schema.Struct({
kind: Schema.Literal(LINK_CHALLENGE_KIND),
@@ -71,6 +72,17 @@ const allowedScopesByClientId: Record<
[RelayWebClientId]: new Set([RelayEnvironmentConnectScope, RelayEnvironmentStatusScope]),
};
function relayJwtVerificationFailureReason(error: RelayJwtError): string {
const cause = error.cause;
if (typeof cause === "object" && cause !== null && "code" in cause) {
const code = (cause as { readonly code?: unknown }).code;
if (typeof code === "string" && code.length > 0) {
return code;
}
}
return cause instanceof Error && cause.name ? cause.name : "unknown";
}
function resolveDpopAccessTokenScopes(input: {
readonly clientId: RelayPublicClientId;
readonly scope: string;
@@ -195,7 +207,14 @@ const make = Effect.gen(function* () {
issuer,
audience: issuer,
nowEpochSeconds: input.nowEpochSeconds,
maxTokenAge: RELAY_DPOP_ACCESS_TOKEN_TTL,
}).pipe(
Effect.tapError((error) =>
Effect.annotateCurrentSpan(
"relay.tokens.verification_failure",
relayJwtVerificationFailureReason(error),
),
),
Effect.flatMap(decodeDpopAccessTokenClaims),
Effect.map((claims): RelayDpopAccessTokenClaims | null => {
const scopes = resolveDpopAccessTokenScopes({
@@ -535,6 +535,7 @@ describe("EnvironmentConnector", () => {
environmentId: "env-connector-test",
status: "offline",
error: "Managed endpoint health request failed: Environment is unavailable.",
traceId: expect.any(String),
});
}).pipe(Effect.provide(connectorTestLayer(execute)));
});
@@ -35,7 +35,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import { FetchHttpClient, HttpClient, HttpClientError } from "effect/unstable/http";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
@@ -179,6 +179,24 @@ function environmentHealthRequestFailureMessage(cause: unknown): string {
: "Managed endpoint health request failed.";
}
function environmentHealthRequestFailureReason(cause: unknown): string {
if (isEnvironmentHealthError(cause)) {
return cause._tag;
}
if (HttpClientError.isHttpClientError(cause)) {
return cause.reason._tag;
}
if (Schema.isSchemaError(cause)) {
return "SchemaError";
}
return cause instanceof Error && cause.name ? cause.name : "Unknown";
}
const currentTraceId = Effect.currentSpan.pipe(
Effect.map((span) => span.traceId),
Effect.orElseSucceed(() => "unavailable"),
);
const withoutRedirects = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
@@ -457,6 +475,7 @@ const make = Effect.gen(function* () {
),
);
const checkedAt = DateTime.formatIso(now);
const traceId = yield* currentTraceId;
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const responseOption = yield* environmentClient.connect.health({ payload: { proof } }).pipe(
withoutRedirects,
@@ -467,21 +486,44 @@ const make = Effect.gen(function* () {
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
);
if (Option.isNone(responseOption)) {
yield* Effect.annotateCurrentSpan({
"relay.environment_health.outcome": "timeout",
"relay.environment_health.trace_id": traceId,
});
yield* Effect.logWarning("Managed endpoint health request timed out", {
environmentId: link.environmentId,
endpoint: endpoint.httpBaseUrl,
traceId,
});
return {
environmentId: link.environmentId,
endpoint,
status: "offline" as const,
checkedAt,
error: "Managed endpoint health request timed out.",
traceId,
};
}
if (responseOption.value._tag === "Failure") {
const failureReason = environmentHealthRequestFailureReason(responseOption.value.cause);
yield* Effect.annotateCurrentSpan({
"relay.environment_health.outcome": "failure",
"relay.environment_health.failure_reason": failureReason,
"relay.environment_health.trace_id": traceId,
});
yield* Effect.logWarning("Managed endpoint health request failed", {
environmentId: link.environmentId,
endpoint: endpoint.httpBaseUrl,
failureReason,
traceId,
});
return {
environmentId: link.environmentId,
endpoint,
status: "offline" as const,
checkedAt,
error: environmentHealthRequestFailureMessage(responseOption.value.cause),
traceId,
};
}
const decoded = responseOption.value.response;
+2 -3
View File
@@ -69,7 +69,6 @@ import { withSpanAttributes } from "../observability.ts";
import { RelayDb } from "../db.ts";
const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const;
const RELAY_DPOP_ACCESS_TOKEN_TTL = "30 minutes";
const relayCorsAllowedHeaders = [
"authorization",
"b3",
@@ -599,7 +598,7 @@ export const tokenApi = HttpApiBuilder.group(
Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),
);
const now = yield* DateTime.now;
const expiresAt = DateTime.addDuration(now, RELAY_DPOP_ACCESS_TOKEN_TTL);
const expiresAt = DateTime.addDuration(now, RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL);
const jti = yield* crypto.randomUUIDv4.pipe(
Effect.catch(() => relayInternalErrorResponse("internal_error")),
);
@@ -617,7 +616,7 @@ export const tokenApi = HttpApiBuilder.group(
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
issued_token_type: RelayAccessTokenType,
token_type: "DPoP" as const,
expires_in: Duration.toSeconds(RELAY_DPOP_ACCESS_TOKEN_TTL),
expires_in: Duration.toSeconds(RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL),
scope: encodeOAuthScope(requestedScopes),
};
}, mapRelayCommonApiErrors("invalid_dpop")),
@@ -13,22 +13,26 @@ const COMPILER_METHODS = new Set<keyof typeof Schema>([
"decodeExit",
"decodeOption",
"decodePromise",
"decodeResult",
"decodeSync",
"decodeUnknownExit",
"decodeUnknownEffect",
"decodeUnknownOption",
"decodeUnknownPromise",
"decodeUnknownResult",
"decodeUnknownSync",
"encodeExit",
"encodeEffect",
"encodeOption",
"encodePromise",
"encodeResult",
"encodeSync",
"encodeUnknownExit",
"encodeUnknownEffect",
"encodeUnknownOption",
"encodeUnknownPromise",
"encodeUnknownResult",
"encodeUnknownSync",
]);
@@ -267,6 +267,15 @@ export const makeEnvironmentSupervisor = Effect.fn("EnvironmentSupervisor.make")
yield* Queue.offer(signals, next);
});
const logManagedRelayAccountChange = Effect.logInfo(
"Managed relay account changed; restarting the environment connection.",
).pipe(
Effect.annotateLogs({
"environment.id": target.environmentId,
"environment.label": target.label,
}),
);
const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
attempt: number,
generation: number,
@@ -375,6 +384,7 @@ export const makeEnvironmentSupervisor = Effect.fn("EnvironmentSupervisor.make")
break;
case "Wakeup":
if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
yield* logManagedRelayAccountChange;
return;
}
break;
@@ -396,6 +406,7 @@ export const makeEnvironmentSupervisor = Effect.fn("EnvironmentSupervisor.make")
break;
case "Wakeup":
if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
yield* logManagedRelayAccountChange;
return;
}
if (next.reason === "application-active") {
@@ -115,6 +115,20 @@ const makeRelayEnvironmentDiscovery = Effect.fn("RelayEnvironmentDiscovery.make"
const accountGeneration = yield* Ref.make(0);
const activeAccountId = yield* Ref.make<Option.Option<string>>(Option.none());
const refreshGeneration = yield* Ref.make(0);
const offlineReportFingerprints = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
const clearOfflineReport = Effect.fn("RelayEnvironmentDiscovery.clearOfflineReport")(function* (
environmentId: string,
) {
yield* Ref.update(offlineReportFingerprints, (current) => {
if (!current.has(environmentId)) {
return current;
}
const next = new Map(current);
next.delete(environmentId);
return next;
});
});
const updateEnvironment = Effect.fn("RelayEnvironmentDiscovery.updateEnvironment")(function* (
generation: number,
@@ -153,6 +167,25 @@ const makeRelayEnvironmentDiscovery = Effect.fn("RelayEnvironmentDiscovery.make"
);
if (result._tag === "Success") {
if (result.success.status === "offline") {
const fingerprint = `${result.success.endpoint.httpBaseUrl}\n${result.success.error ?? ""}`;
const shouldReport = yield* Ref.modify(offlineReportFingerprints, (current) => {
if (current.get(environment.environmentId) === fingerprint) {
return [false, current];
}
return [true, new Map(current).set(environment.environmentId, fingerprint)];
});
if (shouldReport) {
yield* Effect.logWarning("Relay environment health check reported offline", {
environmentId: result.success.environmentId,
endpoint: result.success.endpoint.httpBaseUrl,
message: result.success.error,
traceId: result.success.traceId,
});
}
} else {
yield* clearOfflineReport(environment.environmentId);
}
yield* updateEnvironment(generation, environment.environmentId, (current) => ({
...current,
availability: result.success.status,
@@ -162,6 +195,7 @@ const makeRelayEnvironmentDiscovery = Effect.fn("RelayEnvironmentDiscovery.make"
return;
}
yield* clearOfflineReport(environment.environmentId);
yield* updateEnvironment(generation, environment.environmentId, (current) => ({
...current,
availability: "error",
@@ -278,6 +312,7 @@ const makeRelayEnvironmentDiscovery = Effect.fn("RelayEnvironmentDiscovery.make"
? Effect.gen(function* () {
yield* Ref.update(accountGeneration, (current) => current + 1);
yield* Ref.set(activeAccountId, Option.none());
yield* Ref.set(offlineReportFingerprints, new Map());
const shouldRefresh = yield* Ref.get(hasRefreshed);
yield* SubscriptionRef.set(state, EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE);
if (shouldRefresh) {
@@ -268,6 +268,100 @@ describe("ManagedRelayClient", () => {
});
});
it.effect("refreshes a persisted DPoP token once when the relay rejects it", () => {
let tokenExchangeCount = 0;
const statusTokens: Array<string | null> = [];
let persistedTokens: ReadonlyArray<ManagedRelayAccessTokenCacheEntry> = [
{
accountId: "user-1",
clientId: "t3-mobile",
relayUrl: "https://relay.example.test",
thumbprint: "client-thumbprint",
scopes: [RelayEnvironmentStatusScope],
accessToken: "stale-relay-token",
expiresAtMillis: Number.MAX_SAFE_INTEGER,
},
];
const accessTokenStore: ManagedRelayAccessTokenStore = {
load: Effect.sync(() => persistedTokens),
save: (entries) =>
Effect.sync(() => {
persistedTokens = entries;
}),
clear: Effect.sync(() => {
persistedTokens = [];
}),
};
const fetchFn = ((input, init) => {
const url = String(input);
if (url.endsWith("/v1/client/dpop-token")) {
tokenExchangeCount += 1;
return Promise.resolve(
Response.json({
access_token: "fresh-relay-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 1_800,
scope: RelayEnvironmentStatusScope,
}),
);
}
const authorization = new Headers(init?.headers).get("authorization");
statusTokens.push(authorization);
if (authorization === "DPoP stale-relay-token") {
return Promise.resolve(
Response.json(
{
_tag: "RelayAuthInvalidError",
code: "auth_invalid",
reason: "invalid_bearer",
traceId: "trace-stale-token",
},
{ status: 401 },
),
);
}
return Promise.resolve(
Response.json({
environmentId: "env-1",
endpoint: {
httpBaseUrl: "https://desktop.example.test/",
wsBaseUrl: "wss://desktop.example.test/ws",
providerKind: "cloudflare_tunnel",
},
status: "online",
checkedAt: "2026-06-05T20:00:00.000Z",
descriptor: {
environmentId: "env-1",
label: "Desktop",
platform: { os: "darwin", arch: "arm64" },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
}),
);
}) satisfies typeof globalThis.fetch;
return Effect.gen(function* () {
const relayClient = yield* ManagedRelayClient;
const result = yield* relayClient.getEnvironmentStatus({
clerkToken: clerkToken("user-1", "session-1"),
scopes: [RelayEnvironmentStatusScope],
environmentId: EnvironmentId.make("env-1"),
});
expect(result.status).toBe("online");
expect(statusTokens).toEqual(["DPoP stale-relay-token", "DPoP fresh-relay-token"]);
expect(tokenExchangeCount).toBe(1);
expect(persistedTokens).toMatchObject([
{
accessToken: "fresh-relay-token",
},
]);
}).pipe(Effect.provide(managedRelayTestLayer(fetchFn, undefined, accessTokenStore)));
});
it.effect("does not persist tokens when the Clerk subject cannot be decoded", () => {
let persistedTokens: ReadonlyArray<ManagedRelayAccessTokenCacheEntry> = [];
const accessTokenStore: ManagedRelayAccessTokenStore = {
+169 -80
View File
@@ -191,6 +191,13 @@ function relayRequestError(message: string) {
});
}
function isRejectedDpopAccessToken(error: ManagedRelayClientError): boolean {
return (
error.relayError?._tag === "RelayAuthInvalidError" &&
error.relayError.reason === "invalid_bearer"
);
}
function timeoutRelayRequest(message: string) {
return <A, E, R>(
request: Effect.Effect<A, E, R>,
@@ -470,14 +477,80 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
return { accessToken: token.accessToken, proof, thumbprint };
});
const authorizeMobileRegistration = (input: {
readonly clerkToken: string;
readonly target: DpopProofTarget;
}) =>
authorize({
...input,
scopes: [RelayMobileRegistrationScope],
});
const invalidateAccessToken = Effect.fn("clientRuntime.managedRelay.invalidateAccessToken")(
function* (accessToken: string) {
return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) => {
const nextTokens = tokens.filter((token) => token.accessToken !== accessToken);
if (nextTokens.length === tokens.length) {
return Effect.succeed([false, tokens] as const);
}
return (
options.accessTokenStore ? options.accessTokenStore.save(nextTokens) : Effect.void
).pipe(Effect.as([true, nextTokens] as const));
});
},
);
const runDpopRequest = <A>(
input: {
readonly clerkToken: string;
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
readonly target: DpopProofTarget;
},
request: (
authorization: ManagedRelayAuthorization,
) => Effect.Effect<A, ManagedRelayClientError>,
): Effect.Effect<A, ManagedRelayClientError> => {
const attempt = (
refreshRejectedToken: boolean,
): Effect.Effect<A, ManagedRelayClientError> =>
authorize(input).pipe(
Effect.flatMap((authorization) =>
request(authorization).pipe(
Effect.catch((error) => {
if (!isRejectedDpopAccessToken(error)) {
return Effect.fail(error);
}
return invalidateAccessToken(authorization.accessToken).pipe(
Effect.tap((invalidated) =>
Effect.annotateCurrentSpan({
"relay.token_cache.invalidated": invalidated,
"relay.token_cache.invalidation_reason": "invalid_bearer",
"relay.token_cache.retry_after_invalidation": refreshRejectedToken,
}),
),
Effect.tap((invalidated) =>
invalidated && refreshRejectedToken
? Effect.logWarning(
"Relay rejected a cached DPoP access token; refreshing it once.",
)
: Effect.void,
),
Effect.andThen(refreshRejectedToken ? attempt(false) : Effect.fail(error)),
);
}),
),
),
);
return attempt(true);
};
const mobileRegistrationRequest = <A>(
input: {
readonly clerkToken: string;
readonly target: DpopProofTarget;
},
request: (
authorization: ManagedRelayAuthorization,
) => Effect.Effect<A, ManagedRelayClientError>,
) =>
runDpopRequest(
{
...input,
scopes: [RelayMobileRegistrationScope],
},
request,
);
return ManagedRelayClient.of({
relayUrl,
@@ -561,20 +634,23 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
yield* Effect.annotateCurrentSpan({
"environment.id": input.environmentId,
});
const authorization = yield* authorize({
clerkToken: input.clerkToken,
scopes: input.scopes,
target: dpopProofTargets.getEnvironmentStatus(input.environmentId),
});
return yield* client.dpopClient
.getEnvironmentStatus({
headers: dpopHeaders(authorization),
params: { environmentId: input.environmentId },
})
.pipe(
Effect.mapError(relayRequestError("Could not get relay environment status.")),
timeoutRelayRequest("Relay environment status request timed out."),
);
return yield* runDpopRequest(
{
clerkToken: input.clerkToken,
scopes: input.scopes,
target: dpopProofTargets.getEnvironmentStatus(input.environmentId),
},
(authorization) =>
client.dpopClient
.getEnvironmentStatus({
headers: dpopHeaders(authorization),
params: { environmentId: input.environmentId },
})
.pipe(
Effect.mapError(relayRequestError("Could not get relay environment status.")),
timeoutRelayRequest("Relay environment status request timed out."),
),
);
},
Effect.withSpan("clientRuntime.managedRelay.getEnvironmentStatus"),
withRelayClientTracing,
@@ -584,82 +660,95 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
yield* Effect.annotateCurrentSpan({
"environment.id": input.environmentId,
});
const authorization = yield* authorize({
clerkToken: input.clerkToken,
scopes: input.scopes,
target: dpopProofTargets.connectEnvironment(input.environmentId),
});
const payload: RelayEnvironmentConnectRequest = {
...(input.deviceId ? { deviceId: input.deviceId } : {}),
clientKeyThumbprint: authorization.thumbprint,
};
return yield* client.dpopClient
.connectEnvironment({
headers: dpopHeaders(authorization),
params: { environmentId: input.environmentId },
payload,
})
.pipe(
Effect.mapError(relayRequestError("Could not connect relay environment.")),
timeoutRelayRequest("Relay environment connection timed out."),
);
return yield* runDpopRequest(
{
clerkToken: input.clerkToken,
scopes: input.scopes,
target: dpopProofTargets.connectEnvironment(input.environmentId),
},
(authorization) => {
const payload: RelayEnvironmentConnectRequest = {
...(input.deviceId ? { deviceId: input.deviceId } : {}),
clientKeyThumbprint: authorization.thumbprint,
};
return client.dpopClient
.connectEnvironment({
headers: dpopHeaders(authorization),
params: { environmentId: input.environmentId },
payload,
})
.pipe(
Effect.mapError(relayRequestError("Could not connect relay environment.")),
timeoutRelayRequest("Relay environment connection timed out."),
);
},
);
},
Effect.withSpan("clientRuntime.managedRelay.connectEnvironment"),
withRelayClientTracing,
),
registerDevice: Effect.fnUntraced(
function* (input) {
const authorization = yield* authorizeMobileRegistration({
clerkToken: input.clerkToken,
target: dpopProofTargets.registerDevice(),
});
return yield* client.mobile
.registerDevice({
headers: dpopHeaders(authorization),
payload: input.payload,
})
.pipe(
Effect.mapError(relayRequestError("Could not register relay mobile device.")),
timeoutRelayRequest("Relay mobile device registration timed out."),
);
return yield* mobileRegistrationRequest(
{
clerkToken: input.clerkToken,
target: dpopProofTargets.registerDevice(),
},
(authorization) =>
client.mobile
.registerDevice({
headers: dpopHeaders(authorization),
payload: input.payload,
})
.pipe(
Effect.mapError(relayRequestError("Could not register relay mobile device.")),
timeoutRelayRequest("Relay mobile device registration timed out."),
),
);
},
Effect.withSpan("clientRuntime.managedRelay.registerDevice"),
withRelayClientTracing,
),
unregisterDevice: Effect.fnUntraced(
function* (input) {
const authorization = yield* authorizeMobileRegistration({
clerkToken: input.clerkToken,
target: dpopProofTargets.unregisterDevice(input.deviceId),
});
return yield* client.mobile
.unregisterDevice({
headers: dpopHeaders(authorization),
params: { deviceId: input.deviceId },
})
.pipe(
Effect.mapError(relayRequestError("Could not unregister relay mobile device.")),
timeoutRelayRequest("Relay mobile device unregistration timed out."),
);
return yield* mobileRegistrationRequest(
{
clerkToken: input.clerkToken,
target: dpopProofTargets.unregisterDevice(input.deviceId),
},
(authorization) =>
client.mobile
.unregisterDevice({
headers: dpopHeaders(authorization),
params: { deviceId: input.deviceId },
})
.pipe(
Effect.mapError(relayRequestError("Could not unregister relay mobile device.")),
timeoutRelayRequest("Relay mobile device unregistration timed out."),
),
);
},
Effect.withSpan("clientRuntime.managedRelay.unregisterDevice"),
withRelayClientTracing,
),
registerLiveActivity: Effect.fnUntraced(
function* (input) {
const authorization = yield* authorizeMobileRegistration({
clerkToken: input.clerkToken,
target: dpopProofTargets.registerLiveActivity(),
});
return yield* client.mobile
.registerLiveActivity({
headers: dpopHeaders(authorization),
payload: input.payload,
})
.pipe(
Effect.mapError(relayRequestError("Could not register relay live activity.")),
timeoutRelayRequest("Relay Live Activity registration timed out."),
);
return yield* mobileRegistrationRequest(
{
clerkToken: input.clerkToken,
target: dpopProofTargets.registerLiveActivity(),
},
(authorization) =>
client.mobile
.registerLiveActivity({
headers: dpopHeaders(authorization),
payload: input.payload,
})
.pipe(
Effect.mapError(relayRequestError("Could not register relay live activity.")),
timeoutRelayRequest("Relay Live Activity registration timed out."),
),
);
},
Effect.withSpan("clientRuntime.managedRelay.registerLiveActivity"),
withRelayClientTracing,
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more