Skip to content

Commit e3dc152

Browse files
fix(mobile): open threads from the local cache instead of "Thread unavailable"
The thread route treated the connection placeholder shown before a supervisor reports ("available") as a settled outcome, so it showed "Thread unavailable" before the cached shell and thread were even read. Enabled environments now present as connecting until their supervisor reports, the route waits for the local cache read, and a thread that still can't load opens a new draft in its environment instead of a dead end. A cold start also starts reading the remembered thread's cache while it waits for native layout metrics. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e762f09 commit e3dc152

7 files changed

Lines changed: 112 additions & 10 deletions

File tree

‎apps/mobile/src/features/threads/ThreadRouteScreen.tsx‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@ import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTu
55
import { useWorktreeSetup } from "./use-worktree-setup";
66
import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
77
import { AppBar } from "../../components/ui/AppBar";
8-
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
8+
import {
9+
StackActions,
10+
useNavigation,
11+
useRoute,
12+
type StaticScreenProps,
13+
} from "@react-navigation/native";
914
import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
1015
import * as Option from "effect/Option";
1116
import {
@@ -74,6 +79,9 @@ import { useThreadComposerState } from "../../state/use-thread-composer-state";
7479
import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
7580
import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
7681
import { threadEnvironment, useThreadFamily } from "../../state/threads";
82+
import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads";
83+
import { useProjects } from "../../state/entities";
84+
import { newTaskDestination } from "./new-task-project-selection";
7785
import { projectThreadContentPresentation } from "./threadContentPresentation";
7886
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
7987
import {
@@ -191,6 +199,27 @@ function ThreadUnavailableScreen(props: {
191199
);
192200
}
193201

202+
/** A thread that can't load opens a new task in its environment instead of a dead end. */
203+
function UnavailableThreadDraftRedirect(props: { readonly environmentId: EnvironmentId }) {
204+
const navigation = useNavigation();
205+
const projects = useProjects();
206+
const { layout } = useAdaptiveWorkspaceLayout();
207+
const openDraft = useEffectEvent(() => {
208+
const project = projects.find((candidate) => candidate.environmentId === props.environmentId);
209+
navigation.dispatch(
210+
StackActions.replace(
211+
"Thread",
212+
newTaskDestination(layout.usesSplitView, projects, project, uuidv4()),
213+
),
214+
);
215+
});
216+
// oxlint-disable-next-line t3code/react-effect-budget -- replaces this route in the navigator
217+
useEffect(() => {
218+
openDraft();
219+
}, []);
220+
return <OpeningThreadLoadingScreen />;
221+
}
222+
194223
export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
195224
return (
196225
<ThreadScreenHost>
@@ -225,6 +254,7 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
225254
const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
226255
const { onReconnectEnvironment } = useRemoteConnections();
227256
const navigation = useNavigation();
257+
const routeName = useRoute().name;
228258
const routeConnectionState =
229259
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
230260
const routeThreadKey =
@@ -261,6 +291,10 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
261291

262292
const stillHydrating = threadRouteIsHydrating({
263293
isLoadingConnections: !connectionsReady,
294+
environmentRegistered: routeEnvironmentRuntime !== null,
295+
localCacheRead:
296+
routeEnvironmentShellState.cacheRead &&
297+
selectedThreadDetailState !== EMPTY_ENVIRONMENT_THREAD_STATE,
264298
connectionState: routeConnectionState,
265299
shellStatus: routeEnvironmentShellState.status,
266300
shellHasError: routeEnvironmentShellState.hasError,
@@ -272,6 +306,10 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
272306
return withInspectorHeader(<OpeningThreadLoadingScreen />);
273307
}
274308

309+
if (routeName === "Thread") {
310+
return <UnavailableThreadDraftRedirect environmentId={environmentId} />;
311+
}
312+
275313
return withInspectorHeader(
276314
<ThreadUnavailableScreen
277315
actionLabel={

‎apps/mobile/src/features/threads/thread-route-hydration.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import { threadRouteIsHydrating } from "./thread-route-hydration";
44

55
const settled = {
66
isLoadingConnections: false,
7+
environmentRegistered: true,
8+
localCacheRead: true,
79
connectionState: "connected" as const,
810
shellStatus: "live" as const,
911
shellHasError: false,
@@ -19,6 +21,21 @@ describe("threadRouteIsHydrating", () => {
1921
expect(threadRouteIsHydrating({ ...settled, detailStatus: "empty" })).toBe(true);
2022
});
2123

24+
it("waits for the local cache before trusting an offline connection", () => {
25+
const offline = {
26+
...settled,
27+
connectionState: "offline" as const,
28+
detailStatus: "empty" as const,
29+
};
30+
expect(threadRouteIsHydrating({ ...offline, localCacheRead: false })).toBe(true);
31+
expect(threadRouteIsHydrating(offline)).toBe(false);
32+
expect(threadRouteIsHydrating({ ...offline, connectionState: "reconnecting" })).toBe(false);
33+
expect(threadRouteIsHydrating({ ...offline, connectionState: "connecting" })).toBe(true);
34+
expect(
35+
threadRouteIsHydrating({ ...offline, localCacheRead: false, environmentRegistered: false }),
36+
).toBe(false);
37+
});
38+
2239
it("stops waiting once an empty detail has an actionable outcome", () => {
2340
expect(
2441
threadRouteIsHydrating({

‎apps/mobile/src/features/threads/thread-route-hydration.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/thre
44

55
export function threadRouteIsHydrating(input: {
66
readonly isLoadingConnections: boolean;
7+
readonly environmentRegistered: boolean;
8+
readonly localCacheRead: boolean;
79
readonly connectionState: EnvironmentConnectionPhase;
810
readonly shellStatus: EnvironmentShellStatus;
911
readonly shellHasError: boolean;
@@ -16,16 +18,23 @@ export function threadRouteIsHydrating(input: {
1618
if (input.isLoadingConnections) {
1719
return true;
1820
}
21+
if (!input.environmentRegistered) {
22+
return false;
23+
}
24+
if (!input.localCacheRead) {
25+
return true;
26+
}
27+
// Only a first attempt is worth waiting out; a reconnecting environment has already failed.
1928
if (
2029
input.connectionState === "available" ||
2130
input.connectionState === "offline" ||
31+
input.connectionState === "reconnecting" ||
2232
input.connectionState === "error"
2333
) {
2434
return false;
2535
}
2636
return (
2737
input.connectionState === "connecting" ||
28-
input.connectionState === "reconnecting" ||
2938
input.shellStatus === "synchronizing" ||
3039
(input.connectionState === "connected" && input.shellStatus === "empty") ||
3140
input.detailStatus === "synchronizing" ||

‎apps/mobile/src/features/workspace/workspace-selection-store.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ import { workspaceRoutesOf } from "../layout/workspace-overlay-routes";
1919
import type { WorkspaceSelections } from "../../persistence/mobile-preferences";
2020
import { appAtomRegistry } from "../../state/atom-registry";
2121
import { environmentPresentations } from "../../state/presentation";
22-
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
22+
import {
23+
environmentThreadShells,
24+
startOpeningEnvironmentThread,
25+
threadEnvironment,
26+
} from "../../state/threads";
2327
import {
2428
rememberedSettingsPage,
2529
workspaceSelectionsIn,
@@ -137,11 +141,17 @@ export function settingsLinkPage() {
137141
*/
138142
export async function launchWorkspaceURL(): Promise<string | null> {
139143
if (!REMEMBERS) return null;
140-
await Promise.all([
141-
hydrateWorkspaceSelections(),
142-
firstNativeLayoutMetrics(NATIVE_METRICS_TIMEOUT_MS),
143-
]);
144+
const metrics = firstNativeLayoutMetrics(NATIVE_METRICS_TIMEOUT_MS);
145+
await hydrateWorkspaceSelections();
144146
const thread = selections.threads;
147+
// Read the chat's cached copy while the layout metrics are still on their way.
148+
if (thread) {
149+
startOpeningEnvironmentThread(
150+
thread.environmentId as EnvironmentId,
151+
thread.threadId as ThreadId,
152+
);
153+
}
154+
await metrics;
145155
if (!thread || !workspaceHasColumns() || !workspaceSelectionCheck.thread(thread)) return null;
146156
return Linking.createURL(
147157
`threads/${encodeURIComponent(thread.environmentId)}/${encodeURIComponent(thread.threadId)}`,

‎apps/mobile/src/state/shell.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ const EMPTY_ENVIRONMENT_SHELL_STATE_ATOM = Atom.make<EnvironmentShellState>(EMPT
2626

2727
const shellStatus = (state: EnvironmentShellState) => state.status;
2828
const shellHasError = (state: EnvironmentShellState) => Option.isSome(state.error);
29+
// The empty placeholder stands until the environment has read its cached shell.
30+
const shellCacheRead = (state: EnvironmentShellState) => state !== EMPTY_SHELL_STATE;
2931

3032
export function useEnvironmentShellReadiness(environmentId: EnvironmentId | null) {
3133
const atom =
@@ -35,5 +37,6 @@ export function useEnvironmentShellReadiness(environmentId: EnvironmentId | null
3537
return {
3638
status: useAtomValue(atom, shellStatus),
3739
hasError: useAtomValue(atom, shellHasError),
40+
cacheRead: useAtomValue(atom, shellCacheRead),
3841
};
3942
}

‎packages/client-runtime/src/state/presentation.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,25 @@ describe("presentations with providers", () => {
135135
}
136136
});
137137
});
138+
139+
describe("connection presentation", () => {
140+
it("presents an enabled environment as connecting until its supervisor reports", () => {
141+
const h = harness();
142+
const phase = () => h.registry.get(h.full.presentationAtom(FIRST))?.connection.phase;
143+
const stop = h.registry.subscribe(h.full.presentationAtom(FIRST), () => {});
144+
try {
145+
expect(phase()).toBe("connecting");
146+
h.registry.set(h.catalog, {
147+
isReady: true,
148+
entries: new Map([[FIRST, { ...entry(FIRST), enabled: false }]]),
149+
});
150+
expect(phase()).toBe("available");
151+
h.registry.set(h.catalog, { isReady: true, entries: new Map([[FIRST, entry(FIRST)]]) });
152+
h.registry.set(h.state, AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE }));
153+
expect(phase()).toBe("available");
154+
} finally {
155+
stop();
156+
h.registry.dispose();
157+
}
158+
});
159+
});

‎packages/client-runtime/src/state/presentation.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,13 @@ export function createEnvironmentPresentationAtoms<E>(input: {
8282
() => AVAILABLE_CONNECTION_STATE,
8383
);
8484
const previous = Option.getOrNull(get.self<EnvironmentPresentation | null>());
85+
// The supervisor never publishes this placeholder; an enabled one starts out connecting.
8586
const connection: EnvironmentConnectionPresentation =
86-
entry.unsupportedReason === undefined
87-
? presentEnvironmentConnection(state)
88-
: { phase: "unsupported", error: entry.unsupportedReason, traceId: null };
87+
entry.unsupportedReason !== undefined
88+
? { phase: "unsupported", error: entry.unsupportedReason, traceId: null }
89+
: state === AVAILABLE_CONNECTION_STATE && entry.enabled
90+
? { phase: "connecting", error: null, traceId: null }
91+
: presentEnvironmentConnection(state);
8992
const next = {
9093
entry,
9194
connection:

0 commit comments

Comments
 (0)