Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion apps/web/src/cloud/linkEnvironment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { ManagedRelay } from "@t3tools/client-runtime/relay";
import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";

import { readCloudLinkState } from "./linkEnvironment";
import { readCloudLinkState, unlinkEnvironmentFromCloud } from "./linkEnvironment";

const TARGET = {
environmentId: "environment-1",
Expand Down Expand Up @@ -239,4 +239,49 @@ describe("web cloud link environment client", () => {
}
}),
);

it.effect("reports why the relay kept the environment after a local unlink", () =>
Effect.gen(function* () {
const fetchMock = vi.fn((input: RequestInfo | URL) =>
Promise.resolve(
String(input).startsWith("https://relay.example.test/")
? Response.json(
{
_tag: "RelayInternalError",
code: "internal_error",
reason: "upstream_unavailable",
traceId: "trace-unlink",
},
{ status: 500 },
)
: Response.json({ ok: true, endpointRuntimeStatus: null }),
),
);
vi.stubGlobal("fetch", fetchMock);
vi.stubGlobal("window", {
location: { origin: "t3code://app" },
desktopBridge: {
getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
} as unknown as DesktopBridge,
});

const error = yield* withServices(
unlinkEnvironmentFromCloud({
target: { environmentId: EnvironmentId.make(TARGET.environmentId) },
clerkToken: "clerk-token",
}),
).pipe(Effect.flip);

expect(fetchMock.mock.calls.map(([input]) => String(input))).toEqual([
"http://127.0.0.1:3000/api/connect/unlink",
"https://relay.example.test/v1/client/environment-links/environment-1",
]);
expect(error).toMatchObject({
_tag: "CloudEnvironmentLinkError",
message:
"Disconnected locally, but T3 Connect did not confirm it removed this environment: Relay encountered an internal error (upstream_unavailable).",
traceId: "trace-unlink",
});
}),
);
});
12 changes: 6 additions & 6 deletions apps/web/src/cloud/linkEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ const isEnvironmentCloudApiError = Schema.is(
function decodedRelayClientError(message: string) {
return (cause: ManagedRelay.ManagedRelayClientError) => {
const failed = cause._tag === "ManagedRelayRequestFailedError" ? cause : undefined;
const traceId = failed?.traceId;
const detail = failed ? relayRequestFailureDetail(failed) : null;
const traceId = "traceId" in cause ? cause.traceId : undefined;
const detail = (failed && relayRequestFailureDetail(failed)) ?? cause.message;
return new CloudEnvironmentLinkError({
message: detail ? `${message}: ${detail}` : message,
cause,
Expand Down Expand Up @@ -309,10 +309,10 @@ export const unlinkEnvironmentFromCloud: (input: {
environmentId: input.target.environmentId,
})
.pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
cause,
}),
Effect.mapError(
decodedRelayClientError(
"Disconnected locally, but T3 Connect did not confirm it removed this environment",
),
),
);
}
Expand Down
25 changes: 25 additions & 0 deletions apps/web/src/cloud/relayFailureReason.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay";
import * as Schema from "effect/Schema";

const isRequestFailed = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
const isRequestTimeout = Schema.is(ManagedRelay.ManagedRelayRequestTimeoutError);

/** One short line for an error toast saying why a T3 Connect request failed. */
export function relayFailureReason(cause: unknown): string | null {
for (let current = cause, depth = 0; current instanceof Error && depth < 4; depth += 1) {
if (isRequestTimeout(current)) return "T3 Connect timed out. Try again.";
if (isRequestFailed(current)) {
if (current.transportFailed) return "Could not reach T3 Connect. Check your network.";
if (current.relayError) {
return current.relayError._tag === "RelayInternalError"
? "T3 Connect is unavailable. Try again."
: relayRequestFailureDetail(current);
}
if (current.status === 504) return "T3 Connect timed out. Try again.";
if ((current.status ?? 0) >= 500) return "T3 Connect is unavailable. Try again.";
return relayRequestFailureDetail(current);
}
current = current.cause;
}
return null;
}
47 changes: 32 additions & 15 deletions apps/web/src/cloud/useCloudLinkController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import * as Schema from "effect/Schema";
import { useState } from "react";

import { toastManager } from "../components/ui/toast";
import { stackedThreadToast } from "../components/ui/toastHelpers";
import { relayFailureReason } from "./relayFailureReason";
import { relayEnvironmentDiscovery } from "../state/relay";
import { readEnvironmentScope } from "../state/session";
import { useAtomCommand } from "../state/use-atom-command";
Expand Down Expand Up @@ -51,6 +53,7 @@ function isManagedTunnelActive(
}

const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
const isManagedRelayClientError = Schema.is(ManagedRelay.ManagedRelayClientError);

/** The account's tunnel cap when the relay refused a new tunnel for being at it. */
function tunnelLimitFromLinkFailure(cause: unknown): number | null {
Expand Down Expand Up @@ -84,24 +87,28 @@ export function useCloudLinkController(environmentId: EnvironmentId | null) {
const [operationError, setOperationError] = useState<string | null>(null);
const [tunnelLimit, setTunnelLimit] = useState<number | null>(null);

const reportUpdateFailure = (cause: unknown) => {
const reportUpdateFailure = (cause: unknown, reason?: string) => {
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Connect",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not update T3 Connect",
description: reason ?? relayFailureReason(cause) ?? message,
...(traceId
? {
actionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
actionVariant: "outline",
}
: {}),
data: { hideCopyButton: true },
}),
);
};

const linkData = cloudLinkState.data;
Expand Down Expand Up @@ -157,9 +164,19 @@ export function useCloudLinkController(environmentId: EnvironmentId | null) {
refreshManagedTunnelUsage();
if (unlinkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(unlinkResult)) {
reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
const cause = squashAtomCommandFailure(unlinkResult);
// Only the relay delete fails with a relay error, and it runs after the local unlink.
const relayKeptLink =
isCloudEnvironmentLinkError(cause) && isManagedRelayClientError(cause.cause);
reportUpdateFailure(
cause,
relayKeptLink
? "Disconnected here, but T3 Connect still lists it. Remove it in Account."
: undefined,
);
}
cloudLinkState.refresh();
await refreshRelayEnvironments();
return false;
}
} else {
Expand Down
36 changes: 22 additions & 14 deletions apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ import {
useManagedRelayEnvironments,
useManagedTunnelUsage,
} from "../../cloud/managedRelayState";
import { relayFailureReason } from "../../cloud/relayFailureReason";
import { relayEnvironmentDiscovery } from "../../state/relay";
import { useAtomCommand } from "../../state/use-atom-command";
import { T3CHAT_SUBSCRIPTION_URL, TunnelUsageMeter, tunnelUpgradeCopy } from "../cloud/TunnelUsage";
import { Button, InlineButton } from "../ui/button";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { toastManager } from "../ui/toast";
import { stackedThreadToast } from "../ui/toastHelpers";
import {
ClerkUserProfilePage,
ClerkUserProfileRefreshButton,
Expand Down Expand Up @@ -192,9 +194,9 @@ export function T3ConnectUserProfilePage() {
});
mutationPendingRef.current = false;
setDeregisteringEnvironmentId(null);
setConfirmingEnvironmentId(null);

if (result._tag === "Success") {
setConfirmingEnvironmentId(null);
setRemovedEnvironments((current) => {
const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []);
linkedAtById.set(environment.environmentId, environment.linkedAt);
Expand All @@ -211,6 +213,8 @@ export function T3ConnectUserProfilePage() {
}
if (isAtomCommandInterrupted(result)) return;

// The relay may have removed it before failing.
environmentsState.refresh();
const cause = squashAtomCommandFailure(result);
const message = cause instanceof Error ? cause.message : "Could not deregister the server.";
const traceId = findErrorTraceId(cause);
Expand All @@ -220,19 +224,23 @@ export function T3ConnectUserProfilePage() {
traceId,
cause,
});
toastManager.add({
type: "error",
title: "Could not deregister server",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not deregister server",
description: relayFailureReason(cause) ?? message,
...(traceId
? {
actionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
actionVariant: "outline",
}
: {}),
data: { hideCopyButton: true },
}),
);
};

const removedEnvironmentLinkedAt =
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/components/clerk/clerkAppearance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const clerkAppearance = {
colorRing: "var(--ring)",
},
elements: {
modalBackdrop: "dialog-backdrop",
modalBackdrop: "dialog-backdrop z-50",
cardBox: "dialog-glass rounded-2xl border",
card: "border-0 bg-transparent shadow-none",
footer: "bg-transparent bg-none",
Expand Down
6 changes: 4 additions & 2 deletions packages/client-runtime/src/relay/managedRelay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import * as HttpClientError from "effect/http/HttpClientError";
import type * as HttpMethod from "effect/http/HttpMethod";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
import { relayRequestFailureDetail } from "./errorPresentation.ts";

export interface ManagedRelayDpopProofInput {
readonly method: HttpMethod.HttpMethod;
Expand Down Expand Up @@ -159,8 +160,9 @@ export class ManagedRelayRequestFailedError extends Schema.TaggedError<ManagedRe
},
) {
override get message(): string {
const message = `Could not ${this.action}.`;
return this.transportFailed ? `${message} ${NETWORK_BLOCKING_HINT}` : message;
if (this.transportFailed) return `Could not ${this.action}. ${NETWORK_BLOCKING_HINT}`;
const detail = relayRequestFailureDetail(this);
return detail ? `Could not ${this.action}: ${detail}` : `Could not ${this.action}.`;
}
}

Expand Down
Loading