diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index c4a6ae091a397..29aceda9221c5 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -1,5 +1,7 @@ import * as Dialog from "../../components/ui/Dialog"; import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; +import { useAtomValue } from "@effect/atom-react"; +import { environmentCatalog } from "../../connection/catalog"; import { useRememberThreadProject } from "./useRememberThreadProject"; import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { makeTurnCommandMetadata } from "../../lib/commandMetadata"; @@ -116,9 +118,12 @@ import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane"; import { InspectorSheetContext } from "../layout/workspace-inspector-sheet"; import type { InspectorContent } from "../layout/inspector-panes"; import { + THREAD_ROUTE_CONNECT_GRACE_MS, threadDetailErrorIsCurrent, + threadRouteAwaitsConnection, threadRouteIsHydrating, threadRouteOpensDraft, + threadRouteStartsConnection, } from "./thread-route-hydration"; import { ThreadHeader } from "./ThreadHeader"; import { resumeThread } from "./resume-thread"; @@ -267,6 +272,10 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { const { onReconnectEnvironment } = useRemoteConnections(); const navigation = useNavigation(); const routeName = useRoute().name; + const catalog = useAtomValue(environmentCatalog.catalogValueAtom); + const routeCatalogEntry = environmentId ? catalog.entries.get(environmentId) : undefined; + const routeEnvironmentEnabled = + routeCatalogEntry?.enabled !== false && routeCatalogEntry?.unsupportedReason === undefined; const routeConnectionState = routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState); const routeThreadKey = @@ -277,6 +286,48 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { selectedThread === null ? null : scopedThreadKey(selectedThread.environmentId, selectedThread.id); + const routeThreadShown = selectedThread !== null && selectedThreadKey === routeThreadKey; + const [shownThreadKey, setShownThreadKey] = useState(null); + if (routeThreadShown && shownThreadKey !== routeThreadKey) { + setShownThreadKey(routeThreadKey); + } + // Each Reconnect restarts the wait for the environment to deliver the thread. + const [connectAttempt, setConnectAttempt] = useState(0); + const connectAttemptKey = routeThreadKey === null ? null : `${routeThreadKey}#${connectAttempt}`; + const [graceExpiredKey, setGraceExpiredKey] = useState(null); + // A shown thread that later drops out waits again instead of reusing an earlier timeout. + if (routeThreadShown && graceExpiredKey !== null) { + setGraceExpiredKey(null); + } + const graceExpired = connectAttemptKey !== null && graceExpiredKey === connectAttemptKey; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- ends the wait for a missing thread's environment once the grace period passes + useEffect(() => { + if (connectAttemptKey === null || routeThreadShown) return; + const timer = setTimeout( + () => setGraceExpiredKey(connectAttemptKey), + THREAD_ROUTE_CONNECT_GRACE_MS, + ); + return () => clearTimeout(timer); + }, [connectAttemptKey, routeThreadShown]); + const startConnection = useEffectEvent((target: EnvironmentId) => { + onReconnectEnvironment(target); + }); + const connectionStartedKey = useRef(null); + const routeStartsConnection = + environmentId !== null && + routeEnvironmentRuntime !== null && + routeEnvironmentEnabled && + !routeThreadShown && + !graceExpired && + threadRouteStartsConnection(routeConnectionState); + // A link opened on a resume often finds its environment backing off, so it retries now. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the route environment's connection once per wait while a linked thread is missing + useEffect(() => { + if (!routeStartsConnection || environmentId === null) return; + if (connectionStartedKey.current === connectAttemptKey) return; + connectionStartedKey.current = connectAttemptKey; + startConnection(environmentId); + }, [routeStartsConnection, environmentId, connectAttemptKey]); const selectedThreadDetailState = useSelectedThreadDetailState(); const detailError = selectedThreadDetailState.error; const [errorBeforeConnected, setErrorBeforeConnected] = useState(() => @@ -302,7 +353,7 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { return withInspectorHeader(); } - if (selectedThread !== null && selectedThreadKey === routeThreadKey) { + if (routeThreadShown) { // ThreadRouteContent draws its own inspector header so it can show the sync status. return ( @@ -328,7 +379,16 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { }), }); - if (stillHydrating) { + if ( + stillHydrating || + (routeEnvironmentRuntime !== null && + threadRouteAwaitsConnection({ + connectionState: routeConnectionState, + environmentEnabled: routeEnvironmentEnabled, + detailStatus: selectedThreadDetailState.status, + graceExpired, + })) + ) { return withInspectorHeader(); } @@ -336,8 +396,8 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { routeName === "Thread" && !props.inspectorPresentation && threadRouteOpensDraft({ - connectionState: routeConnectionState, detailStatus: selectedThreadDetailState.status, + threadWasShown: shownThreadKey === routeThreadKey, }) ) { return ; @@ -350,6 +410,9 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { } onAction={() => { if (routeEnvironmentRuntime !== null) { + // This reconnects itself, so the new wait must not start the connection again. + connectionStartedKey.current = `${routeThreadKey}#${connectAttempt + 1}`; + setConnectAttempt(connectAttempt + 1); onReconnectEnvironment(environmentId); return; } diff --git a/apps/mobile/src/features/threads/thread-route-hydration.test.ts b/apps/mobile/src/features/threads/thread-route-hydration.test.ts index 9a7f1043609df..7685d9d91b8c6 100644 --- a/apps/mobile/src/features/threads/thread-route-hydration.test.ts +++ b/apps/mobile/src/features/threads/thread-route-hydration.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { threadDetailErrorIsCurrent, + threadRouteAwaitsConnection, threadRouteIsHydrating, threadRouteOpensDraft, } from "./thread-route-hydration"; @@ -95,29 +96,71 @@ describe("threadRouteIsHydrating", () => { }); }); -describe("threadRouteOpensDraft", () => { - it("keeps the route while a reconnecting environment may still deliver the thread", () => { - expect(threadRouteOpensDraft({ connectionState: "reconnecting", detailStatus: "empty" })).toBe( - false, - ); +describe("threadRouteAwaitsConnection", () => { + const missing = { + connectionState: "available" as const, + environmentEnabled: true, + detailStatus: "empty" as const, + graceExpired: false, + }; + + it("keeps a linked thread loading while its environment has not connected yet", () => { + expect(threadRouteAwaitsConnection(missing)).toBe(true); + expect(threadRouteAwaitsConnection({ ...missing, connectionState: "offline" })).toBe(true); + expect(threadRouteAwaitsConnection({ ...missing, connectionState: "reconnecting" })).toBe(true); + expect( + threadRouteAwaitsConnection({ + ...missing, + connectionState: "offline", + detailStatus: "cached", + }), + ).toBe(true); }); - it("keeps the route while Reconnect retries a thread that failed to sync", () => { - const failedDetail = { - ...settled, - connectionState: "connecting" as const, - detailStatus: "empty" as const, - detailHasError: true, - }; - expect(threadRouteIsHydrating(failedDetail)).toBe(false); - expect(threadRouteOpensDraft(failedDetail)).toBe(false); + it("stops waiting once the grace period ends", () => { + expect(threadRouteAwaitsConnection({ ...missing, graceExpired: true })).toBe(false); + expect( + threadRouteAwaitsConnection({ + ...missing, + connectionState: "reconnecting", + graceExpired: true, + }), + ).toBe(false); }); - it("opens a draft once the thread can't arrive", () => { + it("does not wait for a thread the environment reported deleted", () => { + expect(threadRouteAwaitsConnection({ ...missing, detailStatus: "deleted" })).toBe(false); + }); + + it("does not wait for an environment that won't connect by itself", () => { + expect(threadRouteAwaitsConnection({ ...missing, environmentEnabled: false })).toBe(false); + expect(threadRouteAwaitsConnection({ ...missing, connectionState: "error" })).toBe(false); + expect(threadRouteAwaitsConnection({ ...missing, connectionState: "unsupported" })).toBe(false); + }); + + it("leaves a connecting or connected environment to the hydration check", () => { + expect(threadRouteAwaitsConnection({ ...missing, connectionState: "connecting" })).toBe(false); + expect(threadRouteAwaitsConnection({ ...missing, connectionState: "connected" })).toBe(false); expect( - threadRouteOpensDraft({ connectionState: "reconnecting", detailStatus: "deleted" }), + threadRouteIsHydrating({ ...settled, connectionState: "connecting", detailStatus: "empty" }), ).toBe(true); - expect(threadRouteOpensDraft({ connectionState: "offline", detailStatus: "empty" })).toBe(true); + expect(threadRouteIsHydrating({ ...settled, detailStatus: "empty" })).toBe(true); + }); +}); + +describe("threadRouteOpensDraft", () => { + it("never replaces a linked thread the app hasn't loaded with a draft", () => { + expect(threadRouteOpensDraft({ detailStatus: "empty", threadWasShown: false })).toBe(false); + expect(threadRouteOpensDraft({ detailStatus: "deleted", threadWasShown: false })).toBe(false); + }); + + it("keeps a shown thread's route unless the environment reported it deleted", () => { + expect(threadRouteOpensDraft({ detailStatus: "empty", threadWasShown: true })).toBe(false); + expect(threadRouteOpensDraft({ detailStatus: "cached", threadWasShown: true })).toBe(false); + }); + + it("opens a draft in place of a shown thread that was deleted", () => { + expect(threadRouteOpensDraft({ detailStatus: "deleted", threadWasShown: true })).toBe(true); }); }); diff --git a/apps/mobile/src/features/threads/thread-route-hydration.ts b/apps/mobile/src/features/threads/thread-route-hydration.ts index a6e3454d47659..e601f0c37781f 100644 --- a/apps/mobile/src/features/threads/thread-route-hydration.ts +++ b/apps/mobile/src/features/threads/thread-route-hydration.ts @@ -44,18 +44,50 @@ export function threadRouteIsHydrating(input: { } /** - * Replacing the route with a draft can't be undone, so a thread that may still arrive keeps its - * route: a reconnecting environment often delivers it moments later, and Reconnect starts a - * fresh connecting attempt. + * How long a route whose thread isn't loaded waits for its environment to come up before it shows + * "Thread unavailable". A link opened on a cold start or a resume usually finds the environment + * not connected yet; one connection attempt may take up to its 15 s establishment timeout, and + * the thread's first snapshot follows within a few seconds. */ -export function threadRouteOpensDraft(input: { +export const THREAD_ROUTE_CONNECT_GRACE_MS = 20_000; + +/** + * A thread missing from the local snapshot may still arrive once the environment connects and the + * thread is fetched by id, so an environment that is not connected yet, or is retrying, holds the + * loading screen until the grace period ends. A switched-off or blocked environment won't connect + * by itself. + */ +export function threadRouteAwaitsConnection(input: { readonly connectionState: EnvironmentConnectionPhase; + readonly environmentEnabled: boolean; readonly detailStatus: EnvironmentThreadStatus; + readonly graceExpired: boolean; }): boolean { - if (input.detailStatus === "deleted") { - return true; + if (input.detailStatus === "deleted" || input.graceExpired || !input.environmentEnabled) { + return false; } - return input.connectionState !== "reconnecting" && input.connectionState !== "connecting"; + return ( + input.connectionState === "available" || + input.connectionState === "offline" || + input.connectionState === "reconnecting" + ); +} + +/** An offline or backing-off environment retries now rather than after its backoff. */ +export function threadRouteStartsConnection(connectionState: EnvironmentConnectionPhase): boolean { + return connectionState === "offline" || connectionState === "reconnecting"; +} + +/** + * Replacing the route with a draft can't be undone, so only a thread this route already showed, + * and which the environment then reported deleted, opens a new task in its place. A link to a + * thread the app hasn't loaded shows "Thread unavailable" instead, so the user can reconnect. + */ +export function threadRouteOpensDraft(input: { + readonly detailStatus: EnvironmentThreadStatus; + readonly threadWasShown: boolean; +}): boolean { + return input.detailStatus === "deleted" && input.threadWasShown; } /**