Skip to content
TypeScript

fix(mobile): show an error instead of an endless preview spinner (#9123)

Theo Browne2aa907b19692
diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
index 8b7c3d35a3a..91b832e68d1 100644
--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
@@ -37,6 +37,7 @@ import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useEnvironmentQuery } from "../../state/query";
import { projectEnvironment } from "../../state/projects";
+import type { AssetUrlFailureReason } from "../../state/asset-url-state";
import {
useAdaptiveWorkspaceLayout,
useAdaptiveWorkspacePaneRole,
@@ -56,6 +57,7 @@ import { preloadWorkspaceFileContents } from "./preload-workspace-file";
import { SourceFileSurface } from "./SourceFileSurface";
import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
+import { WorkspaceFilePreviewError } from "./WorkspaceFilePreviewError";
import { WorkspaceFileVideoPreview } from "./WorkspaceFileVideoPreview";
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
import {
@@ -104,8 +106,10 @@ function defaultViewMode(path: string | null): FileViewMode {
function FileContent(props: {
readonly activeMode: FileViewMode;
+ readonly environmentId: EnvironmentId | null;
readonly previewUri: string | null;
- readonly previewUnavailable: boolean;
+ readonly previewFailure: AssetUrlFailureReason | null;
+ readonly onRetryPreview: () => void;
readonly videoSource: MediaVideoPreviewSource | null;
readonly mediaSource?: MediaActionsSource;
readonly resolveVideoUri: () => Promise<string | null>;
@@ -121,8 +125,22 @@ function FileContent(props: {
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
const isBrowserFile = isWorkspaceBrowserPreviewPath(props.relativePath);
const isImageFile = isWorkspaceImagePreviewPath(props.relativePath);
+ const isVideoFile = isVideoPreviewFile(props.relativePath);
+ // Only the surfaces that wait on a signed asset URL can be blocked by one.
+ const needsAssetUrl =
+ isVideoFile || (props.activeMode === "preview" && (isImageFile || isBrowserFile));
- if (isVideoPreviewFile(props.relativePath)) {
+ if (needsAssetUrl && props.previewFailure !== null) {
+ return (
+ <WorkspaceFilePreviewError
+ environmentId={props.environmentId}
+ reason={props.previewFailure}
+ onRetry={props.onRetryPreview}
+ />
+ );
+ }
+
+ if (isVideoFile) {
return (
<WorkspaceFileVideoPreview
name={basename(props.relativePath)}
@@ -130,7 +148,6 @@ function FileContent(props: {
uri={props.previewUri}
source={props.videoSource}
resolvePlaybackUri={props.resolveVideoUri}
- unavailable={props.previewUnavailable}
/>
);
}
@@ -588,6 +605,10 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
assetPreviewUri === null || previewRevision === 0
? assetPreviewUri
: `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
+ // Remounting the preview after a re-mint is what makes a failed asset URL retryable.
+ const handleRetryPreview = () => {
+ void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1));
+ };
const needsFileContents =
relativePath !== null &&
!isVideoFile &&
@@ -889,8 +910,10 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
<FileContent
key={previewKey}
activeMode={resolvedActiveMode}
+ environmentId={environmentId}
previewUri={previewUri}
- previewUnavailable={assetPreview._tag === "Failure"}
+ previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}
+ onRetryPreview={handleRetryPreview}
videoSource={videoSource}
mediaSource={mediaSource}
resolveVideoUri={assetPreview.refresh}
diff --git a/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx b/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx
new file mode 100644
index 00000000000..a1ceebfbc2c
--- /dev/null
+++ b/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx
@@ -0,0 +1,59 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { useCallback } from "react";
+import { View } from "react-native";
+
+import { EmptyState } from "../../components/EmptyState";
+import { environmentCatalog } from "../../connection/catalog";
+import type { AssetUrlFailureReason } from "../../state/asset-url-state";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { useEnvironmentPresentation } from "../../state/presentation";
+import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
+
+/**
+ * Terminal state for a preview whose signed asset URL will not arrive. A dead
+ * environment reuses the same notice the terminal and review sheets show, so the
+ * user gets one recognizable way back online.
+ */
+export function WorkspaceFilePreviewError(props: {
+ readonly environmentId: EnvironmentId | null;
+ readonly reason: AssetUrlFailureReason;
+ readonly onRetry: () => void;
+}) {
+ const { environmentId, onRetry } = props;
+ const environment = useEnvironmentPresentation(environmentId);
+ const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const retryConnection = useCallback(() => {
+ if (environmentId !== null) void retryEnvironment(environmentId);
+ onRetry();
+ }, [environmentId, onRetry, retryEnvironment]);
+
+ if (props.reason === "disconnected") {
+ return (
+ <View className="flex-1 bg-sheet">
+ <EnvironmentConnectionNotice
+ environmentLabel={environment.presentation?.entry.target.label ?? "Environment"}
+ connection={
+ environment.presentation?.connection ?? {
+ phase: "available",
+ error: null,
+ traceId: null,
+ }
+ }
+ resourceName="preview"
+ onRetry={retryConnection}
+ />
+ </View>
+ );
+ }
+
+ return (
+ <View className="flex-1 items-center justify-center bg-sheet px-6">
+ <EmptyState
+ title="Preview unavailable"
+ detail="This file may be missing, unsupported, or unavailable on this environment."
+ actionLabel="Try again"
+ onAction={props.onRetry}
+ />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/files/WorkspaceFileVideoPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileVideoPreview.tsx
index d45f7325a43..1034696ba63 100644
--- a/apps/mobile/src/features/files/WorkspaceFileVideoPreview.tsx
+++ b/apps/mobile/src/features/files/WorkspaceFileVideoPreview.tsx
@@ -1,6 +1,5 @@
import { View } from "react-native";
-import { EmptyState } from "../../components/EmptyState";
import { MediaVideoPlayer } from "../../components/MediaVideoPlayer";
import type { MediaVideoPreviewSource } from "../../lib/videoPreviewSource";
@@ -11,21 +10,9 @@ export function WorkspaceFileVideoPreview(props: {
readonly uri: string | null;
readonly source: MediaVideoPreviewSource | null;
readonly resolvePlaybackUri: () => Promise<string | null>;
- readonly unavailable: boolean;
}) {
const uri = props.uri;
- if (props.unavailable) {
- return (
- <View className="flex-1 items-center justify-center bg-sheet px-6">
- <EmptyState
- title="Video unavailable"
- detail="This file may be missing, unsupported, or unavailable on this environment."
- />
- </View>
- );
- }
-
return (
<View className="flex-1 items-center justify-center bg-sheet p-4">
<MediaVideoPlayer
diff --git a/apps/mobile/src/state/asset-url-state.test.ts b/apps/mobile/src/state/asset-url-state.test.ts
new file mode 100644
index 00000000000..bcc0d070ff8
--- /dev/null
+++ b/apps/mobile/src/state/asset-url-state.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "@effect/vitest";
+
+import { deriveAssetUrlState } from "./asset-url-state";
+
+const SUCCESS = { _tag: "Success" as const, url: "https://environment.example/api/assets/abc" };
+
+describe("deriveAssetUrlState", () => {
+ it("passes a resolved URL through on a live environment", () => {
+ expect(deriveAssetUrlState({ connectionPhase: "connected", shared: SUCCESS })).toEqual(SUCCESS);
+ });
+
+ it("waits while the query is pending and the environment is still reachable", () => {
+ for (const connectionPhase of ["available", "connecting", "connected"] as const) {
+ expect(deriveAssetUrlState({ connectionPhase, shared: { _tag: "Loading" } })).toEqual({
+ _tag: "Loading",
+ });
+ }
+ });
+
+ it("stops waiting once the environment is offline, retrying, or in error", () => {
+ for (const connectionPhase of ["offline", "reconnecting", "error"] as const) {
+ expect(deriveAssetUrlState({ connectionPhase, shared: { _tag: "Loading" } })).toEqual({
+ _tag: "Failure",
+ reason: "disconnected",
+ });
+ }
+ });
+
+ // A dead environment fails the URL query itself, so the query outcome alone
+ // cannot tell a missing file from a missing connection.
+ it("reports disconnected when the query failed while the environment is down", () => {
+ for (const connectionPhase of ["available", "offline", "reconnecting", "error"] as const) {
+ expect(deriveAssetUrlState({ connectionPhase, shared: { _tag: "Failure" } })).toEqual({
+ _tag: "Failure",
+ reason: "disconnected",
+ });
+ }
+ });
+
+ it("does not hand out a resolved URL for a disconnected environment", () => {
+ for (const connectionPhase of ["offline", "reconnecting", "error"] as const) {
+ expect(deriveAssetUrlState({ connectionPhase, shared: SUCCESS })).toEqual({
+ _tag: "Failure",
+ reason: "disconnected",
+ });
+ }
+ });
+
+ it("reports a failed query on a connected environment", () => {
+ expect(
+ deriveAssetUrlState({ connectionPhase: "connected", shared: { _tag: "Failure" } }),
+ ).toEqual({ _tag: "Failure", reason: "failed" });
+ });
+});
diff --git a/apps/mobile/src/state/asset-url-state.ts b/apps/mobile/src/state/asset-url-state.ts
new file mode 100644
index 00000000000..d70e42410fa
--- /dev/null
+++ b/apps/mobile/src/state/asset-url-state.ts
@@ -0,0 +1,47 @@
+import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
+import type { AssetUrlState as SharedAssetUrlState } from "@t3tools/client-runtime/state/assets";
+
+export type AssetUrlFailureReason = "disconnected" | "failed";
+
+/** The shared state plus a reason on failure, so previews can offer the right retry. */
+export type AssetUrlState =
+ | { readonly _tag: "Loading" }
+ | { readonly _tag: "Failure"; readonly reason: AssetUrlFailureReason }
+ | Extract<SharedAssetUrlState, { readonly _tag: "Success" }>;
+
+/**
+ * Folds the shared asset URL state with the environment connection phase. A
+ * dead environment wins over everything else: even a resolved URL is
+ * unreachable there, and a failed query is caused by the outage, not the file.
+ */
+export function deriveAssetUrlState(input: {
+ readonly connectionPhase: EnvironmentConnectionPhase;
+ readonly shared: SharedAssetUrlState;
+}): AssetUrlState {
+ if (
+ input.connectionPhase === "offline" ||
+ input.connectionPhase === "reconnecting" ||
+ input.connectionPhase === "error"
+ ) {
+ return { _tag: "Failure", reason: "disconnected" };
+ }
+ if (input.shared._tag === "Success") {
+ return input.shared;
+ }
+ switch (input.connectionPhase) {
+ // "available" is the idle, not yet dialled state. A pending query there is
+ // still on its way, but the query atom fails at once while idle, so a
+ // failure means the environment is not connected rather than the file is
+ // missing.
+ case "available":
+ return input.shared._tag === "Failure"
+ ? { _tag: "Failure", reason: "disconnected" }
+ : { _tag: "Loading" };
+ case "connecting":
+ return { _tag: "Loading" };
+ case "connected":
+ return input.shared._tag === "Failure"
+ ? { _tag: "Failure", reason: "failed" }
+ : { _tag: "Loading" };
+ }
+}
diff --git a/apps/mobile/src/state/assets.ts b/apps/mobile/src/state/assets.ts
index af6300d8ffa..400bdb6b705 100644
--- a/apps/mobile/src/state/assets.ts
+++ b/apps/mobile/src/state/assets.ts
@@ -1,35 +1,64 @@
import { useAtomValue } from "@effect/atom-react";
import {
- type AssetUrlState,
+ type EnvironmentConnectionPhase,
+ presentConnectionState,
+} from "@t3tools/client-runtime/connection";
+import {
assetUrlStateFromResult,
createAssetEnvironmentAtoms,
EMPTY_ASSET_URL_ATOM,
} from "@t3tools/client-runtime/state/assets";
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
+import * as Option from "effect/Option";
+import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
+import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
+import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
import { usePreparedConnection } from "./session";
import { useAtomQueryRunner } from "./use-atom-query-runner";
-export type { AssetUrlState } from "@t3tools/client-runtime/state/assets";
+export type { AssetUrlFailureReason, AssetUrlState } from "./asset-url-state";
export const assetEnvironment = createAssetEnvironmentAtoms(connectionAtomRuntime);
+const EMPTY_CONNECTION_STATE_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
+ Atom.withLabel("mobile-asset-connection-state:empty"),
+);
+
+function useConnectionPhase(environmentId: EnvironmentId | null): EnvironmentConnectionPhase {
+ const state = useAtomValue(
+ environmentId === null
+ ? EMPTY_CONNECTION_STATE_ATOM
+ : environmentCatalog.stateAtom(environmentId),
+ );
+ const value = Option.getOrNull(AsyncResult.value(state));
+ return value === null ? "available" : presentConnectionState(value).phase;
+}
+
export function useAssetUrlState(
environmentId: EnvironmentId | null,
resource: AssetResource | null,
): AssetUrlState {
const preparedConnection = usePreparedConnection(environmentId);
+ const connectionPhase = useConnectionPhase(environmentId);
const result = useAtomValue(
environmentId === null || resource === null
? EMPTY_ASSET_URL_ATOM
: assetEnvironment.createUrl({ environmentId, input: { resource } }),
);
- return assetUrlStateFromResult(
+ const shared = assetUrlStateFromResult(
result,
preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
);
+ return deriveAssetUrlState({
+ connectionPhase,
+ // A failure left over from an outage is re-queried as soon as the
+ // connection returns. While that re-query is in flight it is not a verdict
+ // on the file, so it reads as loading rather than a false "unavailable".
+ shared: shared._tag === "Failure" && result.waiting ? { _tag: "Loading" } : shared,
+ });
}
export function useAssetUrl(