⚡Megatron LLM Hub
←返回搜索
Website

Lody iOS 把聊天流、输入框与 Live Activity 从 React Native 重写为 UIKit,约 6.1 万行 Swift。

移动端ios重构
Lody iOS started out on Expo + React Native. By October, the chat timeline, composer, Live Activity, and Share Extension had all been rewritten in UIKit—roughly 61,000 lines of Swift alongside 37,000 lines of TypeScript. What remained of React Native was mostly routing and screen-level glue: navigation was split half in Expo Router and half in native code, and every build still ran through expo prebuild , Metro, and CocoaPods. Repository · innei-dev 527 lody-ios Independent iOS client for Lody — native chat, sessions, and coding-agent collaboration on iPhone Swift On the night of October 24, I decided to remove React Native entirely and replace the remaining screens with UIKit one by one. On the morning of October 28, #96 merged into main , deleting the RN runtime after roughly three and a half days (87 hours) across 482 files (+25,700 / −37,500 lines). I then spent the next three days reorganizing the directory structure around explicit dependency layers. Whiteboard Finishing the cutover in 87 hours was only possible because the real strangler-fig work had started six weeks earlier. Between early September and mid-October, diff rendering, the chat timeline, and the rich-text composer were extracted into standalone packages, followed by cloud-runtime on October 11. By the time the migration started on October 24, the app was already layered like this: Whiteboard In other words, React Native had already been hollowed out into a thin outer shell: the heavy UI primitives were standalone packages, and the data runtime had lived inside a Swift-owned offscreen WKWebView from day one. The migration came down to three questions: Where should the cross-platform boundary live once coding agents make native UI cheap? How do you invert the host of a 100k-line app without freezing trunk? And when offline verification holds pixel diffs to 0.00026, which four regressions still slip through the cracks? 1. The Shifting Premise: Moving the Shared Boundary from UI to Data We originally chose React Native with a future Android client in mind. The bet was to keep both the data layer and the UI abstraction in RN: React components would describe screen layouts, while iOS and Android would merely supply the underlying native views. When it came time to build Android, we would only need view implementations—neither the data layer nor screen structures would have to be rewritten. Whiteboard The left side shows that original bet; the right side shows where we landed. The shared cross-platform boundary moved down from UI to a headless data layer: cloud-runtime runs inside an offscreen WebView, iOS and a future Android client implement the same versioned contract, and each platform writes its UI natively. Two shifts broke the original equilibrium. First, coding agents collapsed the marginal cost of native UI . Writing a separate UI per platform used to be the exact expense RN was meant to save. In this migration, the remaining screens were rewritten in batches alongside coding agents in three and a half days. Once the one-time cost of writing native screens drops that low, paying an ongoing abstraction tax to avoid it no longer pencils out. Second, the three-layer translation tax in navigation . Navigation bars, toolbars, and sheets ultimately end up as UIKit, but in RN they had to pass through three layers of translation to get there: Whiteboard On the left, every layer maintains its own state and assumptions. As soon as iOS 26 glass styling, iPad split views, and iPhone Duo foldable layouts entered the picture, bugs clustered in the seams between layers (the gray annotations show a few issues hit while adapting for Duo). Our patch against react-native-screens started on September 10 and was revised 11 times before deletion. On the right, there is no middleman—each view controller owns its navigation items directly. Each individual glitch was patchable, but every fix added another layer of state translation between RN and UIKit. On October 17, I got wide-screen layouts working for iPad and iPhone Duo in RN, and the result still felt rough. A week later, I decided to stop patching and go all-in on native. 2. The Strangler-Fig Inversion: Hollow Out First, Flip the Host Second To swap out the host without halting feature work on main , we couldn't start by rewriting screens. We had to unwind a reverse dependency chain: six weeks of preparatory extraction to hollow out the shell, followed by three sequential locks once the cutover began. Six Weeks of Prep: Stripping Out Heavy Views and Data Until Only Routing and Context Remained The timeline below lays out the extractions between September 6 and October 24 across two tracks—the data layer and UI primitives: The three heaviest UI subsystems went first: diff rendering ( dom-webview ), the chat timeline (ChatKit), and the rich-text composer ( lexical-swift ). They were already written in Swift or self-contained DOM bundles that RN screens simply mounted. When we later replaced screens one by one, the new UIKit view controllers imported those packages directly without having to untangle view logic mid-flight. Repository · Innei 3 ChatKit UIKit chat primitives: streaming text reveal, attachment strip, glass surface. iOS 26, Swift 6. Swift The data layer was never inside RN to begin with. Swift owned an offscreen WKWebView where sync, local replicas, and retries ran; RN only ever received read-only projections for display. On October 11, that runtime and its protocol types were extracted into @lody/cloud-runtime . Earlier, on September 8, the cloud code had already been split by domain into auth , catalog , and send —the exact three boundaries that would become Swift's AuthSession , CatalogSession , and Outbox on October 25. By the night of October 24, all RN held besides routing was the state inside five root Context providers. Lock 1: Establish a Versioned Contract and Sink State into Swift Why didn't day one touch a single screen? Because replacing screens incrementally required UIKit to own navigation first, turning each remaining RN screen into an independently hosted root view. Once screens become separate root views, React Context on a single root component can no longer span across them—so global state had to leave RN first. And for Swift services and native screens to talk to the offscreen runtime without going through RN, Swift and the runtime needed a formal contract. Previously, Swift invoked the runtime by concatenating raw JS strings, which was tolerable when the RN host was the only caller. Now native screens needed to call the runtime directly—and a future Android host would need the exact same surface—so the very first commit on October 24 replaced string interpolation with a schema-driven contract: The Zod schema in cloud-runtime became the single source of truth. Types for every platform are generated from it, and the host and runtime only exchange envelopes carrying a schema version ( v ) and instance generation ( gen ). Version mismatches fail the handshake immediately, and messages from stale WebView generations are dropped on sight. Swapping the host—or adding a new platform—never touches the runtime. Over the next 23 hours, the five React Contexts on the RN root were consolidated into four single-owner Swift services. The left side shows the old RN root provider tree; the right side shows how both RN and UIKit screens read state afterward: Each slice of state has a single owner in Swift. Remaining RN screens and new UIKit screens read the same synchronous JSON snapshot and subscribe to the same change event. Splitting screens into separate root views no longer affected shared state—and as a security bonus, long-lived Better Auth credentials now stayed strictly in Swift and Keychain without ever entering the JS context. By the evening of October 25, once Outbox landed in Swift and CatalogProvider was deleted, the root Context tree was empty. Lock 2: Invert the Host so UIKit Wraps RN Screens With state out of the way, Expo Router still owned navigation. As long as RN owned navigation, native views could only live as child components inside RN screens—we could never replace a whole screen. The pivotal move was inverting the host relationship: UIKit took over the window and navigation chrome, demoting the remaining RN screens into leaf views hosted inside UIKit containers. The diagram below shows the three stages of the host; this step moved us from left to center: Whiteboard In that middle transitional state, each unmigrated RN screen became an isolated surface backed by a single shared RCTHost . The outer UIKit container didn't care whether a destination was rendered by an RN surface or a native view controller, unlocking true screen-by-screen replacement without blast radius across pages. (Earlier on iPad, I had tried reparenting a mounted RN view into a different superview, which silently broke touch press handling; giving each screen its own surface avoided that trap entirely.) The new UIKit shell went in behind a launch flag first. Compact iPhone navigation and regular-width iPad split navigation were wired up in turn; once both ran cleanly, Expo Router was deleted in the early hours of October 26—six hours from feature flag to router removal. Lock 3: Cut the Umbilical Cord—Remove the RN Runtime and Build Chain Once all remaining RN leaf screens were replaced with UIKit (covered in the next section), the app still booted through Expo's AppDelegate and every build still ran through expo prebuild and Metro. #96 severed that final layer—moving from the center of the host diagram to the far right: a native AppDelegate / SceneDelegate boots LodyApplication directly, giving lifecycle, deep links, push notifications, and the share inbox native owners. The build pipeline flipped with it: The ios/ directory is no longer wiped and regenerated by prebuild ; the Xcode project is generated deterministically from a committed project.yml via XcodeGen. React, Expo, Hermes, and the stack of react-native-screens patches were deleted together. Only the headless WebView runtime bundle continues to be built with pnpm —the one layer that never changed from start to finish. Pull Request · innei-dev/lody-ios # 96 refactor(ios): complete the native app migration and remove React Native merged + 25764 − 37457 Leeeon233 2 weeks ago 3. Deterministic Verification and Its Cracks: 0.00026 Pixel Diffs vs. 4 Escaped Regressions Between October 26 and October 28, rewriting every remaining screen in UIKit within 48 hours—without breaking main —would have been impossible with manual QA. What made the blitz safe was an offline verification harness; what makes it interesting in hindsight are the four bugs that still escaped it. Leaf-to-Trunk Replacement: Isolating Every Screen Behind a Single Service Seam Once the UIKit shell was in charge, every native screen was built around the exact same decoupled structure: A view controller's only I/O is a service closure. Production routes inject the live implementation (wired to DataRuntime , Catalog , and Outbox ); Debug scenes inject a scripted implementation returning fixed fixtures. Both paths run the exact same view controller. Before flipping any screen, we registered an offline Debug scene and a verify:ui behavioral test that deep-linked straight into it—no login, no cloud, and no local agent daemon required—running the identical assertion suite before and after the swap. With offline assertions in place, replacement proceeded mechanically from leaves to trunk. On October 26, all Settings sub-screens, Home, and Project screens moved first; that night, the complex Session screen was built in UIKit behind a Debug fixture. On October 27, the remaining screens were conquered in a stack of eight PRs ( #87 – #94 ): message editing, message details, tool details, permissions, PR view, and file browser, followed by flipping the production Session entry point to native and finishing Home and iPad navigation. On the morning of October 28, #86 and the entire PR stack merged together. Pull Request · innei-dev/lody-ios # 86 refactor: UIKit shell and native pages (RN removal phases 2–3) merged + 26846 − 18771 Innei 2 weeks ago When #96 deleted the RN runtime hours later, the offline UI suite ran directly against the pure native build. Across 20 screenshots of the new-session form compared pixel-by-pixel against the previous build, the maximum diff was 0.00026 . Where the Harness Cracked: How 4 Regressions Escaped a 0.00026 Pixel Gate Even with screenshot diffs pinned to the fourth decimal place and core flows working cleanly, four regressions still surfaced after cutover. Looking at them side by side is revealing—every single one lived on the seam between offline scripted scenes and the real runtime environment: Whiteboard The test entry point had no test of its own : The Debug screen dispatches every offline scene, yet had no test case covering itself. After converting to UIKit, it regressed into an ungrouped flat list missing its navigation bar. Build configuration skew (Debug vs. Release) : Debug scenes were only registered under Debug and UI Verify build configurations, and automated checks never ran against Release . Long-pressing the Settings button in TestFlight builds triggered an unregistered route and crashed immediately. Offline stubs bypassed the OS modal hierarchy : During Device Flow sign-in, SFSafariViewController presents over the welcome screen; after authorization completed, dismissing closed only Safari while leaving the welcome screen stuck underneath. Because the "open browser" step in the offline fixture was a no-op stub, the real system modal stack was never exercised. Static fixtures skipped async teardown races in the live runtime : Opening a session from a push notification caused the previous screen's delayed deinit to close the session the new screen had just opened. Offline scenes fed synchronous scripted data without a live DataRuntime , so that cross-controller lifecycle race never fired under test. 4. Post-Merge Convergence: Freeze Paths During Cutover, Layer by Dependency After Throughout the 87-hour sprint, I followed one strict rule: never move files while changing behavior . Keeping file paths frozen meant every commit was a pure implementation swap—easy to review and trivial to git bisect if something broke. The trade-off was that when #96 landed, all 557 Swift files were still sitting inside the legacy Expo module directory, mixing view controllers, data sessions, and platform glue. Only after behavior was locked down did I put on the refactoring hat for three days of structural layering, again doing one thing per step: Step 1: Move files without splitting code. With RN gone, apps/mobile and the Expo module path were vestigial. All Swift sources were moved wholesale into a single Swift package, LodyKit , while dependencies switched from CocoaPods to SPM. Step 2: Split along the import UIKit boundary. Auth, catalog, outbox, the data runtime host, session models, and copy were extracted into LodyData —a module that never imports UIKit and compiles and tests in isolation. Whenever the data layer needs a platform side effect (opening URLs, requesting background execution time, showing a toast, presenting an auth browser, or writing a Share Extension snapshot), it calls the LodyHost protocol, which the top-level App target implements and injects. Step 3: Flatten the project hierarchy. The repository root became the Xcode project root, eliminating the apps/ wrapper. Finally, the remaining UI code in LodyKit was folded back into the App target—the App was its only consumer, while views shared with the Share Extension moved into Shared/UIKit as direct source references. Keeping a separate UI package only added ceremony around access control, so the App target is now organized directly into Application , Navigation , ViewControllers , Views , Services , and Platform . The resulting dependency graph flows strictly in one direction—the lower a layer sits, the less it knows about UI: Whiteboard The repository root is the Xcode project root, generated from the committed project.yml ; the generated Lody.xcodeproj is never edited by hand. Takeaways for Anyone Planning a Similar Migration Looking back, the critical factor wasn't how fast UIKit views could be written—it was respecting a strict sequence of dependency locks where each step unlocked the physical precondition for the next: Start by deciding which layer actually deserves to be shared . React Native's cross-platform leverage lives in UI; once coding agents make platform-native UI cheap to write, it pays to push the shared boundary down into a headless data runtime behind a versioned contract. Extract heavy UI primitives first, sink shared state out of RN, and then invert the navigation host—once a native shell can host legacy RN screens as isolated leaves, every remaining screen can be replaced and verified independently. And when designing your verification harness, remember to test the test entry point itself, Release build flags, real OS modal stacks, and async teardown across live runtime sessions. I'm not a veteran iOS engineer, and this layering reflects how I reasoned through the problem rather than established orthodoxy. I'm still weighing trade-offs—like whether running a JS data runtime inside an offscreen WebView is worth it long-term, whether protocol injection via LodyHost is the cleanest way to handle platform side effects, or whether keeping App UI code in folders rather than SPM packages will hold up as the codebase grows. If you've been through a similar migration or would structure this differently, I'd love to hear your thoughts in the comments.