Skip to content
TypeScript

fix(mobile): open threads from the local cache instead of "Thread unavailable" (#25627)

Julius Marmingea54ba53a5c9d
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 87e57557eba..0287a6975f7 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -5,7 +5,12 @@ import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTu
import { useWorktreeSetup } from "./use-worktree-setup";
import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
import { AppBar } from "../../components/ui/AppBar";
-import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
+import {
+ StackActions,
+ useNavigation,
+ useRoute,
+ type StaticScreenProps,
+} from "@react-navigation/native";
import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import {
@@ -74,6 +79,9 @@ import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
import { threadEnvironment, useThreadFamily } from "../../state/threads";
+import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads";
+import { useProjects } from "../../state/entities";
+import { newTaskDestination } from "./new-task-project-selection";
import { projectThreadContentPresentation } from "./threadContentPresentation";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import {
@@ -191,6 +199,27 @@ function ThreadUnavailableScreen(props: {
);
}
+/** A thread that can't load opens a new task in its environment instead of a dead end. */
+function UnavailableThreadDraftRedirect(props: { readonly environmentId: EnvironmentId }) {
+ const navigation = useNavigation();
+ const projects = useProjects();
+ const { layout } = useAdaptiveWorkspaceLayout();
+ const openDraft = useEffectEvent(() => {
+ const project = projects.find((candidate) => candidate.environmentId === props.environmentId);
+ navigation.dispatch(
+ StackActions.replace(
+ "Thread",
+ newTaskDestination(layout.usesSplitView, projects, project, uuidv4()),
+ ),
+ );
+ });
+ // oxlint-disable-next-line t3code/react-effect-budget -- replaces this route in the navigator
+ useEffect(() => {
+ openDraft();
+ }, []);
+ return <OpeningThreadLoadingScreen />;
+}
+
export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
return (
<ThreadScreenHost>
@@ -225,6 +254,7 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
const { onReconnectEnvironment } = useRemoteConnections();
const navigation = useNavigation();
+ const routeName = useRoute().name;
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeThreadKey =
@@ -261,6 +291,10 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
const stillHydrating = threadRouteIsHydrating({
isLoadingConnections: !connectionsReady,
+ environmentRegistered: routeEnvironmentRuntime !== null,
+ localCacheRead:
+ routeEnvironmentShellState.cacheRead &&
+ selectedThreadDetailState !== EMPTY_ENVIRONMENT_THREAD_STATE,
connectionState: routeConnectionState,
shellStatus: routeEnvironmentShellState.status,
shellHasError: routeEnvironmentShellState.hasError,
@@ -272,6 +306,10 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
return withInspectorHeader(<OpeningThreadLoadingScreen />);
}
+ if (routeName === "Thread" && !props.inspectorPresentation) {
+ return <UnavailableThreadDraftRedirect environmentId={environmentId} />;
+ }
+
return withInspectorHeader(
<ThreadUnavailableScreen
actionLabel={
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 dfea7a57840..9d8ce88506f 100644
--- a/apps/mobile/src/features/threads/thread-route-hydration.test.ts
+++ b/apps/mobile/src/features/threads/thread-route-hydration.test.ts
@@ -4,6 +4,8 @@ import { threadRouteIsHydrating } from "./thread-route-hydration";
const settled = {
isLoadingConnections: false,
+ environmentRegistered: true,
+ localCacheRead: true,
connectionState: "connected" as const,
shellStatus: "live" as const,
shellHasError: false,
@@ -19,6 +21,21 @@ describe("threadRouteIsHydrating", () => {
expect(threadRouteIsHydrating({ ...settled, detailStatus: "empty" })).toBe(true);
});
+ it("waits for the local cache before trusting an offline connection", () => {
+ const offline = {
+ ...settled,
+ connectionState: "offline" as const,
+ detailStatus: "empty" as const,
+ };
+ expect(threadRouteIsHydrating({ ...offline, localCacheRead: false })).toBe(true);
+ expect(threadRouteIsHydrating(offline)).toBe(false);
+ expect(threadRouteIsHydrating({ ...offline, connectionState: "reconnecting" })).toBe(false);
+ expect(threadRouteIsHydrating({ ...offline, connectionState: "connecting" })).toBe(true);
+ expect(
+ threadRouteIsHydrating({ ...offline, localCacheRead: false, environmentRegistered: false }),
+ ).toBe(false);
+ });
+
it("stops waiting once an empty detail has an actionable outcome", () => {
expect(
threadRouteIsHydrating({
diff --git a/apps/mobile/src/features/threads/thread-route-hydration.ts b/apps/mobile/src/features/threads/thread-route-hydration.ts
index 345ec3e31fe..626e34cd7bb 100644
--- a/apps/mobile/src/features/threads/thread-route-hydration.ts
+++ b/apps/mobile/src/features/threads/thread-route-hydration.ts
@@ -4,6 +4,8 @@ import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/thre
export function threadRouteIsHydrating(input: {
readonly isLoadingConnections: boolean;
+ readonly environmentRegistered: boolean;
+ readonly localCacheRead: boolean;
readonly connectionState: EnvironmentConnectionPhase;
readonly shellStatus: EnvironmentShellStatus;
readonly shellHasError: boolean;
@@ -16,16 +18,23 @@ export function threadRouteIsHydrating(input: {
if (input.isLoadingConnections) {
return true;
}
+ if (!input.environmentRegistered) {
+ return false;
+ }
+ if (!input.localCacheRead) {
+ return true;
+ }
+ // Only a first attempt is worth waiting out; a reconnecting environment has already failed.
if (
input.connectionState === "available" ||
input.connectionState === "offline" ||
+ input.connectionState === "reconnecting" ||
input.connectionState === "error"
) {
return false;
}
return (
input.connectionState === "connecting" ||
- input.connectionState === "reconnecting" ||
input.shellStatus === "synchronizing" ||
(input.connectionState === "connected" && input.shellStatus === "empty") ||
input.detailStatus === "synchronizing" ||
diff --git a/apps/mobile/src/features/workspace/workspace-selection-store.ts b/apps/mobile/src/features/workspace/workspace-selection-store.ts
index e30533e4781..62adcd07005 100644
--- a/apps/mobile/src/features/workspace/workspace-selection-store.ts
+++ b/apps/mobile/src/features/workspace/workspace-selection-store.ts
@@ -19,7 +19,11 @@ import { workspaceRoutesOf } from "../layout/workspace-overlay-routes";
import type { WorkspaceSelections } from "../../persistence/mobile-preferences";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentPresentations } from "../../state/presentation";
-import { environmentThreadShells, threadEnvironment } from "../../state/threads";
+import {
+ environmentThreadShells,
+ startOpeningEnvironmentThread,
+ threadEnvironment,
+} from "../../state/threads";
import {
rememberedSettingsPage,
workspaceSelectionsIn,
@@ -137,11 +141,17 @@ export function settingsLinkPage() {
*/
export async function launchWorkspaceURL(): Promise<string | null> {
if (!REMEMBERS) return null;
- await Promise.all([
- hydrateWorkspaceSelections(),
- firstNativeLayoutMetrics(NATIVE_METRICS_TIMEOUT_MS),
- ]);
+ const metrics = firstNativeLayoutMetrics(NATIVE_METRICS_TIMEOUT_MS);
+ await hydrateWorkspaceSelections();
const thread = selections.threads;
+ // Read the chat's cached copy while the layout metrics are still on their way.
+ if (thread) {
+ startOpeningEnvironmentThread(
+ thread.environmentId as EnvironmentId,
+ thread.threadId as ThreadId,
+ );
+ }
+ await metrics;
if (!thread || !workspaceHasColumns() || !workspaceSelectionCheck.thread(thread)) return null;
return Linking.createURL(
`threads/${encodeURIComponent(thread.environmentId)}/${encodeURIComponent(thread.threadId)}`,
diff --git a/apps/mobile/src/state/shell.ts b/apps/mobile/src/state/shell.ts
index dc1bbf967e8..bdde55e8b46 100644
--- a/apps/mobile/src/state/shell.ts
+++ b/apps/mobile/src/state/shell.ts
@@ -26,6 +26,8 @@ const EMPTY_ENVIRONMENT_SHELL_STATE_ATOM = Atom.make<EnvironmentShellState>(EMPT
const shellStatus = (state: EnvironmentShellState) => state.status;
const shellHasError = (state: EnvironmentShellState) => Option.isSome(state.error);
+// The empty placeholder stands until the environment has read its cached shell.
+const shellCacheRead = (state: EnvironmentShellState) => state !== EMPTY_SHELL_STATE;
export function useEnvironmentShellReadiness(environmentId: EnvironmentId | null) {
const atom =
@@ -35,5 +37,6 @@ export function useEnvironmentShellReadiness(environmentId: EnvironmentId | null
return {
status: useAtomValue(atom, shellStatus),
hasError: useAtomValue(atom, shellHasError),
+ cacheRead: useAtomValue(atom, shellCacheRead),
};
}
diff --git a/packages/client-runtime/src/state/presentation.test.ts b/packages/client-runtime/src/state/presentation.test.ts
index 3c3fa20a4a9..7e9cce628e5 100644
--- a/packages/client-runtime/src/state/presentation.test.ts
+++ b/packages/client-runtime/src/state/presentation.test.ts
@@ -135,3 +135,25 @@ describe("presentations with providers", () => {
}
});
});
+
+describe("connection presentation", () => {
+ it("presents an enabled environment as connecting until its supervisor reports", () => {
+ const h = harness();
+ const phase = () => h.registry.get(h.full.presentationAtom(FIRST))?.connection.phase;
+ const stop = h.registry.subscribe(h.full.presentationAtom(FIRST), () => {});
+ try {
+ expect(phase()).toBe("connecting");
+ h.registry.set(h.catalog, {
+ isReady: true,
+ entries: new Map([[FIRST, { ...entry(FIRST), enabled: false }]]),
+ });
+ expect(phase()).toBe("available");
+ h.registry.set(h.catalog, { isReady: true, entries: new Map([[FIRST, entry(FIRST)]]) });
+ h.registry.set(h.state, AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE }));
+ expect(phase()).toBe("available");
+ } finally {
+ stop();
+ h.registry.dispose();
+ }
+ });
+});
diff --git a/packages/client-runtime/src/state/presentation.ts b/packages/client-runtime/src/state/presentation.ts
index 48d27974a2c..a6d1c22c121 100644
--- a/packages/client-runtime/src/state/presentation.ts
+++ b/packages/client-runtime/src/state/presentation.ts
@@ -82,10 +82,13 @@ export function createEnvironmentPresentationAtoms<E>(input: {
() => AVAILABLE_CONNECTION_STATE,
);
const previous = Option.getOrNull(get.self<EnvironmentPresentation | null>());
+ // The supervisor never publishes this placeholder; an enabled one starts out connecting.
const connection: EnvironmentConnectionPresentation =
- entry.unsupportedReason === undefined
- ? presentEnvironmentConnection(state)
- : { phase: "unsupported", error: entry.unsupportedReason, traceId: null };
+ entry.unsupportedReason !== undefined
+ ? { phase: "unsupported", error: entry.unsupportedReason, traceId: null }
+ : state === AVAILABLE_CONNECTION_STATE && entry.enabled
+ ? { phase: "connecting", error: null, traceId: null }
+ : presentEnvironmentConnection(state);
const next = {
entry,
connection: