Skip to content
TypeScript

fix(mobile): threads open with less waiting, and the Threads tab remembers drafts (#24750)

Julius Marminge8d3261ebc222
diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx
index 493a5848fe5..e75b29a8805 100644
--- a/apps/mobile/src/features/home/thread-swipe-actions.tsx
+++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx
@@ -121,6 +121,9 @@ function resolveSecondaryAction(input: {
/** Keep the scroll gate in context so scroll start cannot re-render every row and its subscriptions. */
const SwipeableScrollGateContext = createContext(true);
+// Swipeable rebuilds its native pan gesture whenever its config changes identity, so the props
+// that feed it stay stable across row re-renders such as selection.
+const FAIL_OFFSET_Y: [number, number] = [-10, 10];
export function SwipeableScrollGateProvider(props: {
readonly enabled: boolean;
@@ -402,11 +405,77 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
},
[content],
);
- const handleWillOpen = () => {
- if (!props.dormant && !dismissalRef.current && swipeableRef.current) {
- props.onSwipeableWillOpen?.(swipeableRef.current);
+ const { dormant, onSwipeableWillOpen, backgroundColor, containerStyle } = props;
+ const handleWillOpen = useCallback(() => {
+ if (!dormant && !dismissalRef.current && swipeableRef.current) {
+ onSwipeableWillOpen?.(swipeableRef.current);
}
+ }, [dormant, onSwipeableWillOpen]);
+ const handleSwipeableClose = useCallback(() => {
+ if (swipeableRef.current) onSwipeableClose?.(swipeableRef.current);
+ }, [onSwipeableClose]);
+ const compactActions = props.compactActions === true;
+ const { secondaryAction, threadTitle } = props;
+ // Swipeable calls this on every render; returning the previous element while nothing it shows
+ // changed keeps a selection change from re-rendering the hidden actions.
+ const rightActions = useRef<{ deps: readonly unknown[]; element: ReactNode } | null>(null);
+ const renderRightActions = (
+ _progress: SharedValue<number>,
+ translation: SharedValue<number>,
+ methods: SwipeableMethods,
+ ) => {
+ const deps = [
+ dormant,
+ translation,
+ methods,
+ actionStyle,
+ backgroundColor,
+ compactActions,
+ fullSwipeAction,
+ fullSwipeThreshold,
+ handleFullSwipeArmedChange,
+ primaryAction,
+ commitPrimaryAction,
+ onDelete,
+ secondaryAction,
+ threadTitle,
+ ];
+ const cached = rightActions.current;
+ if (cached && deps.every((dep, index) => Object.is(dep, cached.deps[index]))) {
+ return cached.element;
+ }
+ const element = dormant ? null : (
+ <Animated.View
+ ref={() => {
+ activeTranslationRef.current = translation;
+ }}
+ style={actionStyle}
+ >
+ <ThreadSwipeActions
+ backgroundColor={backgroundColor}
+ compact={compactActions}
+ fullSwipeAction={fullSwipeAction}
+ fullSwipeThreshold={fullSwipeThreshold}
+ onFullSwipeArmedChange={handleFullSwipeArmedChange}
+ primaryAction={{ ...primaryAction, onPress: commitPrimaryAction }}
+ secondaryAction={resolveSecondaryAction({
+ close: () => methods.close(),
+ onDelete,
+ secondaryAction,
+ threadTitle,
+ })}
+ translation={translation}
+ />
+ </Animated.View>
+ );
+ rightActions.current = { deps, element };
+ return element;
};
+ const childrenContainerStyle = useMemo(() => ({ backgroundColor }), [backgroundColor]);
+ const swipeableContainerStyle = useMemo(
+ () => [{ backgroundColor }, containerStyle],
+ [backgroundColor, containerStyle],
+ );
return (
<Animated.View style={dismissStyle}>
@@ -419,53 +488,21 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
- childrenContainerStyle={{ backgroundColor: props.backgroundColor }}
- containerStyle={[{ backgroundColor: props.backgroundColor }, props.containerStyle]}
+ childrenContainerStyle={childrenContainerStyle}
+ containerStyle={swipeableContainerStyle}
dragOffsetFromRight={-8}
enabled={!props.dormant && !isDismissing && props.enabled !== false && gateEnabled}
enableTrackpadTwoFingerGesture={props.enableTrackpadSwipe ?? true}
// Reject vertical pans via patched RNGH failOffsetY; simultaneous trackpad scrolls otherwise open rows on horizontal drift.
- failOffsetY={[-10, 10]}
+ failOffsetY={FAIL_OFFSET_Y}
friction={1}
- onSwipeableClose={() => {
- if (swipeableRef.current) {
- props.onSwipeableClose?.(swipeableRef.current);
- }
- }}
+ onSwipeableClose={handleSwipeableClose}
onSwipeableRelease={handleRelease}
onSwipeableOpenStartDrag={handleWillOpen}
onSwipeableWillOpen={handleWillOpen}
overshootFriction={1}
overshootRight
- renderRightActions={(_progress, translation, methods) =>
- props.dormant ? null : (
- <Animated.View
- ref={() => {
- activeTranslationRef.current = translation;
- }}
- style={actionStyle}
- >
- <ThreadSwipeActions
- backgroundColor={props.backgroundColor}
- compact={props.compactActions === true}
- fullSwipeAction={fullSwipeAction}
- fullSwipeThreshold={fullSwipeThreshold}
- onFullSwipeArmedChange={handleFullSwipeArmedChange}
- primaryAction={{
- ...primaryAction,
- onPress: commitPrimaryAction,
- }}
- secondaryAction={resolveSecondaryAction({
- close: () => methods.close(),
- onDelete: props.onDelete,
- secondaryAction: props.secondaryAction,
- threadTitle: props.threadTitle,
- })}
- translation={translation}
- />
- </Animated.View>
- )
- }
+ renderRightActions={renderRightActions}
rightThreshold={actionsWidth * 0.42}
simultaneousWith={props.simultaneousWith}
>
diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
index 8de05e3118d..872f1f521f7 100644
--- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
+++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
@@ -66,6 +66,7 @@ import {
type WorkspaceDetail,
type WorkspaceDetailSheet,
} from "../workspace/workspace-detail-selection";
+import { startOpeningDetail } from "../workspace/useSelectWorkspaceDetail";
import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { newTaskDestination } from "../threads/new-task-project-selection";
@@ -498,6 +499,7 @@ function AdaptiveWorkspaceLayoutContent(
type: "select",
tab: detail.name === "Thread" ? "threads" : "pullRequests",
});
+ startOpeningDetail(detail);
navigation.dispatch(selectWorkspaceDetail(detail, sheet));
});
}
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index 6b70637f7bd..40cdfc1e3f8 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -499,6 +499,9 @@ function ThreadVisitWatermark(props: {
return null;
}
+// Past the composer's 180 ms height animation.
+const COMPOSER_HEIGHT_SETTLE_MS = 220;
+
export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
const deviceType = useDeviceType();
@@ -601,6 +604,24 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
const selectedThreadKeyRef = useRef(selectedThreadKey);
const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
const [composerHeight, setComposerHeight] = useState<number | null>(null);
+ // The composer animates its height and reports a layout every frame. The feed follows those
+ // frames on the UI thread through onComposerLayout; this is only an estimate, so committing
+ // each frame would re-render the whole screen for the length of the animation.
+ const composerHeightSettle = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const handleComposerHeightChange = useCallback((height: number) => {
+ setComposerHeight((current) => current ?? height);
+ if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
+ composerHeightSettle.current = setTimeout(() => {
+ composerHeightSettle.current = null;
+ setComposerHeight(height);
+ }, COMPOSER_HEIGHT_SETTLE_MS);
+ }, []);
+ useEffect(
+ () => () => {
+ if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
+ },
+ [],
+ );
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
@@ -1804,7 +1825,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
- onHeightChange={setComposerHeight}
+ onHeightChange={handleComposerHeightChange}
onEditorFocusChange={handleOwnedInputFocusChange}
/>
</>
diff --git a/apps/mobile/src/features/workspace/useSelectWorkspaceDetail.ts b/apps/mobile/src/features/workspace/useSelectWorkspaceDetail.ts
index a149212ba43..59d1ac1fd8d 100644
--- a/apps/mobile/src/features/workspace/useSelectWorkspaceDetail.ts
+++ b/apps/mobile/src/features/workspace/useSelectWorkspaceDetail.ts
@@ -1,11 +1,26 @@
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useNavigation } from "@react-navigation/native";
import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context";
+import { startOpeningEnvironmentThread } from "../../state/threads";
import {
selectWorkspaceDetail,
type WorkspaceDetail,
type WorkspaceDetailSheet,
} from "./workspace-detail-selection";
+const first = (value: string | readonly string[] | undefined) =>
+ typeof value === "string" ? value : value?.[0];
+
+/** Starts loading a selected thread before navigation commits; see `startOpeningEnvironmentThread`. */
+export function startOpeningDetail(detail: WorkspaceDetail) {
+ if (detail.name !== "Thread") return;
+ const environmentId = first(detail.params?.environmentId);
+ const threadId = first(detail.params?.threadId);
+ if (environmentId && threadId) {
+ startOpeningEnvironmentThread(EnvironmentId.make(environmentId), ThreadId.make(threadId));
+ }
+}
+
/**
* Shows a page in the detail column the way selecting its list row does. Inside the workspace
* layout this also settles its panes; outside it, the root stack's router still does the rest.
@@ -15,7 +30,9 @@ export function useSelectWorkspaceDetail() {
const { selectDetail } = useAdaptiveWorkspaceLayout();
return (
selectDetail ??
- ((detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) =>
- navigation.dispatch(selectWorkspaceDetail(detail, sheet)))
+ ((detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) => {
+ startOpeningDetail(detail);
+ navigation.dispatch(selectWorkspaceDetail(detail, sheet));
+ })
);
}
diff --git a/apps/mobile/src/features/workspace/workspace-selection-store.ts b/apps/mobile/src/features/workspace/workspace-selection-store.ts
index aaabc0f1715..e30533e4781 100644
--- a/apps/mobile/src/features/workspace/workspace-selection-store.ts
+++ b/apps/mobile/src/features/workspace/workspace-selection-store.ts
@@ -51,7 +51,7 @@ function save() {
function withoutRouteKeys(saved: WorkspaceSelections | undefined): WorkspaceSelections {
const omitKey = <Selection extends { readonly key?: string }>({ key: _, ...rest }: Selection) =>
rest;
- const { threads, pullRequests, settingsKey: _, ...rest } = saved ?? {};
+ const { threads, pullRequests, settingsKey: _, threadsDraft: _draft, ...rest } = saved ?? {};
return {
...rest,
...(threads ? { threads: omitKey(threads) } : {}),
diff --git a/apps/mobile/src/features/workspace/workspace-tab-navigation.test.ts b/apps/mobile/src/features/workspace/workspace-tab-navigation.test.ts
index a7c84f5f6d5..a6f4298d268 100644
--- a/apps/mobile/src/features/workspace/workspace-tab-navigation.test.ts
+++ b/apps/mobile/src/features/workspace/workspace-tab-navigation.test.ts
@@ -96,6 +96,30 @@ describe("opening a workspace tab", () => {
expect(back.routes.at(-1)).toMatchObject({ key: "thread", params: thread.params });
});
+ it("reopens a draft the tab showed after its last chat, until another chat opens", () => {
+ const columns = { columns: true, check: available };
+ const draft = { key: "draft", name: "Thread", params: { draft: { requestId: "r" } } };
+ const withDraft = workspaceSelectionsIn(
+ [home, draft],
+ workspaceSelectionsIn([home, thread], {}),
+ );
+ const back = workspaceTabNavigationState(
+ { routes: [home, settings] },
+ "threads",
+ withDraft,
+ columns,
+ );
+ expect(back.routes.at(-1)).toEqual(draft);
+ const afterChat = workspaceSelectionsIn([home, thread], withDraft);
+ const again = workspaceTabNavigationState(
+ { routes: [home, settings] },
+ "threads",
+ afterChat,
+ columns,
+ );
+ expect(again.routes.at(-1)).toMatchObject({ key: "thread", params: thread.params });
+ });
+
it("falls back to the list for a chat that no longer exists, or an unknown Settings page", () => {
const missing = { thread: () => false, pullRequest: () => true };
expect(
diff --git a/apps/mobile/src/features/workspace/workspace-tab-navigation.ts b/apps/mobile/src/features/workspace/workspace-tab-navigation.ts
index 27c11686fe1..1603f7894fe 100644
--- a/apps/mobile/src/features/workspace/workspace-tab-navigation.ts
+++ b/apps/mobile/src/features/workspace/workspace-tab-navigation.ts
@@ -91,9 +91,17 @@ export function workspaceSelectionsIn(
threadId &&
(next.threads?.environmentId !== environmentId ||
next.threads.threadId !== threadId ||
- next.threads.key !== thread?.key)
+ next.threads.key !== thread?.key ||
+ next.threadsDraft)
) {
- next = { ...next, threads: { environmentId, threadId, key: thread?.key } };
+ const { threadsDraft: _, ...rest } = next;
+ next = { ...rest, threads: { environmentId, threadId, key: thread?.key } };
+ } else if (
+ thread?.key !== undefined &&
+ !threadId &&
+ (next.threadsDraft?.key !== thread.key || next.threadsDraft.params !== thread.params)
+ ) {
+ next = { ...next, threadsDraft: { key: thread.key, params: thread.params } };
}
const pullRequestRoute = routes.findLast((route) => route.name === "PullRequest");
const pullRequest = pullRequestSelection(pullRequestRoute?.params);
@@ -136,6 +144,16 @@ function detailRoute(
check: WorkspaceSelectionCheck,
): RouteLike | undefined {
if (tab === "threads") {
+ const draft = selections.threadsDraft;
+ if (draft) {
+ return (
+ state.routes.find((route) => route.key === draft.key) ?? {
+ key: draft.key,
+ name: "Thread",
+ params: draft.params as object | undefined,
+ }
+ );
+ }
const thread = selections.threads;
if (!thread || !check.thread(thread)) return undefined;
return (
diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts
index c5fd4f487fb..dda53132870 100644
--- a/apps/mobile/src/persistence/mobile-preferences.ts
+++ b/apps/mobile/src/persistence/mobile-preferences.ts
@@ -71,6 +71,8 @@ const WorkspaceSelections = Schema.Struct({
),
settings: Schema.optional(Schema.String),
settingsKey: Schema.optional(Schema.String),
+ /** A draft the threads tab showed after its last chat; only meaningful in its session. */
+ threadsDraft: Schema.optional(Schema.Struct({ key: Schema.String, params: Schema.Unknown })),
});
export type WorkspaceSelections = typeof WorkspaceSelections.Type;
diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts
index 2b7d4db5b99..3f8be2e9290 100644
--- a/apps/mobile/src/state/threads.ts
+++ b/apps/mobile/src/state/threads.ts
@@ -46,6 +46,18 @@ export function useThreadFamily(
}, [environmentId, rootThreadId]);
}
+// Long enough for the opened screen to subscribe; its subscription keeps the thread after this.
+const OPENING_THREAD_HOLD_MS = 3_000;
+
+/**
+ * Starts loading a thread being opened before its screen renders and subscribes, which
+ * otherwise waits for navigation to commit.
+ */
+export function startOpeningEnvironmentThread(environmentId: EnvironmentId, threadId: ThreadId) {
+ const release = appAtomRegistry.mount(environmentThreads.stateAtom(environmentId, threadId));
+ setTimeout(release, OPENING_THREAD_HOLD_MS);
+}
+
const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
Atom.withLabel("mobile-environment-thread:empty"),
);