oficina / docs Public

Hotfix: the iOS editor loops opening a document with a list, image or rule (TestFlight 0.1.10 (12)) open

On branch fix/ios-render-loop

Hotfix for the iPhone editor's update loop, found by S0 (#161, finding 1). On iPhone, opening a document that holds a list (or an image, or a rule) never finished: 100% CPU and memory that kept growing. It also looped after a peer's insert and after typing mid-document. This is in TestFlight 0.1.10 (12). Two commits on 9dbcace: the tests (b89540e), then the fix (2484349). Not merged, released or deployed.

Root cause (confirmed)

The cause is as #161 reported, plus a second reason the renders differ.

  • DocsWorkspace.editor renders the projection again on every body pass, and passes it to NativeDocumentTextView. Its body reads model.selection through the toolbar and the tools.
  • applyRender re-applies the text when the generation hasn't changed but rendered.isEqual(to: content) is false. That check could never be true for a real document, for two reasons: 1. Every render makes new NSTextList and NSTextAttachment objects, and those are only equal to themselves. That covers every list, image and rule. 2. The render JSON-encodes dictionaries into four attributes (docsClipboardContainers, docsBlockAttributes, docsMarks, docsImageAttributes) without sorted keys. Their bytes differ between renders. This is new; it showed on list items even with fix 1 in place.
  • On iOS, re-applying means text.attributedText = …. That moves the caret to the end and back. Unlike the Mac's, iOS textViewDidChangeSelection wrote parent.selection while applying ("Modifying state during view update", in the log). That write invalidates the body, which renders again, which is again "different". The loop is synchronous: the main thread never comes back.

Fix

The fix is in NativeDocumentTextView.swift, DocumentRenderReconciliation.swift and NativeTextProjection.swift.

  • (a) iOS textViewDidChangeSelection does nothing while a render is being applied (guard !applying), as the Mac's has done since c1b9ac9. applyRender already puts the caret where the model has it.
  • (b) applyRender (both platforms) uses a new DocumentRenderReconciliation.isEquivalent. It compares lists by marker format and start number, attachments by bounds, image size, contents and file type, and everything else exactly. Image size and not identity, because a rule's image is drawn fresh on every render. A loading image still counts as a change (placeholder 24×24 → real bounds), and so does a renumbered list or any other attribute; DocumentRenderEquivalenceTests pins all of these.
  • (b′) NativeTextProjection encodes with .sortedKeys.
  • DocumentRenderReconciliation.apply keeps its exact comparison on purpose. A list's paragraphs share one NSTextList, which is what numbers them as one list, so it must not keep old lists beside new ones.

Is each one needed? I ran the three iOS tests with only one half of the fix applied:

  • (b) alone stops the loop: all three pass. The comparison is what feeds the loop.
  • (a) alone also stops the loop, but on iOS every caret move still assigns the whole attributedText again (the caret test fails with 1 redraw). That means a full re-layout of the document on each tap.

I kept both. (b) removes the false "changed". (a) means a genuine same-generation change, such as an image arriving, can't write state during the update that applies it.

Nothing is mutated in a SwiftUI init or body (the 0.1.7/0.1.8 rule).

Tests: failing before, passing after

  • EditorRenderLoopTests (new, Tests/DocsKitTests). It runs DocsWorkspace(client:transport:signOut:documentID:) in a real window: UIWindow + UIHostingController on iOS, NSWindow + NSHostingView on the Mac. The document holds bullet and ordered lists, a data-URL image and a rule, on an in-memory server: the production replica, GET/POST/stream as handlers.go. The test counts NSTextStorage.didProcessEditingNotification on the editor's storage. It requires the editor to go 500 ms without a redraw within 5 s, after a bounded number of redraws. There are three tests: - open, then move the caret: 0 redraws allowed for the caret move; - a peer's insert through the stream; - typing mid-document through the delegate path, as the keyboard does.
  • The same file builds for iOS as a new DocsPhoneTests target (ios/project.yml). native/scripts/test-iphone.sh runs it in the iOS 27.0 simulator (iPhone 18 Pro). It is not in CI, because the runner has no simulator; BUILDING.md says so. - Before (main's sources): each of the three tests hung. The main thread spun, the log showed "Modifying state during view update", and xctest reached 4 GB before I killed it, every time. Because the loop holds the main thread, no assertion can fire. The script therefore sets a 60 s test time allowance, so a looping build fails instead of eating memory. - After: 3/3 pass (about 5 s).
  • On the Mac (swift test), main has no loop, but moving the caret redraws the list document once (assertion red). With the fix: 3/3 green.
  • DocumentRenderEquivalenceTests (4 tests, both platforms): - two renders are not isEqual but are equivalent; - an image that loads, a different list number and any other attribute are each a change.

The Mac can't loop the same way

  • Its textViewDidChangeSelection has always returned while applying.
  • It reconciles in place (DocumentRenderReconciliation.apply) and doesn't reassign the whole text.

So the Mac's false "changed" cost one redundant attribute pass per update, not a loop. EditorRenderLoopTests now holds the Mac to zero redraws on a caret move as well.

Gates

  • native/scripts/check-native.sh: passed. swift test ran 178 tests: 0 failures, 4 skipped (the same skips as main). WorkspaceInitTests and SignedInLaunchTests are green.
  • iOS simulator builds (iOS 27.0, iPhone 18 Pro): DocsPhone, DocsReviewPhone and DocsPhoneTests all build. test-iphone.sh gives 3/3.
  • In the simulator app, built from this branch. This used the review app (DocsReviewPhone, the production DocsWorkspace) against the Go review fixture (TestNativeReviewFixture), seeded with the list, image and rule document plus #161's Russian lists. To get there I made two temporary local edits, neither committed: the fixture read that update, and the review app opened the fixture's sqid straight away. - This branch: the document opens and is drawn. CPU is 98% → 0.0% from 6 s on, and RSS stays flat at 355–358 MB for 30 s. - Same app, main's sources: CPU stays at about 100% and RSS climbs from 345 to 479 MB in 12 s.
  • Hub CI: queued at push. Result in a reply below.

Not here (separate work, as asked)

List markers, Arabic alignment and the iPhone first-page margin (#161 findings 2–4). S0's snapshot harness still pins the iPhone selection. Once this lands, that pin can go when S0 is rebased.

Hub CI at 2484349: passed. amadan ci status oficina/docs -branch fix/ios-render-loop exits 0.

Build output in the worktree is cleaned. The push token docs-ios-loop is revoked. Ready for review: the branch should get the highest-capability-model read before it merges. Not merged, released or deployed.

Review of fix/ios-render-loop at 2484349 — Claude Fable (model claude-fable-5-2), review-only session.

Verdict: APPROVE

Nothing blocks the merge. The findings below are follow-ups; 1 and 2 are worth doing soon because S1a and the list-marker fix (#161 finding 2) lean on them.

What I ran

In my own detached worktree (removed afterwards, build output included), on the iOS 27.0 simulator (iPhone 18 Pro Max, so the booted iPhone 18 Pro was left alone), with the CRDT framework copied from a worktree whose native/crdt and native/host trees are identical:

  • At 2484349: test-iphone.sh passes 3/3. The four DocumentRenderEquivalenceTests also pass when built for iOS.
  • With NativeDocumentTextView.swift put back to 9dbcace: testOpeningAListImageAndRuleSettles fails as described: "Modifying state during view update" in the log, "exceeded execution time allowance of 1 minute", ** TEST FAILED **, exit 65.
  • My own probes (not committed anywhere), results in the findings below.

I did not re-run the Mac suite or check-native.sh; for the Mac I relied on hub CI and on reading the code.

Findings

  1. isEquivalent has no false "equal" that I could reach, but two of the cases rest on an attribute nothing pins. DocumentRenderReconciliation.swift:65 (sameParagraphStyle). Severity: low today, medium for S1a. - Probed on iOS, each correctly "not equivalent": ordered ↔ bullet; one ordered list split into two; a list id change alone; link href (http and non-http); a mark added; align; indent; an unknown block attribute; image alt; a src change between two same-size pictures; placeholder → a loaded 24 × 24 image; placeholder → an image of the symbol's own size; nested vs flat list. - Lists compare only by marker format and start number. A list split in two (same markers, both starting at 1, numbering visibly changes from "2." to "1.") is caught only because docsClipboardContainers carries the container ids. - If S1a renames, drops or stops applying that attribute to every character, a regrouping becomes a silent no-draw. - Suggested: add the split-list, ordered ↔ bullet, href and alt cases to DocumentRenderEquivalenceTests, and a line in the doc comment saying grouping is detected through the containers attribute.
  1. The list comparison must grow with the list renderer. DocumentRenderReconciliation.swift:67. Severity: low now. - NSTextList.options, a subclass, or a per-level marker are not compared. The render sets none of them today. - The list-marker fix and S1a will likely add one. Whoever does should extend sameParagraphStyle in the same change.
  1. One designed false "equal": same src, same size, different pixels. DocumentRenderReconciliation.swift:77 (sameAttachment). Severity: low, not reachable today. - DocsImageStore never replaces an image once loaded for a src, so the editor can't produce this. - It becomes reachable if the store ever refetches or retries a src. - Related, on iOS only: the rule's image is a bitmap drawn with UIColor.separator at render time, so a light/dark switch on its own no longer redraws it until the next generation. The Mac's rule draws through a handler and is unaffected.
  1. Sorted keys: safe. NativeTextProjection.swift:21. - Every reader of the four attributes decodes with JSONDecoder (DocsRichClipboard, TextEditMapping, DocumentCommands, DocumentInlineCode, DocumentInputRules), or only checks that the value is Data. - The bytes are never stored, and the clipboard writer encodes its own values. - Nit: DocumentNativeInputRules.swift:84 still writes .docsBlockAttributes into storage with a plain JSONEncoder(). It is harmless, since apply just rewrites that range on the next render, but the shared encoder would be tidier.
  1. iOS early return: no user selection can be lost. NativeDocumentTextView.swift:280. - applying is true only inside the synchronous applyRender, so no touch is delivered while it is set. The only callbacks it swallows are the ones the assignment itself causes. - The model's selection is already the replica's resolved one (DocsModel.publishCurrent), and DocumentCommands.validSelection guards a stale range. - Probe: an image held back by the server, a selection {116, 6} made mid-document, then the image released. The selection survived, the editor settled, and a later caret move drew nothing. - Side effect, same as the Mac: the "caret after the final newline steps back one" correction no longer runs during an apply. I found no path that puts the model's selection there. - (a) is not pinned by any test. With (b) alone all three tests pass, as the description says, and my image-arrival probe would pass without (a) too: it would write state during the update once and then stop. A test that fails on the "Modifying state during view update" log, or on a binding write during applyRender, would pin it.
  1. Mac caret move: no regression found. NativeDocumentTextView.swift:90. - A document with lists now behaves as a document without them always has: same generation and equivalent means skip. - Real changes still go through apply, which keeps its exact comparison, so list paragraphs still share one NSTextList. - What is lost is an accidental re-apply of list and attachment ranges on every update. I found nothing that relied on it; optimistic storage edits are healed by the next generation.
  1. Cost. DocumentRenderReconciliation.swift:38, DocsWorkspace.swift:238. Severity: low. - isEquivalent walks the whole document, copying a dictionary per run, on every body pass. That is on top of the full renders the body already does (lines 238 and 270 on iOS; 300 on the Mac with the inspector open). - Fine for a hotfix. S1a should replace the whole-document comparison with per-block identity, not build on it.
  1. Test quality. EditorRenderLoopTests.swift. Severity: low. - Line 113: the harness counts edits on the storage it found at open. If .id(model.editorIdentity) ever rebuilds the editor mid-test, the counter goes quiet and assertSettles passes falsely. Asserting at the end that textView is still the same object would close that. - Line 66: allowing: 3 * " typed".count is 18 redraws, which leaves room for one spurious full redraw per character. - Line 178: iOS typing edits the storage by hand, so UIKit's own selection callbacks during real keyboard input are not exercised. That is acceptable, but it is an approximation. - There is no test for a genuine same-generation change (an image arriving) keeping a mid-document selection. My probe is about 25 lines on top of LoopServer and passes.
  1. CI gap for the iOS half. native/scripts/test-iphone.sh, native/BUILDING.md:31. Severity: medium, process. - The bug was iOS-only, and the only test that fails on it is the one CI cannot run. Hub CI being green says nothing about NativeDocumentTextView's iOS coordinator. - "Run it before changing the text view" is a note that will be missed. - Suggested: make test-iphone.sh a required step of the TestFlight release procedure, with its output pasted into the release discussion, as S0's BUILDING.md already asks for snapshots.sh compare all. Run it on the release commit of this hotfix. - The script itself works and fails correctly on a loop.
  1. S0 and S1a. - S0 (feat/native-editor-snapshots): after a rebase, the .constant(model.selection) pin at EditorSnapshots.swift:351-355 can go. No drawing attribute changed here, so I expect no new baselines; snapshots.sh compare all after the rebase is the check. - Both branches edit native/BUILDING.md, so expect a small text conflict. - S1a: see 1, 2 and 7.

Left behind

The iPhone 18 Pro Max simulator device now holds 1.9 GB of data. I could not tell whether my boot created it, so I left it; it is shut down. Free space on the data volume is 17 GB.

Landed on main (squash) after Fable's APPROVE and green hub CI at 2484349; follow-ups are tasks. Next: Docs native 0.1.11 (13) to TestFlight + Mac, with test-iphone.sh run on the release commit.

Docs 0.1.11 (13) released to Mac (Sparkle) and TestFlight from main 198c1da (2026-11-22, release session). It is native only, so there was no server deploy.

Tests on the release commit (finding 9).

  • native/scripts/test-iphone.sh ran in the iPhone 18 Pro simulator on iOS 27.0 (24A434), after build-crdt.sh. TEST SUCCEEDED, 3 tests, 0 failures: - EditorRenderLoopTests.testAPeersInsertSettles passed (1.97 s). - testOpeningAListImageAndRuleSettles passed (1.26 s). - testTypingInTheMiddleSettles passed (1.38 s).
  • swift test --package-path native/apple ran 178 tests: 4 skipped, 0 failures.

Mac 0.1.11 (13), Sparkle. Notarised (id 623ad9ab-cbae-4f4c-aef2-67d8d8774b07).

  • On the unzipped release zip: spctl says Notarized Developer ID, Team Tito. Stapler validates it.
  • The entitlements are unchanged from 12: keychain groups .docs then .id, App Group 9U4A84C4WK.works.oficina, webcredentials:id.oficina.works. embedded.provisionprofile is there.
  • DocsMac --oficina-id-launch-check reported every line ok and exited 0.
  • Published to native-releases as release docs-13, feed commit 0012a84048e3a5bdf0bc3b3d5343ca4a99fef422. The public appcast lists 0.1.11 (13) first.
  • zip sha256 7c41ef1886d806044dec43ede3831105b21331ffa426f148e8001c51a54fa2fd (14892416 bytes). An anonymous download gives the same hash and length.

iPhone 0.1.11 (13), TestFlight.

  • Archived with Apple Distribution and the "Oficina docs iOS App Store 2026-11-14" profile.
  • The archive holds only DocsPhone.app, with no PlugIns and no xctest, so DocsPhoneTests is not in it.
  • Info.plist has 0.1.11 / 13 and ITSAppUsesNonExemptEncryption=false.
  • Uploaded with delivery 54f87751-3bd9-4bec-91ee-6cc83a1bb799. It was VALID on the first poll, with usesNonExemptEncryption=false already set.
  • internalBuildState is INBETATESTING. The "Oficina internal" group has access to all builds.

Next: Paul tries a list, an image and a rule on iPhone build 13.