Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion apps/mobile/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ import {
import { pruneNewTaskFlowStates } from "./features/threads/new-task-flow-state";
import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";
import { installAppUpdateChecks } from "./features/updates/app-updates";
import { perfProbe } from "./features/development/perf-probe-hooks";

import "../global.css";

Expand Down Expand Up @@ -303,7 +304,12 @@ function AppContent() {
<QuickActionsLanguage />
<SubscriptionUsageCoordinator />
<ConnectDeviceApprovalCoordinator />
<GestureHandlerRootView className="flex-1">
<GestureHandlerRootView
className="flex-1"
onTouchStartCapture={perfProbe?.touchStart}
onTouchEndCapture={perfProbe?.touchEnd}
onTouchCancelCapture={perfProbe?.touchEnd}
>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
<StatusBar barStyle={themeAppearance === "dark" ? "light-content" : "dark-content"} />
Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/components/ui/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { ColorValue, PressableProps } from "react-native";
import { withUniwind } from "uniwind";
import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider";
import { withMenuActionIconColors } from "../../lib/menu-action-colors";
import { perfProbe } from "../../features/development/perf-probe-hooks";
import type { MenuProps } from "./Menu.types";

const ThemedMenuView = withUniwind(
Expand Down Expand Up @@ -99,6 +100,13 @@ export function Menu(props: MenuProps) {
}
};
}
const { onPressAction } = props;
const probe = perfProbe;
if (probe && onPressAction)
menuProps.onPressAction = (event) => {
probe.menuAction();
onPressAction(event);
};
return (
<ThemedMenuView
{...menuProps}
Expand Down
11 changes: 10 additions & 1 deletion apps/mobile/src/components/ui/nativeHeaderMenu.ios.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { perfProbe } from "../../features/development/perf-probe-hooks";
import { Toolbar } from "./Toolbar";

import type { AppBarMenu, AppBarMenuItem } from "./AppBar.types";

function renderMenuItems(items: ReadonlyArray<AppBarMenuItem>) {
const probe = perfProbe;
return items.map((item) =>
"items" in item ? (
<Toolbar.Menu key={item.id} title={item.title} icon={item.icon} inline={item.inline}>
Expand All @@ -16,7 +18,14 @@ function renderMenuItems(items: ReadonlyArray<AppBarMenuItem>) {
disabled={item.disabled}
destructive={item.destructive}
isOn={item.selected}
onPress={item.onPress}
onPress={
probe
? () => {
probe.menuAction();
item.onPress();
}
: item.onPress
}
>
{item.title}
</Toolbar.MenuAction>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ vi.mock("./environmentSections", () => ({
vi.mock("./devAutoConnect", () => ({
autoConnectReport: () => ({ connecting: false, error: null }),
devAutoConnectAttemptAtom: {},
pairingLinksAllowed: () => __DEV__,
}));
vi.mock("../../state/use-remote-environment-registry", () => ({
setPendingConnectionError: (message: string | null) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ import { useRemoteConnections } from "../../state/use-remote-environment-registr
import { SymbolView } from "../../components/ui/AppSymbol";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect";
import {
autoConnectReport,
devAutoConnectAttemptAtom,
pairingLinksAllowed,
} from "./devAutoConnect";
import { linkedEnvironmentPrefillAtom } from "./linkedEnvironmentPrefill";
import { splitEnvironmentSections } from "./environmentSections";
import { leaveSettingsPage } from "../settings/settings-navigation";
Expand All @@ -49,8 +53,8 @@ export function ConnectionsNewRouteScreen({
route,
}: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
const params = route.params ?? {};
// Dev-only prefill prevents production links from supplying an attacker-chosen host and token.
const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
// Store builds ignore the prefill so a link can never supply an attacker-chosen host and token.
const routePairingUrl = pairingLinksAllowed() ? (params.pairingUrl?.trim() ?? "") : "";
const known = useAtomValue(linkedEnvironmentPrefillAtom);
const linked = known !== null && known.environmentId === params.linked ? known : null;
// A new prefill link replaces whatever the form held.
Expand Down
10 changes: 10 additions & 0 deletions apps/mobile/src/features/connection/devAutoConnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ it("only prefills without the flag, and ignores the flag in production builds",
expect(harness.pair).not.toHaveBeenCalled();
});

it("auto-connects in a production bundle only when mobile:metrics built it with the probe", () => {
harness.pair.mockClear();
harness.pair.mockResolvedValueOnce({ ok: false, error: null });
vi.stubGlobal("__DEV__", false);
vi.stubEnv("EXPO_PUBLIC_T3_BEHAVIOR_PROBE", "1");
startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
vi.unstubAllEnvs();
expect(harness.pair).toHaveBeenCalledOnce();
});

it("forgets a failed auto-connect once the form is opened again without the flag", async () => {
vi.stubGlobal("__DEV__", true);
const failed = Promise.withResolvers<{ ok: boolean; error: string | null }>();
Expand Down
9 changes: 8 additions & 1 deletion apps/mobile/src/features/connection/devAutoConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ export function withoutPairingTarget(
});
}

/**
* Pairing links prefill and auto-connect only in development and in mobile:metrics' release
* bundles, the one production bundle built with the probe flag; store builds never set it.
*/
export const pairingLinksAllowed = () =>
__DEV__ || process.env.EXPO_PUBLIC_T3_BEHAVIOR_PROBE === "1";

/**
* `connections/new?pairingUrl=…&autoConnect=1` (or `settings/environment-new?…`) pairs from the
* link itself, so a remount of the form never pairs twice. Production builds ignore the flag so
Expand All @@ -92,7 +99,7 @@ export function withoutPairingTarget(
export function startDevAutoConnect(
state: PartialState<NavigationState> | undefined,
): PartialState<NavigationState> | undefined {
if (!__DEV__) return state;
if (!pairingLinksAllowed()) return state;
const route = findLinkedRoute(state, PAIRING_FORM_ROUTES);
if (route === undefined) return state;
const params = (route.params ?? {}) as {
Expand Down
19 changes: 17 additions & 2 deletions apps/mobile/src/features/development/behavior-probe-entry.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
// Metro folds this condition before collecting dependencies, excluding the probe from release bundles.
if (__DEV__ && process.env.EXPO_PUBLIC_T3_BEHAVIOR_PROBE === "1") {
// Production bundles inline the unset flag, so Metro folds this away before collecting dependencies.
// Only mobile:behavior's and mobile:metrics' Metro sets it, including mobile:metrics' release bundle.
if (process.env.EXPO_PUBLIC_T3_BEHAVIOR_PROBE === "1") {
// A production bundle sets up no DevTools hook; React still reports commits to one it finds.
const global = globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: object };
if (!__DEV__)
global.__REACT_DEVTOOLS_GLOBAL_HOOK__ ??= {
isDisabled: false,
supportsFiber: true,
renderers: new Map(),
inject: () => 1,
onScheduleFiberRoot: () => {},
onCommitFiberRoot: () => {},
onCommitFiberUnmount: () => {},
onPostCommitFiberRoot: () => {},
checkDCE: () => {},
};
require("./behavior-probe");
}
127 changes: 126 additions & 1 deletion apps/mobile/src/features/development/behavior-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ interface Fiber {
readonly memoizedProps: Record<string, unknown> | null;
}
interface DevToolsHook {
onCommitFiberRoot?: (id: unknown, root: { current: Fiber }, ...rest: unknown[]) => unknown;
onCommitFiberRoot?: (
id: unknown,
root: { current: Fiber & { readonly actualDuration?: number } },
...rest: unknown[]
) => unknown;
__t3BehaviorProbe?: true;
}
interface ListState {
Expand Down Expand Up @@ -46,10 +50,48 @@ function installCommitHook() {
const original = hook.onCommitFiberRoot.bind(hook);
hook.onCommitFiberRoot = (id, next, ...rest) => {
roots.add(next);
// Development builds time each commit's render work on the root fiber.
if (perf) perf.commits.push({ at: performance.now(), ms: next.current.actualDuration ?? 0 });
return original(id, next, ...rest);
};
}

/** What one measured interaction did, from `perfStart` to `perfStop`; read by mobile:metrics. */
interface PerfWindow {
readonly startedAt: number;
readonly inputs: Array<{ readonly kind: string; readonly at: number }>;
readonly commits: Array<{ readonly at: number; readonly ms: number }>;
readonly content: Array<{ readonly thread: string; readonly at: number; frameAt: number | null }>;
readonly keys: number[];
}
let perf: PerfWindow | null = null;
const perfInput = (kind: string) => perf?.inputs.push({ kind, at: performance.now() });

// The app's input points (see perf-probe-hooks.ts); they record only inside a window.
Object.assign(globalThis, {
__t3PerfProbe: {
touchStart: () => perfInput("touch-start"),
touchEnd: () => perfInput("touch-end"),
menuAction: () => perfInput("menu-action"),
key: () => {
const window = perf;
if (!window) return;
const at = performance.now();
window.inputs.push({ kind: "key", at });
requestAnimationFrame(() => window.keys.push(performance.now() - at));
},
contentShown: (thread: string) => {
const window = perf;
if (!window) return;
const entry = { thread, at: performance.now(), frameAt: null as number | null };
window.content.push(entry);
requestAnimationFrame(() => {
entry.frameAt = performance.now();
});
},
},
});

/** Visits every mounted fiber; `enter` returns the context passed to the fiber's children. */
function walk<C>(fiber: Fiber | null, context: C, enter: (fiber: Fiber, context: C) => C) {
let node = fiber;
Expand Down Expand Up @@ -329,5 +371,88 @@ Object.assign(globalThis, {
sampled = null;
return JSON.stringify({ js: frames.js, ui: runOnUISync(uiFramesStop), feed: samples });
},
/** Opens a perf window: inputs, commits, timeline content and frames until `perfStop`. */
perfStart() {
perf = { startedAt: performance.now(), inputs: [], commits: [], content: [], keys: [] };
const counter = globalThis as { __t3RenderCounterStart?: () => boolean };
counter.__t3RenderCounterStart?.();
return this.recordStart(false);
},
/** Cheap progress of the open window, so the harness can wait for quiet without a tree walk. */
perfPeek() {
const window = perf;
const last = Math.max(
window?.inputs.at(-1)?.at ?? 0,
window?.commits.at(-1)?.at ?? 0,
window?.content.at(-1)?.frameAt ?? 0,
);
return JSON.stringify({
now: performance.now(),
last,
inputs: window?.inputs.length ?? 0,
content: window?.content.flatMap((entry) => (entry.frameAt === null ? [] : [entry.thread])),
});
},
perfStop() {
const window = perf;
perf = null;
const counter = globalThis as { __t3RenderCounterStop?: () => unknown };
const { js, ui } = JSON.parse(this.recordStop()) as { js: number[]; ui: number[] };
const hermes = (
globalThis as { HermesInternal?: { getInstrumentedStats?: () => Record<string, number> } }
).HermesInternal?.getInstrumentedStats?.();
return JSON.stringify({
...window,
js,
ui,
renders: counter.__t3RenderCounterStop?.() ?? null,
heapBytes: hermes?.js_heapSize ?? null,
});
},
/** What the app holds: atom registry nodes by label, and mounted fibers by component. */
retention() {
const { appAtomRegistry } = require("../../state/atom-registry") as {
appAtomRegistry: { getNodes: () => ReadonlyMap<unknown, unknown> };
};
const atoms = new Map<string, number>();
for (const key of appAtomRegistry.getNodes().keys()) {
const label =
typeof key === "string"
? `key:${key.split(/[:/]/)[0]}`
: ((key as { label?: readonly [string, ...unknown[]] | string }).label ?? "unlabeled");
const name = Array.isArray(label) ? String(label[0]) : String(label);
atoms.set(name, (atoms.get(name) ?? 0) + 1);
}
const fibers = new Map<string, number>();
let fiberCount = 0;
for (const root of roots)
walk(root.current, null, (fiber) => {
fiberCount += 1;
const type = fiber.type as { displayName?: string; name?: string } | string | null;
const name = typeof type === "string" ? type : (type?.displayName ?? type?.name ?? "");
if (name) fibers.set(name, (fibers.get(name) ?? 0) + 1);
return null;
});
const top = (map: Map<string, number>) =>
Object.fromEntries([...map].sort((a, b) => b[1] - a[1]).slice(0, 25));
return JSON.stringify({
atomCount: appAtomRegistry.getNodes().size,
fiberCount,
atoms: top(atoms),
fibers: top(fibers),
});
},
/** The Hermes heap, after a full collection when this runtime exposes `gc`. */
heap() {
const internal = globalThis as {
gc?: () => void;
HermesInternal?: { getInstrumentedStats?: () => Record<string, number> };
};
internal.gc?.();
return JSON.stringify({
bytes: internal.HermesInternal?.getInstrumentedStats?.().js_heapSize ?? null,
collected: typeof internal.gc === "function",
});
},
},
});
15 changes: 15 additions & 0 deletions apps/mobile/src/features/development/perf-probe-hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/** Input points for mobile:metrics' perf windows; null unless the env-gated behavior probe loaded. */
export interface PerfProbe {
readonly touchStart: () => void;
readonly touchEnd: () => void;
/** A native menu item's JS handler ran: the first point JS sees of a tap inside a native menu. */
readonly menuAction: () => void;
/** The composer's text changed: one key. */
readonly key: () => void;
/** A thread's timeline rows became visible. */
readonly contentShown: (thread: string) => void;
}

// behavior-probe-entry runs before the app's modules in index.ts, so this is read after it installs.
export const perfProbe: PerfProbe | null =
(globalThis as { __t3PerfProbe?: PerfProbe }).__t3PerfProbe ?? null;
2 changes: 2 additions & 0 deletions apps/mobile/src/features/threads/ThreadComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ import {
import { useVoiceInputController } from "../voice-input/useVoiceInputController";
import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
import type { ExistingThreadSettingsRouteParams } from "./ThreadSettingsSheet";
import { perfProbe } from "../development/perf-probe-hooks";
import {
useThreadSettingsSheetPresentation,
type NavigationWithFinishTransitioning,
Expand Down Expand Up @@ -901,6 +902,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
skills={composerMenu.skills}
selection={composerMenu.selection}
onChangeText={(text) => {
perfProbe?.key();
if (!isSubmissionLocked) props.onChangeDraftMessage(text);
}}
onSelectionChange={composerMenu.onSelectionChange}
Expand Down
12 changes: 12 additions & 0 deletions apps/mobile/src/features/threads/ThreadFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ import {
THREAD_FEED_MAINTAIN_SCROLL_AT_END_THRESHOLD,
} from "./threadFeedEndFollow";
import { useMessageTimeFormatter } from "./useMessageTimeFormatter";
import { perfProbe, type PerfProbe } from "../development/perf-probe-hooks";

const linkedThreadEnvironmentIds = (markdown: string, environmentId: EnvironmentId) =>
hasThreadLinks(markdown)
Expand Down Expand Up @@ -3096,6 +3097,14 @@ function DisclosureRow(props: {
// instead of at width 0 and again when the new feed's own layout reports the same width.
let lastSplitViewport: { windowWidth: number; width: number; height: number } | null = null;

/** Tells mobile:metrics' probe the commit that first showed this thread's rows. */
function PerfContentMark(props: { readonly probe: PerfProbe; readonly thread: string }) {
const { probe, thread } = props;
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the visible commit to the dev-only perf probe
useLayoutEffect(() => probe.contentShown(thread), [probe, thread]);
return null;
}

export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const gt = useGT();
const m = useMessages();
Expand Down Expand Up @@ -4306,6 +4315,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
className="flex-1"
style={splitLayout && viewportWidth > 0 ? { width: viewportWidth } : undefined}
>
{perfProbe && !settling && props.feed.length > 0 ? (
<PerfContentMark key={feedThreadKey} probe={perfProbe} thread={feedThreadKey} />
) : null}
{/* oxlint-disable-next-line t3code/require-registered-list-scroll -- ThreadFeedScrollView is passed through the iOS-only spread below; the prop rejects undefined. */}
<KeyboardAwareLegendList
ref={attachList}
Expand Down
Loading
Loading