@devries-cameron20 / t3code-1 / commits / e9236274a3
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(mobile): showcase capture runs as an app service, not a chain of effects (#25857)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 05:42 UTC e9236274a3a6e0c731a7df4092db1e686f039068
6 files changed +384 -247
apps/mobile/src/App.tsx
+3 -1
@@ -24,6 +24,7 @@ import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet
24 import * as Dialog from "./components/ui/Dialog";
25 import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
26 import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
27 +import { installShowcaseCapture } from "./features/showcase/ShowcaseCaptureCoordinator";
28 import {
29 presentPendingIncomingShare,
30 pruneIncomingShareImports,
@@ -42,7 +43,7 @@ import {
43 installAppearanceRuntime,
44 useAppearancePreferences,
45 } from "./features/settings/appearance/AppearancePreferencesProvider";
45 -import { RootStack, workspaceLocationFromState } from "./Stack";
46 +import { RootStack, rootPathnameFromState, workspaceLocationFromState } from "./Stack";
47 import { appAtomRegistry } from "./state/atom-registry";
48 import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
49 import { environmentThreadShells } from "./state/threads";
@@ -181,6 +182,7 @@ const appServiceDisposers = [
182 installAgentNotificationNavigation(linkToAppPath),
183 installAppShortcuts(linkToAppPath),
184 installAppUpdateChecks(),
185 + installShowcaseCapture(rootPathnameFromState),
186 ];
187 disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => {
188 for (const dispose of appServiceDisposers) dispose();
apps/mobile/src/Stack.tsx
+8 -4
@@ -137,7 +137,7 @@ import {
137 isWorkspaceOverlayRoute,
138 registerPresentedRoutes,
139 } from "./features/layout/workspace-overlay-routes";
140 -import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
140 +import { ShowcaseReadyMarker } from "./features/showcase/ShowcaseCaptureCoordinator";
141 import {
142 SettingsLegalDocumentCloseHeaderButton,
143 SettingsLegalDocumentExternalHeaderButton,
@@ -492,12 +492,16 @@ export function workspaceLocationFromState(state: NavigationState) {
492 };
493 }
494
495 +export function rootPathnameFromState(state: NavigationState): string {
496 + const path = getPathFromState(state, navigationPathConfig);
497 + return path.startsWith("/") ? path : `/${path}`;
498 +}
499 +
500 function RootStackLayout(props: {
501 readonly children: React.ReactNode;
502 readonly state: NavigationState;
503 }) {
499 - const path = getPathFromState(props.state, navigationPathConfig);
500 - const pathname = path.startsWith("/") ? path : `/${path}`;
504 + const pathname = rootPathnameFromState(props.state);
505 const workspaceLocation = workspaceLocationFromState(props.state);
506 const settingsOpen = settingsOpenIn(
507 props.state.routes
@@ -524,7 +528,7 @@ function RootStackLayout(props: {
528 routeDraftId={routeDraftId}
529 >
530 <HardwareKeyboardCommandProvider pathname={pathname}>
527 - <ShowcaseCaptureCoordinator pathname={pathname} />
531 + <ShowcaseReadyMarker />
532 <SettingsEnvironmentFilterProvider open={settingsOpen}>
533 <WorkspaceConnectionStatusProvider>
534 <AndroidWorkspaceTabsProvider state={props.state}>
apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx
+1 -1
@@ -111,7 +111,7 @@ function resolveThemeVariablesByAppearance(
111 }
112
113 /** The appearance whose theme is on screen, read from the native scheme. */
114 -function resolveThemeAppearance(stored: Preferences | null): MobileThemeAppearance {
114 +export function resolveThemeAppearance(stored: Preferences | null): MobileThemeAppearance {
115 const themeMode = normalizeMobileThemeMode(stored?.themeMode);
116 if (themeMode !== "system") return themeMode;
117 return Appearance.getColorScheme() === "dark" ? "dark" : "light";
apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx
+334 -241
@@ -1,16 +1,30 @@
1 -import { useEffect, useEffectEvent, useRef, useState, useSyncExternalStore } from "react";
2 -import { Keyboard, View } from "react-native";
3 -import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
1 +import { useSyncExternalStore } from "react";
2 +import { Appearance, Keyboard, View } from "react-native";
3 +import {
4 + CommonActions,
5 + StackActions,
6 + type NavigationAction,
7 + type NavigationState,
8 +} from "@react-navigation/native";
9 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
10 import { AsyncResult } from "effect/reactivity";
11 import { requireOptionalNativeModule } from "expo";
12
7 -import { useConnectionController } from "../connection/useConnectionController";
8 -import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
9 -import type { MobileThemeId } from "../../lib/mobileTheme";
10 -import { useProjects, useThreadShells } from "../../state/entities";
13 +import { connectPairingUrl } from "../../connection/onboarding";
14 +import {
15 + createMobileThemePairPatch,
16 + resolveMobileThemeIds,
17 + type MobileThemeId,
18 +} from "../../lib/mobileTheme";
19 +import { rootNavigationRef } from "../../lib/rootNavigation";
20 +import { appAtomRegistry } from "../../state/atom-registry";
21 +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
22 +import { environmentProjects } from "../../state/projects";
23 import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
24 +import { environmentThreadShells } from "../../state/threads";
25 import { holdEditingQueuedMessage } from "../../state/use-thread-outbox";
13 -import { useWorkspaceState } from "../../state/workspace";
26 +import { workspaceConnections } from "../../state/workspace";
27 +import { resolveThemeAppearance } from "../settings/appearance/AppearancePreferencesProvider";
28 import {
29 applyNativeShowcaseOrientation,
30 getNativeShowcaseOrientation,
@@ -20,299 +34,378 @@ import {
34 markNativeShowcaseReady,
35 type ShowcaseScene,
36 } from "./nativeShowcaseScene";
23 -import {
24 - buildShowcasePendingTasks,
25 - SHOWCASE_PENDING_TASK_DEFINITIONS,
26 -} from "./showcasePendingTasks";
37 import { buildShowcaseAgentActivity } from "./showcaseAgentActivity";
38 import {
39 isShowcaseThemeApplied,
40 SHOWCASE_THREAD_ID,
41 showcaseReadinessKey,
42 showcaseSceneOnScreen,
43 + shouldNavigateToShowcaseScene,
44 + type ShowcaseNavigationTarget,
45 } from "./showcaseCaptureModel";
34 -import { retryShowcaseOperation } from "./showcaseRetry";
46 +import {
47 + buildShowcasePendingTasks,
48 + SHOWCASE_PENDING_TASK_DEFINITIONS,
49 +} from "./showcasePendingTasks";
50 import {
51 clearShowcaseRenderSignal,
52 getShowcaseRenderSnapshot,
53 subscribeToShowcaseRenderSignal,
54 } from "./showcaseRenderSignal";
55 +import { retryShowcaseOperation } from "./showcaseRetry";
56 import { stageShowcaseAgentActivity } from "./stageShowcaseAgentActivity";
41 -import { openSettings } from "../settings/settings-navigation";
57 +import { settingsNavigationState } from "../settings/settings-navigation";
58 import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection";
59
60 const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
61 +// Native launch requests (pairing links, scene switches) have no change event.
62 +const NATIVE_POLL_MS = 250;
63 +const READY_SETTLE_MS = 500;
64
46 -export function ShowcaseCaptureCoordinator(props: { readonly pathname: string }) {
47 - if (!SHOWCASE_ENABLED) return null;
48 - return <EnabledShowcaseCaptureCoordinator pathname={props.pathname} />;
49 -}
50 -
51 -function EnabledShowcaseCaptureCoordinator(props: { readonly pathname: string }) {
52 - const navigation = useNavigation();
53 - useEffect(() => {
54 - const menu = requireOptionalNativeModule<{
55 - closeMenu(): void;
56 - setToolsButtonVisible(visible: boolean): void;
57 - }>("ExpoDevMenu");
58 - // The dev menu can open after bundle loading and block orientation requests.
59 - const timer = setInterval(() => {
60 - menu?.closeMenu();
61 - menu?.setToolsButtonVisible(false);
62 - }, 1_000);
63 - return () => clearInterval(timer);
64 - }, []);
65 - const { connectPairingUrl } = useConnectionController();
66 - const {
67 - isReady: appearancePreferencesReady,
68 - themeId,
69 - themeIds,
70 - setThemeIdForBothAppearances,
71 - } = useAppearancePreferences();
72 - const workspace = useWorkspaceState();
73 - const projects = useProjects();
74 - const threads = useThreadShells();
75 - const attemptedPairingRef = useRef(new Set<string>());
76 - const seededPendingTaskIdsRef = useRef(new Set<string>());
77 - const [pairingUrls, setPairingUrls] = useState<ReadonlyArray<string>>([]);
78 - const [pendingTasksReady, setPendingTasksReady] = useState(false);
79 - const [requestedScene, setRequestedScene] = useState<ShowcaseScene | null>(null);
80 - const [requestedTheme, setRequestedTheme] = useState<MobileThemeId | null>(null);
81 - const [themeRequestSettled, setThemeRequestSettled] = useState(false);
82 - const [readyScene, setReadyScene] = useState<ShowcaseScene | null>(null);
83 - const [orientationSettled, setOrientationSettled] = useState(false);
84 - const [agentActivityStaged, setAgentActivityStaged] = useState(false);
85 - const requestedSceneRef = useRef<ShowcaseScene | null>(null);
86 - // Read current entities without restarting on shell updates and re-entering open permission prompts.
87 - const readFixtureEntities = useEffectEvent(() => ({ threads, projects }));
88 - const { signal: renderSignal, reports: renderReports } = useSyncExternalStore(
89 - subscribeToShowcaseRenderSignal,
90 - getShowcaseRenderSnapshot,
91 - getShowcaseRenderSnapshot,
92 - );
93 -
94 - useEffect(() => {
95 - if (pairingUrls.length > 0) return;
65 +const readySceneListeners = new Set<() => void>();
66 +let readyScene: ShowcaseScene | null = null;
67
97 - const readLaunchRequest = () => {
98 - const values = getNativeShowcasePairingUrls();
99 - if (values.length === 0) return;
100 - setRequestedTheme(getNativeShowcaseTheme());
101 - setThemeRequestSettled(true);
102 - setPairingUrls(values);
103 - };
104 - readLaunchRequest();
105 - const interval = setInterval(readLaunchRequest, 250);
106 - return () => clearInterval(interval);
107 - }, [pairingUrls.length]);
68 +function setReadyScene(scene: ShowcaseScene | null): void {
69 + if (readyScene === scene) return;
70 + readyScene = scene;
71 + for (const listener of readySceneListeners) listener();
72 +}
73
109 - useEffect(() => {
110 - if (orientationSettled) return;
111 - const orientation = getNativeShowcaseOrientation();
112 - if (orientation === null) {
113 - // oxlint-disable-next-line react/set-state-in-effect -- Capture readiness follows the native orientation change.
114 - setOrientationSettled(true);
115 - return;
116 - }
74 +function subscribeToReadyScene(listener: () => void): () => void {
75 + readySceneListeners.add(listener);
76 + return () => readySceneListeners.delete(listener);
77 +}
78
118 - let cancelled = false;
119 - void retryShowcaseOperation(async () => applyNativeShowcaseOrientation(orientation), {
120 - isCancelled: () => cancelled,
121 - }).then((applied) => {
122 - if (!cancelled && applied) setOrientationSettled(true);
123 - });
124 - return () => {
125 - cancelled = true;
126 - };
127 - }, [orientationSettled]);
79 +function getReadyScene(): ShowcaseScene | null {
80 + return readyScene;
81 +}
82
129 - useEffect(() => {
130 - const readRequestedScene = () => {
131 - const value = getNativeShowcaseScene();
132 - if (!value || requestedSceneRef.current === value) return;
133 - requestedSceneRef.current = value;
134 - // Draws belong to their scene request; revisiting review must wait for its new surface.
135 - clearShowcaseRenderSignal();
136 - setAgentActivityStaged(false);
137 - setRequestedScene(value);
138 - };
139 - readRequestedScene();
140 - const interval = setInterval(readRequestedScene, 250);
141 - return () => clearInterval(interval);
142 - }, []);
83 +interface Run {
84 + cancelled: boolean;
85 + done: boolean;
86 +}
87
144 - const themeApplied = isShowcaseThemeApplied({
145 - launchRequestRead: themeRequestSettled,
146 - requestedTheme,
147 - themeIds,
148 - });
88 +function cancelRun(run: Run | null): null {
89 + if (run) run.cancelled = true;
90 + return null;
91 +}
92
150 - useEffect(() => {
151 - if (requestedTheme === null || themeApplied || !appearancePreferencesReady) {
152 - return;
153 - }
154 - setThemeIdForBothAppearances(requestedTheme);
155 - }, [appearancePreferencesReady, requestedTheme, setThemeIdForBothAppearances, themeApplied]);
93 +function showcaseNavigationAction(
94 + scene: ShowcaseScene,
95 + environmentId: string,
96 + rootState: NavigationState,
97 +): NavigationAction {
98 + const params = { environmentId, threadId: SHOWCASE_THREAD_ID };
99 + switch (scene) {
100 + case "threads":
101 + return StackActions.popToTop();
102 + case "agent-activity":
103 + return CommonActions.reset({ index: 0, routes: [{ name: "Home" }] });
104 + case "environments":
105 + return CommonActions.reset(settingsNavigationState(rootState, "SettingsEnvironments"));
106 + case "terminal":
107 + return CommonActions.navigate("ThreadTerminal", { ...params, terminalId: "term-1" });
108 + case "review":
109 + return CommonActions.navigate("ThreadReview", params);
110 + case "thread":
111 + return selectWorkspaceDetail({ name: "Thread", params });
112 + }
113 +}
114
157 - useEffect(() => {
158 - if (pairingUrls.length === 0) return;
159 - let cancelled = false;
160 - void (async () => {
161 - await Promise.all(
162 - pairingUrls.map(async (pairingUrl) => {
163 - if (cancelled || attemptedPairingRef.current.has(pairingUrl)) return;
164 - const paired = await retryShowcaseOperation(
165 - async () => AsyncResult.isSuccess(await connectPairingUrl(pairingUrl)),
166 - { isCancelled: () => cancelled },
167 - );
168 - if (paired) attemptedPairingRef.current.add(pairingUrl);
169 - }),
170 - );
171 - })();
172 - return () => {
173 - cancelled = true;
174 - };
175 - }, [connectPairingUrl, pairingUrls]);
115 +/**
116 + * Drives a showcase capture: pairs servers, seeds the fixture, applies theme and
117 + * orientation, and navigates to each scene the native harness requests. Inputs
118 + * are read from their stores on each step, so nothing depends on render timing.
119 + */
120 +export function installShowcaseCapture(
121 + pathnameFromState: (state: NavigationState) => string,
122 +): () => void {
123 + if (!SHOWCASE_ENABLED) return () => {};
124
177 - const scene = showcaseSceneOnScreen(requestedScene, props.pathname);
178 - const hasServerFixture =
179 - workspace.state.hasReadyEnvironment &&
180 - workspace.environments.length >= 3 &&
181 - projects.length >= 3 &&
182 - threads.some((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
183 - const hasFixture = hasServerFixture && pendingTasksReady;
184 - const showcaseThread = threads.find((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
125 + let disposed = false;
126 + let launchRequestRead = false;
127 + let requestedTheme: MobileThemeId | null = null;
128 + let orientationSettled = false;
129 + let requestedScene: ShowcaseScene | null = null;
130 + let pendingTasks: Run | null = null;
131 + let agentActivity: Run | null = null;
132 + let lastNavigation: ShowcaseNavigationTarget | null = null;
133 + let readiness: { key: string; cancel: () => void } | null = null;
134 + const isCancelled = (run?: Run) => () => disposed || run?.cancelled === true;
135
186 - useEffect(() => {
187 - if (!hasServerFixture || pendingTasksReady) return;
136 + const devMenu = requireOptionalNativeModule<{
137 + closeMenu(): void;
138 + setToolsButtonVisible(visible: boolean): void;
139 + }>("ExpoDevMenu");
140 + // The dev menu can open after bundle loading and block orientation requests.
141 + const devMenuTimer = setInterval(() => {
142 + devMenu?.closeMenu();
143 + devMenu?.setToolsButtonVisible(false);
144 + }, 1_000);
145
189 - const pendingTasks = buildShowcasePendingTasks(projects, Date.now());
190 - if (pendingTasks.length !== SHOWCASE_PENDING_TASK_DEFINITIONS.length) return;
146 + const orientation = getNativeShowcaseOrientation();
147 + if (orientation === null) {
148 + orientationSettled = true;
149 + } else {
150 + void retryShowcaseOperation(async () => applyNativeShowcaseOrientation(orientation), {
151 + isCancelled: isCancelled(),
152 + }).then((applied) => {
153 + if (!applied) return;
154 + orientationSettled = true;
155 + evaluate();
156 + });
157 + }
158
192 - let cancelled = false;
193 - for (const task of pendingTasks) holdEditingQueuedMessage(task.messageId);
194 - void (async () => {
195 - const results = await Promise.all(
196 - pendingTasks.map(async (task) => {
197 - const messageId = String(task.messageId);
198 - if (seededPendingTaskIdsRef.current.has(messageId)) return true;
199 - const seeded = await retryShowcaseOperation(
200 - async () => {
201 - await enqueueThreadOutboxMessage(task);
202 - return true;
203 - },
204 - { isCancelled: () => cancelled },
205 - );
206 - if (seeded) seededPendingTaskIdsRef.current.add(messageId);
207 - return seeded;
208 - }),
159 + const pair = (pairingUrls: ReadonlyArray<string>) => {
160 + for (const pairingUrl of pairingUrls) {
161 + void retryShowcaseOperation(
162 + async () =>
163 + AsyncResult.isSuccess(
164 + await runAtomCommand(
165 + appAtomRegistry,
166 + connectPairingUrl,
167 + { pairingUrl },
168 + { reportFailure: false },
169 + ),
170 + ),
171 + { isCancelled: isCancelled() },
172 );
210 - if (!cancelled && results.every(Boolean)) setPendingTasksReady(true);
211 - })();
212 - return () => {
213 - cancelled = true;
214 - };
215 - }, [hasServerFixture, pendingTasksReady, projects]);
216 -
217 - useEffect(() => {
218 - if (requestedScene === null || !hasFixture || !showcaseThread) return;
219 - if (scene === requestedScene) return;
220 -
221 - const params = {
222 - environmentId: String(showcaseThread.environmentId),
223 - threadId: SHOWCASE_THREAD_ID,
224 - };
225 - if (requestedScene === "threads") {
226 - navigation.dispatch(StackActions.popToTop());
227 - return;
173 }
229 - if (requestedScene === "agent-activity") {
230 - navigation.dispatch(CommonActions.reset({ index: 0, routes: [{ name: "Home" }] }));
231 - return;
174 + };
175 +
176 + const readNativeRequests = () => {
177 + if (!launchRequestRead) {
178 + const pairingUrls = getNativeShowcasePairingUrls();
179 + if (pairingUrls.length > 0) {
180 + launchRequestRead = true;
181 + requestedTheme = getNativeShowcaseTheme();
182 + pair(pairingUrls);
183 + }
184 }
233 - if (requestedScene === "environments") {
234 - openSettings(navigation, "SettingsEnvironments");
235 - } else if (requestedScene === "terminal") {
236 - navigation.dispatch(
237 - CommonActions.navigate("ThreadTerminal", { ...params, terminalId: "term-1" }),
238 - );
239 - } else if (requestedScene === "review") {
240 - navigation.dispatch(CommonActions.navigate("ThreadReview", params));
241 - } else {
242 - navigation.dispatch(selectWorkspaceDetail({ name: "Thread", params }));
185 + const scene = getNativeShowcaseScene();
186 + if (scene && scene !== requestedScene) {
187 + requestedScene = scene;
188 + // Draws belong to their scene request; revisiting review must wait for its new surface.
189 + clearShowcaseRenderSignal();
190 + agentActivity = cancelRun(agentActivity);
191 }
244 - }, [hasFixture, navigation, requestedScene, scene, showcaseThread]);
192 + };
193
246 - useEffect(() => {
247 - if (scene !== "agent-activity" || !hasFixture || agentActivityStaged) {
248 - return;
249 - }
250 - let cancelled = false;
194 + const seedPendingTasks = () => {
195 + const pendingTaskList = buildShowcasePendingTasks(
196 + appAtomRegistry.get(environmentProjects.projectsAtom),
197 + Date.now(),
198 + );
199 + if (pendingTaskList.length !== SHOWCASE_PENDING_TASK_DEFINITIONS.length) return;
200 + const run: Run = { cancelled: false, done: false };
201 + pendingTasks = run;
202 + for (const task of pendingTaskList) holdEditingQueuedMessage(task.messageId);
203 + void Promise.all(
204 + pendingTaskList.map((task) =>
205 + retryShowcaseOperation(
206 + async () => {
207 + await enqueueThreadOutboxMessage(task);
208 + return true;
209 + },
210 + { isCancelled: isCancelled(run) },
211 + ),
212 + ),
213 + ).then((results) => {
214 + if (run.cancelled || !results.every(Boolean)) return;
215 + run.done = true;
216 + evaluate();
217 + });
218 + };
219 +
220 + const stageAgentActivity = () => {
221 + const run: Run = { cancelled: false, done: false };
222 + agentActivity = run;
223 let lastOutcome: string | null = null;
224 void retryShowcaseOperation(
225 async () => {
226 const now = Date.now();
255 - const { threads: latestThreads, projects: latestProjects } = readFixtureEntities();
256 - const activity = buildShowcaseAgentActivity(latestThreads, latestProjects, now);
227 + const activity = buildShowcaseAgentActivity(
228 + appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
229 + appAtomRegistry.get(environmentProjects.projectsAtom),
230 + now,
231 + );
232 const outcome =
233 activity === null
234 ? "fixture threads not loaded"
235 : await stageShowcaseAgentActivity(activity, now);
236 if (outcome === true) return true;
262 - if (outcome !== lastOutcome)
237 + if (outcome !== lastOutcome) {
238 console.warn(`[showcase] agent activity not staged: ${outcome}`);
239 + }
240 lastOutcome = outcome;
241 return false;
242 },
267 - { isCancelled: () => cancelled, attemptTimeoutMs: 60_000 },
243 + { isCancelled: isCancelled(run), attemptTimeoutMs: 60_000 },
244 ).then((staged) => {
269 - if (!cancelled && staged) setAgentActivityStaged(true);
245 + if (run.cancelled || !staged) return;
246 + run.done = true;
247 + evaluate();
248 });
271 - return () => {
272 - cancelled = true;
273 - };
274 - }, [agentActivityStaged, hasFixture, scene]);
249 + };
250
276 - const readinessKey = showcaseReadinessKey({
277 - scene,
278 - requestedScene,
279 - hasFixture,
280 - orientationSettled,
281 - themeApplied,
282 - agentActivityStaged,
283 - themeId,
284 - renderSignal,
285 - renderReports,
286 - });
287 - // Losing readiness hides the marker. A redraw or theme change while ready keeps it and re-settles.
288 - if (readinessKey === null && readyScene !== null) setReadyScene(null);
289 -
290 - useEffect(() => {
291 - if (readinessKey === null || scene === null) return;
251 + const updateReadiness = (key: string | null, scene: ShowcaseScene | null) => {
252 + if (readiness?.key === key) return;
253 + readiness?.cancel();
254 + readiness = null;
255 + if (key === null || scene === null) {
256 + setReadyScene(null);
257 + return;
258 + }
259 if (scene === "terminal") Keyboard.dismiss();
293 -
294 - let renderFrame: number | null = null;
295 - let readyFrame: number | null = null;
260 + let frame: number | null = null;
261 + // Two frames after the settle delay so the scene has been drawn, not just committed.
262 const settleTimer = setTimeout(() => {
297 - renderFrame = requestAnimationFrame(() => {
298 - readyFrame = requestAnimationFrame(() => {
263 + frame = requestAnimationFrame(() => {
264 + frame = requestAnimationFrame(() => {
265 + frame = null;
266 markNativeShowcaseReady(scene);
267 setReadyScene(scene);
268 });
269 });
303 - }, 500);
304 - return () => {
305 - clearTimeout(settleTimer);
306 - if (renderFrame !== null) cancelAnimationFrame(renderFrame);
307 - if (readyFrame !== null) cancelAnimationFrame(readyFrame);
270 + }, READY_SETTLE_MS);
271 + readiness = {
272 + key,
273 + cancel: () => {
274 + clearTimeout(settleTimer);
275 + if (frame !== null) cancelAnimationFrame(frame);
276 + },
277 };
309 - }, [readinessKey, scene]);
278 + };
279 +
280 + const step = () => {
281 + readNativeRequests();
282 +
283 + const preferences = appAtomRegistry.get(mobilePreferencesAtom);
284 + const storedPreferences = AsyncResult.isSuccess(preferences) ? preferences.value : null;
285 + const themeIds = resolveMobileThemeIds(storedPreferences ?? {});
286 + const themeApplied = isShowcaseThemeApplied({ launchRequestRead, requestedTheme, themeIds });
287 + // The write patches preferences optimistically, so the step it triggers
288 + // already sees the theme applied. A failed save rolls the patch back, and
289 + // the next step writes again.
290 + if (requestedTheme !== null && !themeApplied && storedPreferences) {
291 + appAtomRegistry.set(updateMobilePreferencesAtom, createMobileThemePairPatch(requestedTheme));
292 + }
293 + const themeId = themeIds[resolveThemeAppearance(storedPreferences)];
294 +
295 + const projects = appAtomRegistry.get(environmentProjects.projectsAtom);
296 + const threads = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
297 + const showcaseThread = threads.find((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
298 + const hasServerFixture =
299 + appAtomRegistry.get(workspaceConnections.stateAtom).hasReadyEnvironment &&
300 + appAtomRegistry.get(workspaceConnections.environmentsAtom).length >= 3 &&
301 + projects.length >= 3 &&
302 + showcaseThread !== undefined;
303 + if (hasServerFixture && pendingTasks === null) seedPendingTasks();
304 + const hasFixture = hasServerFixture && pendingTasks?.done === true;
305 +
306 + const navigationReady = rootNavigationRef.isReady();
307 + const rootState = navigationReady ? rootNavigationRef.getRootState() : undefined;
308 + const scene = rootState
309 + ? showcaseSceneOnScreen(requestedScene, pathnameFromState(rootState))
310 + : null;
311 +
312 + if (requestedScene !== null && hasFixture && showcaseThread && rootState) {
313 + const navigation = { requestedScene, scene, thread: showcaseThread };
314 + // Arriving forgets the target, so leaving the scene again navigates back.
315 + if (scene === requestedScene) {
316 + lastNavigation = null;
317 + } else if (shouldNavigateToShowcaseScene(lastNavigation, navigation)) {
318 + lastNavigation = navigation;
319 + rootNavigationRef.dispatch({
320 + ...showcaseNavigationAction(
321 + requestedScene,
322 + String(showcaseThread.environmentId),
323 + rootState,
324 + ),
325 + target: rootState.key,
326 + });
327 + }
328 + }
329 +
330 + if (scene === "agent-activity" && hasFixture) {
331 + if (agentActivity === null) stageAgentActivity();
332 + } else if (agentActivity?.done === false) {
333 + agentActivity = cancelRun(agentActivity);
334 + }
335 +
336 + const render = getShowcaseRenderSnapshot();
337 + updateReadiness(
338 + showcaseReadinessKey({
339 + scene,
340 + requestedScene,
341 + hasFixture,
342 + orientationSettled,
343 + themeApplied,
344 + agentActivityStaged: agentActivity?.done === true,
345 + themeId,
346 + renderSignal: render.signal,
347 + renderReports: render.reports,
348 + }),
349 + scene,
350 + );
351 + };
352 +
353 + // Steps write atoms they also observe; a nested change reruns the step once
354 + // the current one finishes instead of interleaving with it.
355 + let stepping = false;
356 + let stepAgain = false;
357 + function evaluate() {
358 + if (disposed) return;
359 + if (stepping) {
360 + stepAgain = true;
361 + return;
362 + }
363 + stepping = true;
364 + try {
365 + do {
366 + stepAgain = false;
367 + step();
368 + } while (stepAgain);
369 + } finally {
370 + stepping = false;
371 + }
372 + }
373 +
374 + const unsubscribers = [
375 + appAtomRegistry.subscribe(mobilePreferencesAtom, evaluate),
376 + appAtomRegistry.subscribe(environmentProjects.projectsAtom, evaluate),
377 + appAtomRegistry.subscribe(environmentThreadShells.threadShellsAtom, evaluate),
378 + appAtomRegistry.subscribe(workspaceConnections.stateAtom, evaluate),
379 + appAtomRegistry.subscribe(workspaceConnections.environmentsAtom, evaluate),
380 + subscribeToShowcaseRenderSignal(evaluate),
381 + rootNavigationRef.addListener("state", evaluate),
382 + ];
383 + const appearanceSubscription = Appearance.addChangeListener(evaluate);
384 + const pollTimer = setInterval(evaluate, NATIVE_POLL_MS);
385 + evaluate();
386 +
387 + return () => {
388 + disposed = true;
389 + clearInterval(devMenuTimer);
390 + clearInterval(pollTimer);
391 + appearanceSubscription.remove();
392 + for (const unsubscribe of unsubscribers) unsubscribe();
393 + pendingTasks = cancelRun(pendingTasks);
394 + agentActivity = cancelRun(agentActivity);
395 + readiness?.cancel();
396 + readiness = null;
397 + setReadyScene(null);
398 + };
399 +}
400
311 - if (readyScene === null) return null;
401 +/** The capture harness waits for this marker before taking a screenshot. */
402 +export function ShowcaseReadyMarker() {
403 + const scene = useSyncExternalStore(subscribeToReadyScene, getReadyScene, getReadyScene);
404 + if (scene === null) return null;
405 return (
406 <View
407 pointerEvents="none"
315 - testID={`showcase-ready-${readyScene}`}
408 + testID={`showcase-ready-${scene}`}
409 style={{ position: "absolute", width: 1, height: 1, opacity: 0.01 }}
410 />
411 );
apps/mobile/src/features/showcase/showcaseCaptureModel.test.ts
+13
@@ -4,6 +4,7 @@ import {
4 isShowcaseThemeApplied,
5 showcaseReadinessKey,
6 showcaseSceneOnScreen,
7 + shouldNavigateToShowcaseScene,
8 type ShowcaseReadinessInput,
9 } from "./showcaseCaptureModel";
10
@@ -84,3 +85,15 @@ describe("showcaseReadinessKey", () => {
85 expect(showcaseReadinessKey({ ...drawn, renderReports: 2 })).not.toBe(firstDraw);
86 });
87 });
88 +
89 +describe("shouldNavigateToShowcaseScene", () => {
90 + it("dispatches again when the thread shell changes while the scene is still not on screen", () => {
91 + const shell = { id: "remote-command-center" };
92 + const first = { requestedScene: "review", scene: "threads", thread: shell } as const;
93 + expect(shouldNavigateToShowcaseScene(null, first)).toBe(true);
94 + expect(shouldNavigateToShowcaseScene(first, { ...first })).toBe(false);
95 + expect(shouldNavigateToShowcaseScene(first, { ...first, thread: { ...shell } })).toBe(true);
96 + expect(shouldNavigateToShowcaseScene(first, { ...first, scene: "thread" })).toBe(true);
97 + expect(shouldNavigateToShowcaseScene(first, { ...first, scene: "review" })).toBe(false);
98 + });
99 +});
apps/mobile/src/features/showcase/showcaseCaptureModel.ts
+25
@@ -27,6 +27,31 @@ export function showcaseSceneOnScreen(
27 : routeScene;
28 }
29
30 +export interface ShowcaseNavigationTarget {
31 + readonly requestedScene: ShowcaseScene;
32 + readonly scene: ShowcaseScene | null;
33 + /** The showcase thread shell; a new shell (or environment) is a new target to navigate to. */
34 + readonly thread: object;
35 +}
36 +
37 +/**
38 + * Whether to dispatch the navigation for `next`, given the target last dispatched. A target is
39 + * dispatched once, and again whenever any part of it changes, so a dispatch that did not move
40 + * the route is retried when the thread shell or route updates.
41 + */
42 +export function shouldNavigateToShowcaseScene(
43 + last: ShowcaseNavigationTarget | null,
44 + next: ShowcaseNavigationTarget,
45 +): boolean {
46 + return (
47 + next.scene !== next.requestedScene &&
48 + (last === null ||
49 + last.requestedScene !== next.requestedScene ||
50 + last.scene !== next.scene ||
51 + last.thread !== next.thread)
52 + );
53 +}
54 +
55 export function isShowcaseThemeApplied(input: {
56 readonly launchRequestRead: boolean;
57 readonly requestedTheme: MobileThemeId | null;