Skip to content
Source
Sign inSign up
pingdotgg/t3code

Fix native composer lag with revision-gated updates #3574

Mergedjuliusmarmingemerged 6 commits intomain fromrefs/pull/3574/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Summary

  • Gate native composer updates by event revision so stale controlled props do not overwrite newer text or selection state.
  • Merge composer text and selection updates into a single controlled document payload on iOS, and ignore out-of-order native events in the React wrapper.
  • Simplify thread and chat timeline presentation by removing separate disclosure anchor plumbing and moving work-log overflow handling into the work log component itself.
  • Add unit coverage for composer revision handling and update thread activity tests to match the new work-log presentation model.

Testing

  • Not run (PR content only).
  • Expected project checks from the repo workflow: vp check.
  • Expected typecheck gate from the repo workflow: vp run typecheck.
  • Added/updated tests in apps/mobile/src/native/composerEditorRevision.test.ts and apps/mobile/src/lib/threadActivity.test.ts.

Note

Medium Risk Touches native/React controlled-input sync for the main composer; regressions could show as caret jumps, lost keystrokes, or stale text, though logic is covered by new unit tests.

Overview Fixes native composer lag by replacing separate value, tokensJson, and selectionJson props with a single controlledDocumentJson payload and a monotonic eventCount revision on both sides.

The React wrapper builds that document using new composerEditorRevision helpers: it acknowledges native events in order, resolves which revision parent props belong to (including delayed or mismatched selection renders), detects native echo so React does not push selection back on the same keystroke, and prunes acknowledged snapshots. Native change/selection events now include value and eventCount; iOS ignores controlled updates below the current native revision and skips echo updates when serialized text diverges. Selection is cleared after apply on native to avoid repeat caret moves.

Adds composerEditorRevision.test.ts for revision/echo/prune behavior. pnpm-lock.yaml changes are lockfile peer-resolution churn only.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 1d0a86a7f0b7bbe5b778583db201fea4556d1ae2. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Fix native composer lag by replacing discrete props with revision-gated controlledDocumentJson

  • Replaces the three separate native props (value, tokensJson, selectionJson) with a single controlledDocumentJson prop that carries revision metadata (mostRecentEventCount, isNativeEcho).
  • Adds a revision-tracking system in T3ComposerEditor.ios.tsx and composerEditorRevision.ts to align React-controlled updates with the correct native event sequence, preventing selection jumps and feedback loops.
  • The native view in T3ComposerEditorView.swift now increments an nativeEventCount on each text change, ignores stale or echo updates, and applies value/tokens/selection atomically.
  • Native change and selection events now include eventCount (and value for selection events) so the React side can acknowledge and prune processed snapshots.
  • Behavioral Change: native view no longer accepts individual value/tokensJson/selectionJson props; all callers must send controlledDocumentJson.
Macroscope summarized 1d0a86a.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: 70fe5f70-319f-40b5-9485-afe786909b93

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `t3code/native-composer-lag`

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. @@ -350,5 +357,6 @@
      350357 }
      351358 }
      352359
      353- func setValue(_ value: String) {
      354- self.value = value
      360+ func setControlledDocumentJson(_ documentJson: String) {
      361+ guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson),
      362+ document.mostRecentEventCount >= nativeEventCount else {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium ios/T3ComposerEditorView.swift:362

      setControlledDocumentJson guards with document.mostRecentEventCount >= nativeEventCount, which accepts payloads where the two counts are equal. After a native edit emits event N (incrementing nativeEventCount to N), React updates mostRecentEventCount to N but may not have produced the updated value yet (e.g. async/debounced onChangeText). The stale document.value tagged with N passes the >= guard and applyControlledDocument overwrites the newer native text, silently dropping the user's edit. Consider tightening the gate so equal-count payloads are rejected, or otherwise ensuring the document value is only applied when React has confirmed it reflects the latest native event.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift around line 362:
      
      `setControlledDocumentJson` guards with `document.mostRecentEventCount >= nativeEventCount`, which accepts payloads where the two counts are equal. After a native edit emits event `N` (incrementing `nativeEventCount` to `N`), React updates `mostRecentEventCount` to `N` but may not have produced the updated `value` yet (e.g. async/debounced `onChangeText`). The stale `document.value` tagged with `N` passes the `>=` guard and `applyControlledDocument` overwrites the newer native text, silently dropping the user's edit. Consider tightening the gate so equal-count payloads are rejected, or otherwise ensuring the document value is only applied when React has confirmed it reflects the latest native event.
    4. Cursor Bugbot has reviewed your changes using high effort and found 4 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for all 4 issues found in the latest run.

      • ✅ Fixed: Selection advances revision without text
        • Removed the nativeEventCount increment from emitSelection() so selection-only events carry the current count without advancing it, preventing the counter from racing ahead of text events.
      • ✅ Fixed: Token updates ignore revision gate
        • Added a lastReceivedEventCount guard to setTokensJson that defers the forced token rebuild when React's acknowledged count trails nativeEventCount, preventing stale tokens from triggering a document rebuild.
      • ✅ Resolved by another fix: Native gate blocks parent edits
        • Fixed by Bug 4's change to use mostRecentEventCountRef.current in controlledDocumentJson, ensuring the serialized revision always reflects the latest acknowledged count so intentional React edits pass the native gate.
      • ✅ Fixed: Payload uses lagging revision state
        • Changed controlledDocumentJson to serialize mostRecentEventCountRef.current instead of the mostRecentEventCount state value, ensuring the payload always carries the authoritative ref revision even before state commits.

      Create PR

      Or push these changes by commenting:

      @cursor push 0a1175a602
      Preview (pingdotgg/t3code@0a1175a602)
      diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      @@ -288,6 +288,7 @@
         private var didAutoFocus = false
         private var isApplyingControlledValue = false
         private var nativeEventCount = 0
      +  private var lastReceivedEventCount = 0
         private var lastContentSize = CGSize.zero
         private var iconImages: [String: UIImage] = [:]
         private var pendingIconUris = Set<String>()
      @@ -358,10 +359,13 @@
         }
       
         func setControlledDocumentJson(_ documentJson: String) {
      -    guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson),
      -          document.mostRecentEventCount >= nativeEventCount else {
      +    guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson) else {
             return
           }
      +    lastReceivedEventCount = document.mostRecentEventCount
      +    guard document.mostRecentEventCount >= nativeEventCount else {
      +      return
      +    }
           value = document.value
           requestedSelection = document.selection
           applyControlledDocument(force: tokensNeedRebuild)
      @@ -378,6 +382,9 @@
           self.tokensJson = tokensJson
           tokens = decode([ComposerTokenPayload].self, from: tokensJson) ?? []
           tokensNeedRebuild = true
      +    guard lastReceivedEventCount >= nativeEventCount else {
      +      return
      +    }
           applyControlledDocument(force: true)
           if tokensMatchCurrentValue() {
             tokensNeedRebuild = false
      @@ -720,7 +727,6 @@
       
         private func emitSelection() {
           let selection = sourceSelection()
      -    nativeEventCount += 1
           onComposerSelectionChange([
             "selection": ["start": selection.start, "end": selection.end],
             "eventCount": nativeEventCount,
      
      diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      @@ -135,8 +135,9 @@
             JSON.stringify({
               value: props.value,
               selection: selection ?? null,
      -        mostRecentEventCount,
      +        mostRecentEventCount: mostRecentEventCountRef.current,
             }),
      +    // eslint-disable-next-line react-hooks/exhaustive-deps
           [mostRecentEventCount, props.value, selection],
         );
         const acceptNativeEvent = useCallback((eventCount: number) => {
      You can send follow-ups to the cloud agent here.
    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      2 blocking correctness issues found. This PR introduces significant runtime behavior changes to native iOS editor synchronization. Unresolved HIGH severity review comments identify potential bugs where legitimate parent updates may be silently dropped and user edits could be lost, warranting human review of the synchronization logic.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Pruned snapshots mis-tag stale text
        • Replaced aggressive event-count-based snapshot pruning with a size-capped approach (50 entries) to preserve snapshots needed for lag detection, and changed the fallback from Math.max(state, ref) to just the state value so it stays aligned with what React has processed.
      • ✅ Fixed: Stale revision for repeated text
        • Added includesNativeEvent tracking (whether mostRecentEventCount state changed between renders) so that when no native event occurred, parent-driven value changes bypass snapshot matching and use mostRecentEventCount directly, preventing old snapshot matches from rejecting intentional edits.

      Create PR

      Or push these changes by commenting:

      @cursor push 11bde65f5a
      Preview (pingdotgg/t3code@11bde65f5a)
      diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      @@ -97,6 +97,7 @@
         const nativeRef = useRef<NativeComposerEditorRef>(null);
         const mostRecentEventCountRef = useRef(0);
         const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
      +  const prevMostRecentEventCountRef = useRef(0);
         const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
           { eventCount: 0, value: props.value },
         ]);
      @@ -145,11 +146,14 @@
             })),
           );
         }, [props.value, skillLabels]);
      -  const controlledEventCount = resolveComposerControlledEventCount(
      -    props.value,
      -    Math.max(mostRecentEventCount, mostRecentEventCountRef.current),
      -    nativeEventSnapshotsRef.current,
      -  );
      +  const includesNativeEvent = mostRecentEventCount !== prevMostRecentEventCountRef.current;
      +  const controlledEventCount = includesNativeEvent
      +    ? resolveComposerControlledEventCount(
      +        props.value,
      +        mostRecentEventCount,
      +        nativeEventSnapshotsRef.current,
      +      )
      +    : mostRecentEventCount;
         const controlledDocumentJson = JSON.stringify({
           value: props.value,
           selection: selection ?? null,
      @@ -157,12 +161,14 @@
           mostRecentEventCount: controlledEventCount,
         });
         useEffect(() => {
      -    nativeEventSnapshotsRef.current = [
      -      { eventCount: controlledEventCount, value: props.value },
      -      ...nativeEventSnapshotsRef.current.filter(
      -        (snapshot) => snapshot.eventCount > controlledEventCount,
      -      ),
      -    ];
      +    prevMostRecentEventCountRef.current = mostRecentEventCount;
      +  }, [mostRecentEventCount]);
      +  useEffect(() => {
      +    const maxSnapshots = 50;
      +    const snapshots = nativeEventSnapshotsRef.current;
      +    if (snapshots.length > maxSnapshots) {
      +      nativeEventSnapshotsRef.current = snapshots.slice(-maxSnapshots);
      +    }
         }, [controlledEventCount, props.value]);
         const acceptNativeEvent = useCallback((eventCount: number, value: string) => {
           const acknowledgedEventCount = acknowledgeComposerNativeEvent(
      You can send follow-ups to the cloud agent here.
    7. @@ -350,15 +359,11 @@
      350359 }
      351360 }
      352361
      353- func setValue(_ value: String) {
      354- self.value = value
      355- applyControlledDocument(force: tokensNeedRebuild)
      356- if tokensMatchCurrentValue() {
      357- tokensNeedRebuild = false
      362+ func setControlledDocumentJson(_ documentJson: String) {
      363+ guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson),
      364+ document.mostRecentEventCount >= nativeEventCount else {
      365+ return
      358366 }
      359- }
      360-
      361- func setTokensJson(_ tokensJson: String) {
      362- guard self.tokensJson != tokensJson else {
      367+ if document.isNativeValue && textView.serializedText() != document.value {
      363368 return
      364369 }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High ios/T3ComposerEditorView.swift:367

      The isNativeValue guard in setControlledDocumentJson drops legitimate parent-driven updates. When isNativeValue is true and the current text differs from document.value, the function returns early. But isNativeValue is computed by checking if the value matches any previous native snapshot, not just the latest one. So after typing "ab" then "abc", a parent reset back to "ab" is misclassified as a native echo and silently ignored, breaking controlled undo/reset. The mostRecentEventCount >= nativeEventCount check already prevents stale echo updates, so the isNativeValue guard is redundant and harmful. Consider removing it.

      -    if document.isNativeValue && textView.serializedText() != document.value {
      -      return
      -    }
           if tokensJson != document.tokensJson {
      Also found in 1 other location(s)

      apps/mobile/src/native/T3ComposerEditor.ios.tsx:167

      isNativeValue is computed from nativeEventSnapshotsRef, but that ref is seeded with { value: props.value } before the native view has emitted any events. On the first render this makes every initial props.value look like native-originated text. The iOS view rejects native-originated payloads when its current text differs (setControlledDocumentJson returns early if document.isNativeValue &amp;&amp; textView.serializedText() != document.value), so mounting ComposerEditor with a non-empty existing draft now leaves the editor blank instead of showing the provided text.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift around lines 367-369:
      
      The `isNativeValue` guard in `setControlledDocumentJson` drops legitimate parent-driven updates. When `isNativeValue` is `true` and the current text differs from `document.value`, the function returns early. But `isNativeValue` is computed by checking if the value matches **any** previous native snapshot, not just the latest one. So after typing `"ab"` then `"abc"`, a parent reset back to `"ab"` is misclassified as a native echo and silently ignored, breaking controlled undo/reset. The `mostRecentEventCount >= nativeEventCount` check already prevents stale echo updates, so the `isNativeValue` guard is redundant and harmful. Consider removing it.
      
      Also found in 1 other location(s):
      - apps/mobile/src/native/T3ComposerEditor.ios.tsx:167 -- `isNativeValue` is computed from `nativeEventSnapshotsRef`, but that ref is seeded with `{ value: props.value }` before the native view has emitted any events. On the first render this makes every initial `props.value` look like native-originated text. The iOS view rejects native-originated payloads when its current text differs (`setControlledDocumentJson` returns early if `document.isNativeValue && textView.serializedText() != document.value`), so mounting `ComposerEditor` with a non-empty existing draft now leaves the editor blank instead of showing the provided text.
      
    8. Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Value-only native flag blocks updates
        • Changed isComposerNativeValue and resolveComposerControlledSelection to check only the most recent (last) snapshot instead of any historical snapshot, preventing React-prepended controlled values from being misidentified as native-owned.
      • ✅ Fixed: Early return drops parent selection
        • Replaced requestedSelection = nil with applyRequestedSelection() in applyControlledDocument's early-return path so parent-only selection updates are applied even when text and tokens already match, and fixed the React-side resolveComposerControlledSelection to stop incorrectly nullifying selections based on stale snapshots.

      Create PR

      Or push these changes by commenting:

      @cursor push 85e2f12c1c
      Preview (pingdotgg/t3code@85e2f12c1c)
      diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      @@ -488,7 +488,7 @@
         private func applyControlledDocument(force: Bool = false) {
           let currentSource = textView.serializedText()
           guard force || currentSource != value || !documentMatchesExpectedTokens() else {
      -      requestedSelection = nil
      +      applyRequestedSelection()
             updatePlaceholderVisibility()
             return
           }
      
      diff --git a/apps/mobile/src/native/composerEditorRevision.ts b/apps/mobile/src/native/composerEditorRevision.ts
      --- a/apps/mobile/src/native/composerEditorRevision.ts
      +++ b/apps/mobile/src/native/composerEditorRevision.ts
      @@ -54,7 +54,9 @@
         selection: ComposerEditorSelection | null,
         snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
       ): ComposerEditorSelection | null {
      -  if (selection === null || snapshots.some((snapshot) => snapshot.value === value)) {
      +  if (selection === null) return null;
      +  const lastSnapshot = snapshots[snapshots.length - 1];
      +  if (lastSnapshot !== undefined && lastSnapshot.value === value) {
           return null;
         }
         return selection;
      @@ -64,5 +66,6 @@
         value: string,
         snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
       ): boolean {
      -  return snapshots.some((snapshot) => snapshot.value === value);
      +  const lastSnapshot = snapshots[snapshots.length - 1];
      +  return lastSnapshot !== undefined && lastSnapshot.value === value;
       }
      You can send follow-ups to the cloud agent here.
    9. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Stale props skip revision resolve
        • Removed the includesNativeEvent gate so resolveComposerControlledEventCount is always called, ensuring stale props get a lower event count that the native side will reject instead of accepting with mostRecentEventCount.

      Create PR

      Or push these changes by commenting:

      @cursor push 19a2f474be
      Preview (pingdotgg/t3code@19a2f474be)
      diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      @@ -149,14 +149,12 @@
           );
         }, [props.value, skillLabels]);
         const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
      -  const controlledEventCount = includesNativeEvent
      -    ? resolveComposerControlledEventCount(
      -        props.value,
      -        selection ?? null,
      -        mostRecentEventCount,
      -        nativeEventSnapshotsRef.current,
      -      )
      -    : mostRecentEventCount;
      +  const controlledEventCount = resolveComposerControlledEventCount(
      +    props.value,
      +    selection ?? null,
      +    mostRecentEventCount,
      +    nativeEventSnapshotsRef.current,
      +  );
         const isNativeEcho =
           includesNativeEvent &&
           isComposerNativeEcho(
      You can send follow-ups to the cloud agent here.
    10. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Unbounded snapshot history slows composer
        • Restored the cap that trims nativeEventSnapshotsRef to the most recent 50 entries after each nativeEventSequence update, preventing unbounded array growth and the associated memory/latency regression.

      Create PR

      Or push these changes by commenting:

      @cursor push 91cacb479b
      Preview (pingdotgg/t3code@91cacb479b)
      diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
      @@ -174,6 +174,10 @@
         });
         useEffect(() => {
           previousRenderedEventSequenceRef.current = nativeEventSequence;
      +    const snapshots = nativeEventSnapshotsRef.current;
      +    if (snapshots.length > 50) {
      +      nativeEventSnapshotsRef.current = snapshots.slice(-50);
      +    }
         }, [nativeEventSequence]);
         const acceptNativeEvent = useCallback(
           (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
      You can send follow-ups to the cloud agent here. Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 22ca1f8fbe98e253e5201eab8e9821f51d6dd6fa. Configure [here](https://www.cursor.com/dashboard/bugbot).
    11. juliusmarminge merged this6245c54

    12. juliusmarminge closed this

Sign in to join this conversation.