# AGENTS.md

learnX is a React Native app (iOS, iPadOS, Mac Catalyst, Android) for Tsinghua University's Web Learning, built on [`@robertying/thu-learn-lib`](https://github.com/robertying/thu-learn-lib). This file holds what applies everywhere. Folders with more to know have their own `AGENTS.md`, and the workflows are skills:

| Where                                 | What                                                                                                                                                              |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CONTRIBUTING.md`                     | Setup from a fresh clone for outside contributors: tools, iOS signing with your own team, Android SDK, mock login, checks                                         |
| `src/navigation/AGENTS.md`            | Navigators, split views, headers, startup hooks, taps from outside the app                                                                                        |
| `src/screens/AGENTS.md`               | Today, first launch (Welcome, Setup, What's New), opening items from lists, detail screens                                                                        |
| `src/components/AGENTS.md`            | The component layer (text, icons, forms, cards, native controls) and the design rules: platform colors and icons, deadlines and status colors, permission prompts |
| `src/assets/translations/AGENTS.md`   | How user-visible text is written in English and Chinese                                                                                                           |
| `src/data/AGENTS.md`                  | Stores, TanStack Query, server actions and favorites, timetable, background sync, login and account data, mock login and mock data                                |
| `src/services/AGENTS.md`              | What learnX keeps in step outside the app (widgets, reminders, Spotlight, calendar, courseX) and downloaded files                                                 |
| `src/widgets/AGENTS.md`               | Home screen widgets (`expo-widgets`)                                                                                                                              |
| `modules/AGENTS.md`                   | Local Expo modules: native tests, Spotlight and App Intents, crash reporting, sharing files to learnX, the Android APK updater and build flavors                  |
| `patches/README.md`                   | Patched dependencies: what each patch fixes and how to change one (`pnpm patch`)                                                                                  |
| `.maestro/AGENTS.md`                  | End-to-end flows                                                                                                                                                  |
| `.claude/skills/release`              | Version bumps, release builds and uploads (fastlane)                                                                                                              |
| `.claude/skills/release-notes`        | Release notes for the stores and GitHub                                                                                                                           |
| `.claude/skills/upgrade-dependencies` | Upgrading every declared dependency (npm, patches, pods, gems, Gradle, Node, Actions) and verifying the app                                                       |

## Commands

- `pnpm start` runs Metro; `pnpm ios` / `pnpm android` build and launch the app.
- `cd ios && bundle exec pod install` installs the pods with the CocoaPods version locked in `Gemfile.lock` (run `bundle install` once first); run it after `ios/Podfile`, a native package or a patch changes. `pnpm pod` also runs `pod update`, which moves pods to newer versions: use it only when upgrading (the upgrade-dependencies skill). Use the Ruby in `.ruby-version` with a gem folder you can write to, such as Homebrew's (`brew install ruby`, with `$(brew --prefix ruby)/bin` first on `PATH`); Bundler installs the gems there.
- The Xcode targets' folders (`ios/learnX`, `ios/ShareExtension`, `ios/ExpoWidgetsTarget`, `ios/MacPreview`, `ios/learnXTests`, `ios/learnXUITests`) are synchronized folders: a file added there joins its target with no project change. Each target's `Info.plist` (and the widgets' `ExpoWidgetsLayoutRegistry.config.json`) is left out of its resources in the project's exception sets. The share extension also compiles `modules/share/ios/SharedFileInbox.swift`, and the Mac's Quick Look plugin (`MacPreview`, an AppKit bundle, see `modules/AGENTS.md`) `modules/quicklook/ios/MacPreviewHosting.swift`, each listed on its own.
- `pnpm bump major|minor|patch` (or `pnpm bump x.y.z`) sets the app version in `package.json`, the Xcode project and Gradle and bumps the build number; `pnpm bump build` (or `pnpm bump` alone) is a rebuild (build number + 1). See the release skill.
- Run `pnpm format` (Oxfmt) after changing files; `pnpm check` (typecheck, lint, format check, the over-the-air runtime version check, Jest with coverage, ShellCheck: what CI's JS checks run; CI's Release bundles runs `scripts/check-release-bundle.sh`) must pass before committing. Oxlint's config is in `.oxlintrc.json`. Lint is type-aware (`oxlint-tsgolint`): mark an intentionally unawaited promise with `void`.
- User-visible text goes in `src/assets/translations` (`en.ts` and `zh.ts`; wording rules in its `AGENTS.md`), read with `t('key', { param })` from `helpers/i18n`; `{param}` placeholders are filled in. Date formats are translations too, written out with `formatDate` (and times with `formatTime`, `timeRange`, `relativeTime`) from the same file. The `learnx/no-han-outside-translations` lint rule (`lint/plugin.mjs`) rejects Chinese text elsewhere in `src`; disable it per line only for text that must not be translated, with the reason.
- Debug builds load JS from Metro; only native changes need a rebuild.
- `scripts/test-ios.sh <simulator udid>` runs the native iOS tests (Swift Testing) and prints the line coverage of the app's and the modules' Swift; see `modules/AGENTS.md`.
- `android/local.properties` (git-ignored, see `android/local.properties.example`) holds the Android release signing values; debug builds don't need it.
- `.env` (git-ignored, see `.env.example`) is inlined at build time into `helpers/env.ts` by `babel/inline-env.js`, which only passes listed keys (the mock login); the live test login (`LIVE_*`) stays in `.env` for `scripts/e2e.sh`, which passes it as launch arguments. Add a key there before reading it in the app. The app can be used without a Tsinghua account through the mock login (`src/data/AGENTS.md`).

## File names

- In `src` and `jest`, a file is named after what it exports: PascalCase for a component, screen or navigator (`CourseCard.tsx`) and for a default-exported constant object (`constants/SplitSizes.ts`); camelCase for hooks (`useClock.ts`), helpers, data, services and files with several exports (`navigation/options.tsx`). Folders are lowercase. Tests are `<module>.test.ts(x)` in the folder's `__tests__` (`<module>.<case>.test.ts` for a case that needs a fresh module, like `useLinkTaps.noLink.test.ts`); one table of cases over sibling screens is named for the group (`ContentLists.test.tsx` for Notices, Assignments and Files).
- Platform variants use React Native's platform extensions: `Name.tsx` for iOS and Mac, `Name.android.tsx` for Android, and `Name.shared.ts` for what both use. Never put the platform in the name itself (`NameAndroid.tsx`).
- Scripts, Maestro flows, mock files and patches are kebab-case. Swift and Kotlin files are PascalCase.
- Names set by something else stay as they are: Android resources and the icons in `src/assets/icons` are snake_case, `ios/ExpoWidgetsTarget/index.swift` matches what the expo-widgets config plugin generates, and `docs/PRIVACY_POLICY_*.md` are linked from the store listings.

## React Compiler

- `babel-plugin-react-compiler` (in `babel.config.js`) memoizes every component and hook under `src/`, so don't add `useMemo`, `useCallback` or `React.memo` for performance.
- Don't make an effect depend on a function. A function that an effect only calls goes in `useEffectEvent`, and the effect lists the data it reacts to (e.g. `refresh` in `Notices`: `useEffect(() => refresh(), [courseIds, loggedIn])`). The compiler's memoization is an optimization, not a guarantee, so an effect shouldn't rerun just because a function fell out of compilation. `react-hooks/exhaustive-deps` flags the direct cases.
- `useCallback` / `useMemo` are still right where a value has to keep its identity and can't be an effect event: handlers handed to `navigation.setOptions` from an effect, functions and values in a context provider (the split views), and hook outputs that callers use as effect deps (`useFilteredData`).
- The compiler silently skips a function it can't handle and leaves it unmemoized. In 1.0 that includes `try` blocks with `finally`, `throw`, or conditional / logical / optional-chaining expressions (`?:`, `&&`, `||`, `??`, `?.`): compute values before the `try` and keep only the awaited calls inside it. Constants named `use…` are taken for hooks, so don't use that prefix for non-hooks.

## Over-the-air updates

- `expo-updates` replaces the JS bundle without a store release, from an update server that speaks the [Expo Updates protocol](https://docs.expo.dev/technical-specs/expo-updates-1/) (channel `production`). An update is built with `expo export`. Release builds bundle with `expo export:embed` (the Xcode bundle phase, `react {}` in `android/app/build.gradle`) and Metro uses Expo's config, so a store build's bundle and an update are made the same way.
- `app.json` holds the update URL, the request headers (channel `production` and `expo-app-id`, the Expo project the update server serves) and the runtime version, and `certs/ota-certificate.pem` the code-signing certificate (`keyid` `main`, `rsa-v1_5-sha256`; the private key is never in the repo). Builds write them in: `scripts/ota-config-ios.sh` (the "Configure updates" phase) into the app's copy of `ios/learnX/Expo.plist`, `android/app/build.gradle` into resources the manifest's `expo.modules.updates.*` meta-data reads. The release build lanes refuse the placeholder URL. `scripts/__tests__/otaConfig.test.ts` keeps the two platforms in step.
- A build takes only updates published for its exact runtime version, whatever its build number. The runtime version is the app version of the first release with the current native code (`19.0.0`): a release that changes only JS keeps it, so one update reaches every version since. Set it to the new app version in any release that changes native code: a package with native code or its version, `modules/`, Swift or Kotlin in `ios/` or `android/`, a patch to native code, Podfile or Gradle settings, Info.plist, entitlements, String Catalogs, icons, the widgets (their extension has its own bundle), a persisted store's version (`src/data/storeVersions.json`, see `src/data/AGENTS.md`). JS that calls a native API an older binary lacks also needs a store release. CI's "Runtime version" step (`scripts/check-ota-runtime.mjs`) enforces this: `ota-fingerprint.json` holds each platform's native fingerprint (`npx expo-updates fingerprint:generate`, with what counts in `fingerprint.config.js`) at the current runtime version, and the step fails when native code changes while the runtime version is one that shipped (a `v<version>` tag exists), when it changes before then without the record following, or when the runtime version changes without native code; it prints the values to record (CI's, from a clean checkout, since a local one can differ). So the first native change after a release sets the runtime version to the coming release's version, and later ones in that cycle only update the record.
- An update ships the JS of a commit whose native fingerprint matches the runtime version (above); anything else needs a store release.
- The native side checks on every cold launch without waiting and downloads in the background; the update starts at the next launch. Coming back after an hour in the background checks again, or starts an update already downloaded (as if the system had ended the app): `updateOnReturn` in `services/ota`, which `hooks/useReLogin` runs first when the app comes back, so a reload never cuts off a login or fetches it started. Debug builds load from Metro and never use updates. Settings › About adds the running update's id to the version, and crash reports carry it as `js_bundle` (or `embedded`), which says which source map decodes them.
- E2E builds (`TEST_LOGIN=1`, `-PciRelease`) never ask the real server: they get runtime version `e2e`, `http://localhost:8199/manifest` and a test certificate (`scripts/ota-e2e-cert.sh`, in `build/ota-e2e/`). `scripts/e2e-ota.sh ios|android` starts `scripts/ota-e2e-server.mjs` (the protocol, signed, with modes switched over HTTP) and runs `.maestro/ota/update-and-rollback.yaml`: an update downloads and runs, a badly signed one is refused, a rollback brings back the built-in bundle. CI's Android E2E job runs it after the flows.

## Unit tests (Jest)

- `src/helpers` holds logic with no side effects beyond thin platform reads (i18n, icons, what's new), tested in `src/helpers/__tests__` without mocks of the server or the system. The browser scripts the web views run (`helpers/preval/*.js`) are tested there too, by their own names (`darkMode.test.ts`), since anything inside `helpers/preval` goes into Metro's cache key; the ones loaded as modules count toward coverage (`collectCoverageFrom` in `jest.config.js`). Code that talks to the system's stores and outputs or to a server outside `data/source` (background sync, notifications, reminders, Spotlight and App Intents, widgets' feed in `services/surfaces`, the calendar in `services/calendar`, downloaded files in `services/files`, crash reporting, courseX, submissions, store report, launch options, list actions) lives in `src/services`, tested in `src/services/**/__tests__`. The calendar's pure builders are in `helpers/calendar` (event details, ICS). Hooks are tested in `src/hooks/__tests__` with `renderHook` from `@testing-library/react-native` (v14: `renderHook`, `rerender` and `act` are async, so await them).
- Mock native modules and the data layer per test file (`jest.mock('services/files/downloads', …)`, `components/Toast`, pickers, `data/source`); use the real Zustand stores (`setSetting`, `setPendingAssignmentData`, `resetUserData`) instead of mocking them. Tests of `services/files` opt into an in-memory file system (`jest/mocks/memoryFileSystem.ts`) that they seed and read back; `helpers/html` loads with `data/source` mocked. Global mocks are listed in `jest/setup.ts`, each stand-in in `jest/mocks/`. After each test Jest clears every mock's calls (`clearMocks`) and restores spies and replaced properties (`restoreMocks`), and `jest/setupAfterEnv.ts` goes back to real timers, English (`en-US`) and a 24-hour clock, so switch platforms with `jest.replaceProperty(Platform, 'OS', 'android')`, timers with `jest.useFakeTimers()` and the language with `mockLocale.current` (`test-utils/locale`), and don't restore by hand.
- A test fails on any `console.error` or `console.warn` it doesn't expect (`jest/setupAfterEnv.ts`), Testing Library's own warnings included, such as an act() warning or an event fired where it doesn't bubble (lay a view out with `fireLayout` from `test-utils/layout`, which finds the view whose `onLayout` measures an element): change a store that a rendered component reads (`useAuthStore.setState`, `setCurrentSemester`, `setSetting`) inside `await act(...)`, in `afterEach` too. A test that expects a log spies on it (`jest.spyOn(console, 'warn').mockImplementation(() => {})`). TanStack Query's notifications already run in act().
- Test hooks that hold real logic (state, ordering, error paths), not thin wrappers around one call.
- Components and screens are tested in `src/components/__tests__` and `src/screens/__tests__` with `render` and `screen` (also async in v14), one file per component or screen named after it (`CardRow.test.tsx`, and `android/CardRow.test.tsx` for its Android file); shared test data goes in `jest/fixtures/`. Tests import from `jest/` as `test-utils/…` (`test-utils/fixtures/cards`, `test-utils/mocks/navigator`), an alias in `babel.config.js` and `tsconfig.json`, never by a relative path. Query what the user sees (text, role, `testID`); press through `userEvent` (`userEvent.setup({ advanceTimers: jest.advanceTimersByTime })` under fake timers), since `fireEvent.press` can bubble to the test element's own `onPress` prop. Screens get their props from `screenProps({ navigation, route: { params } })` (`test-utils/screenProps`), with `navigation` a plain object of the `jest.fn()`s the screen calls, and mock their data hooks (`data/content`).
- `pnpm test` runs three Jest projects (`jest.config.js`): `ios` loads each split component's iOS file, `tooling` runs the tests of the repo's own tooling in `scripts/__tests__` (the E2E env values and the flows' learnx:// links, the Maestro flow references, the lint plugin and config, the coverage tables, and native files kept in step such as the Chinese String Catalogs) with Node's types (`scripts/tsconfig.json`, which `pnpm typecheck` also checks, with the config files, `babel/`, `lint/` and the scripts as checked JS), and `android` runs the tests in `__tests__/android/` with the `.android.tsx` files, `Platform.OS` 'android' and Compose stand-ins (`jest/mocks/expoCompose.tsx`, `jest/mocks/expoComposeModifiers.ts`): a row made tappable by `clickable`, `toggleable` or `selectable` is a pressable with that role and state, and a dropdown shows its items only while expanded. Test an Android variant there.
- CI runs `pnpm test --coverage`, which fails when coverage drops below `coverageThreshold` in `jest.config.js` (kept just under the current numbers). Cover new code with tests, and raise the thresholds when coverage grows.
- `jest/setup.ts` replaces native views globally: `@expo/ui` `Icon` renders a view with testID `icon-<name>`, and expo-symbols' `SymbolView` a view with the testID `SystemIcon` is given; `@expo/ui` `Button` and `Switch` are a pressable and an accessible `switch` (flip it with `fireEvent(switch, 'valueChange', value)`); `ReanimatedSwipeable` renders its children and both sides' actions, puts `enabled` and its swipe callbacks on its props for tests to call, and gives its ref `mockSwipeableMethods` (`jest/mocks/swipeable.tsx`); every `@expo/ui/swift-ui/modifiers` export is a `jest.fn`. Reanimated runs its web build through its Jest resolver; haptics, device info, cookies, the share extension and safe area insets are mocked. dayjs has `relativeTime` and the `zh-cn` locale loaded, as `helpers/i18n` sets them up.

## Pull requests

- One change per pull request, squash-merged once the required checks (`CI / JS checks`, `CI / Release bundles`, `CI / Android`) pass. The title and description say what the change does compared with `main` and why, for a reader who hasn't seen how it came about: no history of earlier attempts or review rounds. The squash commit message follows the same rule.
