<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Varun Kukade on Medium]]></title>
        <description><![CDATA[Stories by Varun Kukade on Medium]]></description>
        <link>https://medium.com/@varunkukade999?source=rss-3443b8abb2e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hSsbx6fbA4kSAfKgs4idOQ.jpeg</url>
            <title>Stories by Varun Kukade on Medium</title>
            <link>https://medium.com/@varunkukade999?source=rss-3443b8abb2e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:25:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varunkukade999/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Part 2: Geofencing & Background Location Tracking in React Native 2026]]></title>
            <link>https://medium.com/@varunkukade999/part-2-geofencing-background-location-tracking-in-react-native-2026-ffe26d67bd3a?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe26d67bd3a</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 13:44:06 GMT</pubDate>
            <atom:updated>2026-08-23T14:01:33.975Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first article we covered how location works at the OS level, what permissions you need in place and how to actually implement geofencing. Now we build on that foundation and learn how to reliably track user’s location in all states of app.</p><p><strong>What This Article Covers</strong></p><ul><li>How to achieve reliable location tracking on Android</li><li>How to achieve reliable location tracking on iOS</li><li>How to achieve motion-aware location tracking on Android and iOS</li><li>Observability and debugging</li><li>OEM-specific battery optimisation on Android</li><li>Testing strategy</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTwCJUuXXtJceSkXQat3XQ.png" /></figure><h3>How to implement location tracking</h3><p>Receiving a geofence entry event is only the first half of the problem. The second half is: once the user is inside the fence, how do you reliably track their location across all app states — foreground, background, and quit?</p><p>The answer is not one-size-fits-all. The right tracking approach depends entirely on what your use case actually needs. Before writing any code, it is worth being clear about what you are trying to achieve inside the fence.</p><p><strong>Real-World Examples to Frame the Decision</strong></p><ul><li><strong>Airport navigation</strong> — detect entry into the airport, then track the user’s movement continuously to provide turn-by-turn navigation to the correct terminal, gate, or baggage claim.</li><li><strong>Construction site safety</strong> — detect entry into a construction site, then monitor location to ensure workers stay within safe zones and alert them if they approach hazardous areas.</li><li><strong>Sports and fitness</strong> — detect entry into a running track, golf course, or ski resort, then continuously track movement to record laps, performance, or route statistics.</li><li><strong>Large warehouse</strong> — detect entry, then poll location every 1–2 minutes to track asset movement, estimate worker location, and record time spent in different areas. Works well when the goal is analytics rather than real-time safety alerts.</li><li><strong>Children safety</strong> — detect entry into a home geofence, notify family the child arrived safely. Detect exit, notify family the child left. No continuous tracking needed — only the arrival and departure events matter.</li></ul><p>In all of these, the pattern is the same: detect geofence entry first, then decide how to track movement inside based on what the use case actually requires.</p><p><strong>Why Not Create Smaller Secondary Geofences Inside the Primary One?</strong></p><p>The primary geofence is typically 80–100m radius. To track precise movement inside it, you would need secondary geofences of 10–20m radius. But as covered in the geofencing section earlier, anything below 50m radius is unreliable on both platforms. At 10–20m you will not get consistent events at all. Smaller geofences are the wrong tool for in-fence tracking.</p><p><strong>Location Polling — The Right Tool for In-Fence Tracking</strong></p><p>The correct approach for tracking movement inside a primary geofence is location polling — fetching the user’s location at a configured interval while they are inside the fence.</p><p>Every time you poll, you request a fresh location fix from the OS. The OS returns the best available result using GPS, WiFi, or cellular — whichever is available. If GPS is on, you get the most accurate fix. For safety-critical use cases like construction sites, prompting the user to enable GPS in android before entering the geofence is a must.</p><p><strong>How to choose polling interval:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8kzuWEwfwJJszyZSHXT4g.png" /></figure><p><strong>What to Do With Each Polled Location</strong></p><p>Each location fix should be sent to the backend as a ping. Do not process exit decisions or business logic in the app — let the backend own that logic, as covered in the geofencing strategy section. Each ping can carry additional metadata alongside the coordinates:</p><pre>coordinates<br>timestamp<br>isGPSEnabled<br>batteryPercent<br>appState (foreground / background / quit)<br>locationAccuracy</pre><p>This metadata helps you build an observability layer to understand the quality and reliability of your tracking data over time.</p><p>Taking the construction site safety example — the backend already knows the exact coordinates of dangerous or hazardous locations inside the fence. For every new ping it receives, the backend checks whether the user’s location is near any hazardous zone and pushes a notification to the user’s device if so.</p><p>If you choose to handle this on the app side instead, you would fetch the hazardous location coordinates from the backend, use a library like <a href="https://turfjs.org/">turf</a> to create virtual boundaries around them, track near-entry events on the device, and push local notifications using a library like <a href="https://notifee.app/">notifee</a>. Both approaches work — backend ownership is recommended for long-term maintainability since any changes to hazard zone coordinates or detection logic can be updated on the server without requiring a new app release.</p><p><strong>What Happens If the Network Is Down During Polling?</strong></p><p>Your app should maintain a local queue of unsent pings. When network connectivity is restored, flush the queue to the backend. Without this, you will silently lose location data whenever the user is briefly offline — which happens frequently inside large buildings, parking structures, and areas with weak signal.</p><p><strong>When to Stop Location Polling</strong></p><p>The most straightforward trigger to stop polling is the OS geofence exit event for the primary fence. When the OS tells you the user has left, stop polling immediately and clear all tracking state.</p><p>However, OS exit events can be delayed or missed — especially in quit state. Relying solely on the OS exit event means polling could silently keep running long after the user has left. You need three additional safeguards working together:</p><p><strong>1. Self-managed exit via Haversine</strong><br>Rather than relying entirely on the OS exit event — which can be delayed or missed, especially in quit state — run a Haversine distance check on every polled location. If two or three consecutive location fixes show the user outside the primary geofence boundary, treat that as an exit and stop polling. This gives you a reliable self-managed exit that does not depend on the OS delivering the exit event on time.</p><p><strong>2. Maximum session timeout</strong><br> Set a hard cap on how long polling can run — for example, 2–3 hours. If polling has been running continuously beyond that duration, something has likely gone wrong — the exit event was missed, the Haversine check failed due to poor GPS, or the user left the area with no signal. Stop polling, log the anomaly, and let the backend reconcile the open session.</p><p><strong>3. Permission revoked mid-session</strong><br> If the user revokes location permission while polling is active, the OS will stop delivering location fixes. Detect this change, stop the polling loop cleanly, and notify the backend that the session ended due to permission loss.</p><p>The rule is simple: the OS exit event starts the stop sequence, but never depend on it alone. Haversine self-exit, session timeout, and permission monitoring together ensure polling never runs longer than it should.</p><h4>Continuous Location Polling for Long Sessions — Battery Problem</h4><p>If you are continuously polling location inside a geofence for a long duration with GPS active throughout, it will drain the user’s battery noticeably. For short sessions of a few minutes this is acceptable. For sessions of 30 minutes or longer, you need a smarter approach.</p><p>This is where motion-aware location tracking comes in. Both the Transistor Software SDK and Radar implement this internally.</p><p>The core insight: you only care about the user’s location when they are actually moving inside the fence. When the user is stationary — sitting at a counter, waiting in a queue, standing in a hallway — their location is not changing. Polling continuously during that time burns battery for zero new information. You only need a new location fix once they start moving again.</p><p>Motion-aware tracking solves this by switching modes based on what the device is actually doing:</p><ul><li><strong>User is moving</strong> → continuous location updates for precise in-fence tracking. Higher battery draw, but necessary for accurate movement data.</li><li><strong>User is stationary</strong> → location services are paused. Every 60 seconds or so, a single location fix is requested to check if the user has started moving, then paused again immediately.</li></ul><p><strong>Understanding the Real Difference Between These Two Modes</strong></p><p>This distinction is worth understanding clearly because it affects how you think about battery impact.</p><p>In <strong>continuous mode</strong>, the GPS hardware is running and delivering a stream of fixes every 1–5 seconds the entire time — even between your polling intervals. Your app may only act on a fix every 60 seconds, but the GPS pipeline never stops in between.</p><p>In <strong>motion-aware stationary mode</strong>, location services are explicitly stopped. The GPS pipeline is completely off between heartbeats. Every 60 seconds, a one-shot request wakes the GPS chip for 2–3 seconds to get a single fix, then shuts it down again. Between those brief wake windows, nothing is running.</p><p><strong>Battery impact in numbers:</strong><br>Continuous GPS draws roughly 150–200mA constantly. Waking for a single fix every 60 seconds uses roughly 5% of that during the stationary phase. On a 45-minute session where the user is mostly stationary, continuous GPS would visibly drain the battery and your app would appear at the top of the user’s battery usage stats. Motion-aware tracking eliminates that drain entirely during stationary phases.</p><p><strong>Motion-Aware Tracking and Safety-Critical Use Cases</strong></p><p>Motion-aware tracking is not suitable for safety-critical use cases like construction site hazard detection.</p><p>When the user goes stationary and tracking switches to a 60-second heartbeat, there is a blind spot. In that window, the user could start moving, walk into a hazardous zone, and already be inside it before the next fix arrives. In a safety context, that blind spot is unacceptable.</p><p>Reducing the heartbeat interval helps but does not fully solve the problem — you are still trading accuracy for battery, and that trade-off is not worth making when user safety is at stake.</p><p>For safety-critical use cases: keep continuous polling always on. Accept the battery drain. It is a manageable operational concern. Missing a hazard alert is not.</p><h3>How to achieve reliable location tracking on Android</h3><p>Earlier in this article, we mentioned there is exactly one legal way to poll user location across foreground, background, and quit state on Android — even with only “Allow While Using” permission granted. That mechanism is the <strong>Android Foreground Service (FGS)</strong>.</p><p>This is confirmed by the <a href="https://developer.android.com/guide/components/foreground-services">Android developer docs</a> and validated through our own production testing. The only state where nothing works is if the user completely denies location access — in that case, stop all geofencing and location polling immediately.</p><h4>What Is a Foreground Service (FGS) ?</h4><p>Reference: <a href="https://developer.android.com/develop/background-work/services/fgs">Developer Docs</a></p><p>A foreground service is a type of Android service that performs operations noticeable to the user. Unlike background services, Android gives foreground services much higher priority — the OS will not kill them under memory pressure.</p><p>The trade-off is mandatory: foreground services must always show a persistent notification so the user is aware the service is running. You cannot run a foreground service silently. This is a hard OS requirement, not a Play Store guideline.</p><h4>Which FGS Type to Use</h4><p>Android 14 and above require every foreground service to declare a specific service type in the manifest. For location polling, the correct type is location.</p><p>Reference: <a href="https://developer.android.com/guide/components/foreground-services#types">Foreground service types</a></p><p>What the location type requires:</p><ul><li>Declare FOREGROUND_SERVICE and FOREGROUND_SERVICE_LOCATION permissions in your manifest</li><li>User must have granted at least ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION at runtime</li></ul><p>Do not combine types unnecessarily. If you combine location with another type like specialUse, your service must meet the prerequisites of all declared types simultaneously — which makes things harder to manage and harder to justify during Play Store review.</p><h4>If you are using Transistor Software SDK and Radar:</h4><p>Both of them handle their own <strong>Android Foreground Services</strong> internally for continuous location tracking. If you are already using either SDK, you do not need to integrate any other library offering FGS separately — these SDKs start and manage their own FGS when you initiate tracking with the correct permissions declared in the manifest.</p><p>TransistorSoft handles this based on device motion state. Check <a href="https://github.com/transistorsoft/react-native-background-geolocation/wiki/Philosophy-of-Operation#android-moving-state">this</a>.</p><p><strong>Moving:</strong> If device is moving, Location-services will be engaged and the plugin will begin tracking according to your configured distanceFilter or locationUpdateInterval. Inside moving state following 2 approaches can be used based on the requirement:</p><p><strong>1. Distance-based Tracking: </strong>Engage distance-based tracking simply by providing a distanceFilter &gt; 0 (eg: distanceFilter: 50). Plugin will begin recording a location each distanceFilter meters. Check <a href="https://docs.transistorsoft.com/react-native/GeoConfig/#distancefilter">this</a>.</p><p><strong>2. Time-based Tracking: </strong>To engage time-based tracking, simply configure distanceFilter: 0. The plugin will record a location each locationUpdateInterval milliseconds (eg: locationUpdateInterval: 30000 will record a location every 30s. Plugin also supports <a href="https://docs.transistorsoft.com/react-native/GeoConfig/#fastestlocationupdateinterval">fastestLocationUpdateInterval</a>.</p><p>Check this <a href="https://docs.transistorsoft.com/react-native/GeoConfig/#accuracy-and-sampling">config</a> for above 2 configs. You can subscribe to <strong>onLocation </strong>in moving state. In moving state, location services stay on and every location the SDK records is delivered through BackgroundGeolocation.onLocation.</p><pre>BackgroundGeolocation.onLocation((location) =&gt; {<br>  console.log(&quot;location co-ords:&quot;, location);<br>});</pre><p><strong>Stationary</strong>: While in the stationary state, since Android does not <em>completely</em> suspend apps in the background, the plugin is able to fire a <a href="https://docs.transistorsoft.com/react-native/HeartbeatEvent/"><strong>heartbeat event</strong></a> periodically (<a href="https://docs.transistorsoft.com/react-native/AppConfig/#heartbeatinterval">#heartbeatInterval</a>). The <strong>heartbeat event</strong> is implemented using the Android AlarmManager mechanism and is guaranteed to fire your Javascript callback:</p><pre>BackgroundGeolocation.ready({<br>  app: {<br>    heartbeatInterval: 60<br>  }<br>});<br><br>BackgroundGeolocation.onHeartbeat((event) =&gt; {<br>  console.log(&quot;[onHeartbeat]&quot;, event);<br>  // Optionally request a new location during heartbeat.<br>  BackgroundGeolocation.getCurrentPosition({<br>    samples: 1,<br>    persist: true<br>  }).then((location) =&gt; {<br>    console.log(&quot;[getCurrentPosition]&quot;, location);<br>  });<br>});</pre><p>The heartbeat event does not actively gives a fresh location fix. Call <a href="https://docs.transistorsoft.com/react-native/BackgroundGeolocation/#getcurrentposition">BackgroundGeolocation.getCurrentPosition</a> if an up-to-date reading is required. When heartbeat event is received you can make fresh location fix request and make the API call to the backend.</p><p>Hence <strong>onLocation + onHeartbeat</strong> is what you can rely on for android continuous tracking inside the geofence.</p><p>Example to understand:</p><pre>BackgroundGeolocation.ready({<br>  geolocation: { distanceFilter: 0, locationUpdateInterval: 10000 },<br>  app: { heartbeatInterval: 10 },<br>});<br><br>BackgroundGeolocation.onLocation(loc =&gt; console.log(&#39;moving:&#39;, loc.coords));<br>BackgroundGeolocation.onHeartbeat(() =&gt; {<br>  BackgroundGeolocation.getCurrentPosition({ samples: 1 }).then(loc =&gt;<br>    console.log(&#39;stationary:&#39;, loc.coords),<br>  );<br>});</pre><p>Moving: onLocation every ~10s</p><p>Stationary: onHeartbeat every ~10s</p><p>Moving again: onHeartbeat stops, onLocation resumes</p><h4>If you are not using Transistor Software SDK and Radar:</h4><p>In this case, you need to start managing FGS by yourself.</p><p>React Native does not have built-in support for Android foreground services. Notifee is the cleanest way to achieve this in React Native and provides a clean API to start and manage foreground services from JavaScript. f you already have the FGS running inside your own app, you can even utilize the same.</p><p>But Notifee is not maintained and the original <a href="https://github.com/invertase/notifee">Notifee</a> repository was officially archived by Invertase on April 7, 2026. Check this <a href="https://github.com/invertase/notifee">readme</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-qZL05eW90YRVr1-hKPUg.png" /></figure><p>Alternative library: <a href="https://github.com/marcocrupi/react-native-notify-kit">https://github.com/marcocrupi/react-native-notify-kit</a> An actively maintained fork of Notifee for React Native notifications. This repository preserves the original Notifee APIs and native core while continuing development for modern React Native releases.</p><blockquote>I will explain the behaviour through Notifee but you can very well switch to new library as its just a fork of notifee.</blockquote><p>The Notifee library handles creating the notification, registering the service, and managing the service lifecycle. You register a headless task that runs inside the FGS, and that task is where your location polling logic lives. The service keeps running regardless of whether the app is in foreground, background, or killed.</p><p>There is an important architectural point to understand here: app code does not execute in the quit state — only index.js code does. This means your location polling logic needs to live in two places, switching between them based on the current app state.</p><p><strong>Step 1 — Start the FGS by displaying a notification (inside app code)</strong></p><p>When the app is in the foreground and you want to start location polling, display a notification with asForegroundService: true. This creates the foreground service and starts the persistent notification:</p><pre>import notifee, { AndroidColor } from &#39;@notifee/react-native&#39;;<br><br>notifee.displayNotification({<br>  title: &#39;Foreground service&#39;,<br>  body: &#39;This notification will exist for the lifetime of the service runner&#39;,<br>  android: {<br>    channelId,<br>    asForegroundService: true,<br>    color: AndroidColor.RED,<br>    colorized: true,<br>    ongoing: false<br>  },<br>});</pre><blockquote>Note: Set ongoing false so that users can swipe notification away. <br>Android 13: ongoing:true blocks swipe; Android 14+ ignores it for FGS and bydefault allow user to swipe it. Keep false so users can hide the shade entry while FGS continues.</blockquote><p>Inside your app code, start location polling when the FGS starts. If the app moves to background or quit state, stop this polling — the index.js runner takes over from here.</p><p><strong>Step 2 — Register the FGS runner (inside index.js)</strong></p><pre>import notifee from &#39;@notifee/react-native&#39;;<br><br>notifee.registerForegroundService((notification) =&gt; {<br>  return new Promise(() =&gt; {<br>    // Long running task...<br>  });<br>});</pre><p>The callback registered with registerForegroundService is executed every time you display or update the notification, and it survives the app being killed or quit. Inside that callback, detect the current app state — if the app is in background or killed state, start a new polling interval for location. If the app returns to foreground, stop this polling and let the app-level polling take over.</p><p>This two-location polling architecture is a hard requirement of how React Native and Android foreground services work together. Without it, polling stops the moment the app is killed.</p><p><strong>What Notification to Show</strong></p><p>The FGS notification is mandatory — the user will see it in the notification shade for as long as the service is active. Design it carefully. This is what the user sees while you are tracking their location.</p><p><strong>When inside a geofence and only doing location tracking:</strong></p><ul><li>Title: [App Name] - You&#39;re at [Place Name]</li><li>Text: Tap to explore</li><li>Icon: your app icon</li></ul><p><strong>When a user-triggered session is active (delivery, fitness, navigation):</strong></p><ul><li>Title: [Session type] in progress</li><li>Text: relevant session information — time elapsed, distance, status</li><li>Icon: your app icon</li></ul><p><strong>What not to do:</strong></p><ul><li>Do not use vague text like “Tracking your location” with no context — this feels surveillance-like and damages user trust</li><li>Do not leave the notification title and body empty — Play Store reviewers check this</li><li>Do not show information unrelated to why location is being tracked</li></ul><p><strong>Can You Make API Calls Inside FGS?</strong></p><p>Yes. You can make HTTP requests to your backend from inside the FGS. Every time you get a location fix, send a ping immediately. This is exactly how you achieve the “<strong>backend owns event tracking</strong>” approach described earlier — the FGS polls location and sends pings, the backend does all the entry/exit logic.</p><p>Handle network failures gracefully: if the API call fails, queue the ping locally and retry when connectivity is restored. Do not drop pings silently.</p><p><strong>Handle network failures gracefully:</strong> if the API call fails, queue the ping locally (app storage) and retry when connectivity is restored. Do not drop pings silently.</p><p><strong>How the User Can Stop the FGS</strong></p><p>Android gives users multiple ways to stop a foreground service. Understanding each path and handling it correctly matters for both user experience and Play Store compliance.</p><ol><li><strong>From the notification — swipe behaviour varies by Android version:</strong></li></ol><p>Pre–Android 13</p><ul><li>FGS notifications were effectively non-dismissible.</li><li>Swipe usually failed unless the service stopped.</li></ul><p>Android 13 (API 33)</p><ul><li>Users can dismiss FGS notifications by swipe</li><li>The foreground service continues</li></ul><p>Android 14+</p><ul><li>Even setOngoing(true) notifications can be dismissed by swipe</li><li>Exceptions: device locked, or user taps Clear all (helps prevent accidental mass dismiss)</li></ul><p>If keeping the notification visible is a hard requirement and the user should not be able to dismiss it by swiping, use a dismiss → cancel notification strategy.</p><p>Whenever <strong>app is in background</strong> and user dismissed the notification, you can use <a href="https://docs.page/invertase/notifee/react-native/events#background-events"><strong>onBackgroundEvent</strong></a> to handle this event.</p><p><strong>index.js</strong></p><pre>// index.js<br>import { AppRegistry } from &#39;react-native&#39;;<br>import notifee, { EventType } from &#39;@notifee/react-native&#39;;<br>import App from &#39;./App&#39;;<br><br>notifee.onBackgroundEvent(async ({ type, detail }) =&gt; {<br>  const { notification, pressAction } = detail;<br>  if (type === EventType.ACTION_PRESS &amp;&amp; pressAction.id === &#39;mark-as-read&#39;) {<br>    <br>    await fetch(`https://my-api.com/chat/${notification.data.chatId}/read`, {<br>      method: &#39;POST&#39;,<br>    });<br>    // cancel the notification<br>    await notifee.cancelNotification();<br>  }<br>});<br><br>AppRegistry.registerComponent(&#39;app&#39;, () =&gt; App);</pre><p>Check above code. Notifee offers two different methods, cancelNotification and stopForegroundService.</p><p><strong>cancelNotification</strong>: Just cancels/hides/remove notification from notification drawer. This doesn’t stop the service.</p><p><strong>stopForegroundService</strong>: Removes the notification + stops the service alltogether which will stop the location polling in all states of app.</p><p>Based on your requirements you can go with any method. If you want that location polling should work even if user dismiss the notification, you can go with <strong>cancelNotification. </strong>I have tested it in all states of app and it doesn’t stop the location poll at all.</p><p>Similar to handle the dismiss in <strong>app foreground and app killed state</strong>, you can use <a href="https://docs.page/invertase/notifee/react-native/events#foreground-events"><strong>onForegroundEvent</strong></a></p><p><strong>2. From Active Apps</strong> — Android shows a list of apps with active foreground services. The user can tap “Stop” here to kill the service. This works same as <strong>stopForegroundService.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*fLTjwrmRTkmoZk8W" /></figure><p><strong>3. From App Settings</strong> — Settings → Apps → [Your App] → Force Stop kills the service and the entire app.</p><p><strong>4. From your app UI</strong> — if you provide a stop button inside the app, your code calls <strong>stopForegroundService.</strong></p><p><strong>What Happens When the User Stops the FGS From Active Apps?</strong></p><p>From Android 14 onwards, when the user stops a foreground service from the Active Apps panel, Android calls onTimeout() on the service giving it a brief window to clean up, then stops it.</p><p>The <a href="https://developer.android.com/guide/components/foreground-services#handle-user-stopped-service">official docs</a> are explicit: “If a user stops a foreground service, the app should not restart the service automatically.”</p><p>Respect that decision. Do not automatically restart the FGS. Your backend should handle the case where pings stop arriving unexpectedly — after a configurable timeout of no pings, auto-close any open session using the last known location.</p><p><strong>Edge Cases to Handle</strong></p><ul><li><strong>Location permission revoked mid-session</strong> — stop the service cleanly, notify the backend the session ended due to permission loss, show an in-app prompt when the user returns.</li><li><strong>Device runs out of battery while FGS is active</strong> — same as force quit. Backend should auto-close open sessions after a ping timeout.</li><li><strong>User locks screen and puts phone in pocket</strong> — FGS continues running normally. The notification remains visible on the lock screen.</li><li><strong>User uninstalls the app while FGS is running</strong> — service stops immediately.</li><li><strong>Two geofence events fire in rapid succession before FGS has started</strong> — guard against starting the FGS twice. Check if it is already running before starting a new instance.</li><li><strong>Network unavailable when FGS tries to send a ping</strong> — queue locally and retry. Do not block the polling loop waiting for network.</li></ul><p><strong>What to Avoid</strong></p><ul><li>Do not start a location FGS and leave it running indefinitely without a clear stop condition. Always have an explicit stop trigger.</li><li>Do not use WorkManager or JobScheduler for periodic location polling — they have minimum 15-minute intervals and are not suitable for sub-minute polling.</li><li>Do not use a background service (non-foreground) for location polling — Android 8+ will kill it aggressively under battery optimisation.</li></ul><p><strong>Can You Start a Location FGS From Background State?</strong></p><p>If app is in bcakground/killed state and OS sends the entry/exit event, you would need to start the FGS from the background/Killed state itself. Short answer to this question is — Yes, based on various conditions.</p><p><strong>Through our testing we have seen the various instances where — App was in killed state, OS sent the geofence entry event, app had given “Allow all the time” location permission, app was relaunched in the background, headless code executed, we started the Location Type FGS immediately and it sustained for long period of time.</strong></p><p>But it has a nuanced answer from the official docs.</p><p><a href="https://developer.android.com/guide/components/foreground-services#background-start-restrictions">Android 12+ restricts starting foreground services while the app is in the background</a> and throws ForegroundServiceStartNotAllowedException if violated.</p><p>However, there are specific exemptions. One of them, explicitly stated in the docs, is:</p><blockquote><strong>“</strong>Your app receives an event that’s related to geofencing or activity recognition transition.<strong>”</strong></blockquote><p>However, there is a second restriction that applies specifically to the location type:</p><blockquote>“The location runtime permissions are subject to while-in-use restrictions. For this reason, you cannot create a location foreground service while your app is in the background, unless you’ve been granted the <em>ACCESS_BACKGROUND_LOCATION</em> runtime permission.&quot;</blockquote><p>This means:</p><ul><li><strong>If the user has only granted “While Using” permission</strong> — you cannot start a location type FGS from a background geofence entry event. You can only start it while the app is in the foreground — for example, when the user manually triggers an action in the app.</li><li><strong>If the user has granted “Always Allow”</strong> — the geofence entry event can start the location FGS from background or quit state.</li></ul><p>Reference: <a href="https://developer.android.com/guide/components/foreground-services#background-start-restrictions">Restrictions on starting a foreground service from the background</a></p><h4>Declaring Location FGS Type in Play Console</h4><p>For apps targeting Android 14 and above, if your app uses a foreground service of type location, you must declare it in Play Console under Monitor and Improve → App Content.</p><p>Reference: <a href="https://support.google.com/googleplay/android-developer/answer/13392821">Understanding foreground service and full-screen intent requirements</a></p><p>This is not a hard approval gate like the background location permission declaration — it is a declaration. You are telling Google what your FGS does and backing it up with a description and video.</p><p><strong>What you need to provide for the </strong><strong>location FGS type:</strong></p><ul><li>Your specific use case selected from a pre-set list</li><li>A video demonstrating the feature</li></ul><p>Google provides these pre-set use cases in the Play Console form for TYPE_LOCATION:</p><ul><li>Background Location Updates: User-initiated location sharing</li><li>Background Location Updates: Navigation</li><li>Geofencing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZr9rDNOsp7TK22BbMsoAQ.png" /></figure><p>From our own experience, we selected <strong>Geofencing</strong> as the use case and it was accepted. The key is not which use case you select — it is how strongly you back it up with a real, clearly user-beneficial feature in the video. A weak feature with any use case selected will get rejected. A strong, genuine feature demonstrated honestly will get accepted.</p><p><strong>Very important:</strong> you must have a feature that actually needs background location tracking on top of geofencing. If your feature works adequately with only geofencing and does not genuinely require continuous polling, the Play Store may push back on the FGS declaration.</p><p>If your use case fits better under “Background Location Updates: User-initiated location sharing” or “Navigation,” those are equally valid choices depending on your feature.</p><p><strong>Video strategy</strong></p><p>Keep the video under 2 minutes. Show:</p><ol><li>FGS starting — either from a user action in the UI or triggered by a geofence event</li><li>The feature working while the app is in background — show the persistent FGS notification while it is running</li><li>The feature stopping when the session ends</li></ol><p><strong>The consistency rule applies here too</strong></p><p>The FGS declaration, the notification text, and the video must all describe the same thing. Keep the story consistent across all three — exactly the same principle as background location permission submission.</p><h3>How to achieve reliable location tracking on iOS</h3><p>The honest answer upfront: long continuous location tracking on iOS works reliably in foreground, and in background when the location session was started (or already alive) from a foreground-valid path.</p><p>If the app is quit and later relaunched only by a geofence event, you get a<br>short background wake — not a long tracking session. That is intentional<br>iOS behavior, not an SDK bug. Design for both paths explicitly.</p><p><strong>How It Works — The Full Flow</strong></p><ol><li>Register geofences for the outer boundary of the location you want to track inside.</li><li>User enters the geofence — entry event fires.</li><li>Start continuous location polling.</li><li>Send location pings to the backend.</li><li>User exits the outer geofence — stop location polling.</li></ol><p><strong>Foreground State</strong></p><p>Location polling works exactly as expected. No platform-specific constraints to account for.</p><p><strong>Background state</strong></p><p>As I previously mentioned, when the app moves to background, iOS normally keeps it running briefly for 5 seconds, then suspends it. IOS gives a backgrounded app approximately 30 seconds of execution time via UIApplication.beginBackgroundTask. After that it again suspends the app. You cannot chain background tasks indefinitely to bypass this.</p><p>Check <a href="https://developer.apple.com/documentation/UIKit/UIApplication/beginBackgroundTask(expirationHandler:)">this</a> &amp; <a href="https://medium.com/@kkapilchoubisa/background-tasks-in-ios-d92d0a51dc25">this</a> article for detailed info. But you can keep app alive in background for longer periods of time using certain approaches. Check out this article I created <a href="https://medium.com/@varunkukade999/how-to-extend-ios-app-background-execution-time-in-swift-a391b2aa7846">here</a> which explains how its done. Approaches I explained are</p><p>1. Keep GPS alive whole time when user goes background<br>2. Turn on /Turn off gps in certain intervals to keep app alive in background. This approach is used by Transistor Software SDK using <strong>preventSuspend: true</strong>. Check <a href="https://docs.transistorsoft.com/react-native/AppConfig/#preventsuspend">this</a>.</p><p><strong>Important clarification:</strong> preventSuspend: true prevents suspension, not termination. iOS can still kill your app from background due to memory pressure or jetsam — iOS&#39;s low-memory management system. This setting buys you more time, not immunity.</p><p>Also important: preventSuspend is a heavy option. The SDK documentation explicitly warns it has a noticeable battery impact. Do not leave it on permanently — enable it only when the user is actively inside a tracked area, and disable it when they leave.</p><p><strong>preventSuspend requires &quot;Always&quot; authorization.</strong> It does not work with &quot;While in Use.&quot; As the SDK author Christocracy confirmed: &quot;iOS does not allow an app to turn on location-services for a brief instant in the background with WhenInUse.&quot;</p><h4>How preventSuspend actually works under the hood — and why it is brittle</h4><p>preventSuspend attempts to work around ios limitation with a pulse mechanism. Christocracy explains: &quot;Prevent suspend operates by periodically turning on location-services just before the background time-limit expires, which resets the time-limit. If, for any reason a location fails to be recorded in each of these 30s, preventSuspend will fail. This is a very brittle mechanism, designed for very specialized use-cases. 99% of apps don&#39;t require preventSuspend.&quot;</p><p>References: <a href="https://github.com/transistorsoft/react-native-background-geolocation/issues/1099#issuecomment-655424685">Issue #1099</a> · <a href="https://github.com/transistorsoft/flutter_background_geolocation/issues/155#issuecomment-557975222">Issue #155</a> · <a href="http://github.com/transistorsoft/flutter_background_geolocation/issues/1255#issuecomment-2000071725">Issue #1255</a></p><h4>How the Transistor Software SDK handles background location on iOS</h4><p>Two events feed location data in background:</p><p>onLocation — fires every time the user moves a configured distance (for example, every 5 metres). Under the hood, this uses CLLocationManager.startUpdatingLocation() with a distance filter set to your configured threshold. If the user is stationary, this stops firing — the OS has nothing to report.</p><p>onHeartbeat — covers the stationary case where onLocation goes silent. Inside stationary state, Apple does not push location on a timer. The SDK solves this by:</p><ul><li>Detecting the stationary state and calling stopUpdatingLocation() to disengage location services</li><li>Starting a HeartbeatService with a configurable interval (for example, every 15, 30, or 60 seconds)</li><li>Running a UIBackgroundTask renewal chain every ~25 seconds to keep the app schedulable in background so the timer can actually fire</li><li>Inside each heartbeat callback, manually requesting the current location as a one-shot fix</li></ul><p>Together, these two events cover both states completely:</p><blockquote>onLocation = OS-driven: &quot;tell me when the user moves 5m.&quot;<br>onHeartbeat = app-driven: &quot;user is stationary — wake me every N seconds so I can manually request a fresh GPS fix.&quot;</blockquote><p><strong>Quit State: <br></strong>As I said, after app is killed it gets relaunched only for geofence entry/exot events. If app is killed by user after entering the geofence, there is no way to track user’s location on ios. This is hard limit imposed by OS. <strong>TransistorSoft</strong> adds a <strong>stopOnTerminate</strong> flag which relaunches app in background after user cross 200m from the place where app was killed. Only after that, you can resume tracking.</p><p><strong>Common Workarounds That Do Not Work</strong></p><p>Two approaches come up regularly when teams try to solve the force-quit problem. Neither works.</p><p><strong>Using many small inner geofences</strong></p><p>This fails for two independent reasons. First, iOS’s minimum reliable geofence radius is around 100–200m depending on available signals. A small geofence inside a larger area will either never fire or fire randomly — this is the exact reason geofences are the wrong tool for inner area tracking. Second, even if small geofences worked, region monitoring after a user force-quit is already unreliable. Stacking two unreliable mechanisms does not improve reliability. Additionally, iOS limits you to 20 monitored regions per app — using them all for inner areas leaves nothing for outer boundaries.</p><p><strong>Silent push notifications (</strong><strong>content-available: 1)</strong></p><p>iOS explicitly blocks background push delivery to force-quit apps. A silent push will not wake a force-quit app. Live Activity push updates only refresh a UI widget — they do not relaunch the app process. The app stays terminated. This is the same OS-level policy, with no bypass available.</p><h4>Declaring Persistent Background Location for iOS App Store</h4><p>There are two distinct iOS capabilities involved in this article, and it is important not to confuse them during App Store submission:</p><ul><li><strong>Region monitoring / geofencing</strong> — handled by CLLocationManager region monitoring APIs. Does not require declaring location in UIBackgroundModes. iOS supports this out of the box with &quot;Always Allow&quot; permission. Used for primary geofence detection.</li><li><strong>Persistent background location</strong> — continuous or periodic location updates running while the app is in background or quit state. Requires explicitly declaring location inside UIBackgroundModes in your Info.plist. Used for location tracking inside the geofence after entry.</li></ul><p>If you are doing location tracking inside a geofence after entry, you must declare UIBackgroundModes location. Apple will detect this during review and will ask you to justify it.</p><p><strong>How Apple Reviews This</strong></p><p>When you submit a build with location in UIBackgroundModes, the reviewer checks your <strong>Notes</strong> section in App Store Connect and evaluates whether your features genuinely require persistent background location — or whether region monitoring alone would have been sufficient. If region monitoring alone could achieve your goal, Apple will reject the persistent background mode declaration.</p><p>Your notes must clearly argue that your features need both — region monitoring for boundary detection, and persistent background location for what happens inside the boundary after detection.</p><p><strong>What to Add to Your Existing App Store Notes</strong></p><p>You already have your notes structured with feature descriptions and justification for “Always Allow” permission. Add one additional field to each relevant feature explaining why persistent background location is needed on top of geofencing:</p><pre>TEST ACCOUNT FLOW<br>[Step by step sign-in instructions using the credentials above]<br><br>LOCATION PERMISSION FLOW<br>- We first request &quot;While Using the App&quot; location only<br>- &quot;Always&quot; is never force-requested on first launch<br>- Our &quot;Always&quot; disclosure appears only after the user grants <br>  &quot;While Using the App&quot; permission<br><br>HOW TO SEE THE ALWAYS DISCLOSURE <br>(Follow bg_location_permission_disclosure.mov)<br>[Step by step instructions to reach the in-app disclosure]<br><br>WHY ALWAYS LOCATION IS NEEDED<br>[What your app does and why &quot;Always&quot; is needed. <br>2-3 sentences maximum]<br><br>VIDEOS:<br>bg_location_permission_disclosure.mov | <br>bg_location_feature1.mov | <br>bg_location_feature2.mp4<br><br>Feature 1: [Feature title] (bg_location_feature1.mov)<br>What the video shows: [Step by step explanation]<br>Why this matters: [User value]<br>Why Always is required: [Why &quot;While Using&quot; is insufficient]<br>Why UIBackgroundModes location is required: [Why region <br>monitoring alone is insufficient for this feature]<br><br>Feature 2: [Feature title] (bg_location_feature2.mp4)<br>What the video shows: [Step by step explanation]<br>Why this matters: [User value]<br>Why Always is required: [Why &quot;While Using&quot; is insufficient]<br>Why UIBackgroundModes location is required: [Why region <br>monitoring alone is insufficient for this feature]</pre><p>Use this pattern for the UIBackgroundModes justification field:</p><pre>&quot;Region monitoring alone is not sufficient for this feature <br>because [specific reason]. Once the geofence entry is <br>detected, the app must continue tracking the user&#39;s location <br>in the background at [interval] to [specific user benefit]. <br>Without location in UIBackgroundModes, iOS suspends the app <br>after geofence entry and no further location updates <br>are delivered.&quot;</pre><p><strong>The Argument You Need to Make</strong></p><p>Your feature descriptions must convince the reviewer of two things:</p><ol><li>Geofencing alone only fires on boundary crossings — it tells you the user entered or exited, but nothing about what happens in between.</li><li>Your feature has a genuine reason to know what happens in between — safety, navigation, session tracking — and that reason directly benefits the user.</li></ol><p>If both are true and clearly stated in your notes, persistent background location will be accepted alongside your existing geofencing justification.</p><h3>How to Technically Achieve Motion-Aware Location Polling on Android and iOS</h3><p>Every background location implementation eventually faces the same battery problem. Continuous GPS is expensive. Turning it off entirely means missing the moment a user arrives, leaves, or stops at a destination. The practical question is not whether to poll — it is when to poll aggressively and when to switch to something lighter.</p><p>That decision hinges on one signal: is the user moving or stopped?</p><p>Once you know the answer, the pattern is the same on both platforms:</p><ul><li><strong>Moving</strong> → engage continuous location updates (distance-filtered GPS)</li><li><strong>Stopped</strong> → disengage continuous GPS, start a lightweight heartbeat timer that periodically requests a fresh fix</li></ul><p>The two approaches below differ only in how they infer motion. Both arrive at the same switching behaviour — they just use different inputs to make the decision.</p><h4>Approach 1: Activity Recognition — The TransistorSoft Way</h4><p>This is the industry-standard path used by most background location SDKs, including the Transistor Software SDK. Instead of inferring motion from GPS patterns, you ask the OS directly what the user is physically doing.</p><p><strong>Android — Google Play Services Activity Recognition</strong></p><p>Android exposes motion through the <a href="https://developers.google.com/location-context/activity-recognition">Activity Recognition API</a> (part of Google Play Services Location). You subscribe to activity transition updates via ActivityRecognitionClient. The OS fuses accelerometer, gyroscope, and other low-power sensors internally to classify what the user is doing.</p><p>Manifest permissions required:</p><pre>&lt;uses-permission android:name=&quot;android.permission.ACTIVITY_RECOGNITION&quot; /&gt;<br>&lt;uses-permission android:name=&quot;com.google.android.gms.permission.ACTIVITY_RECOGNITION&quot; /&gt;</pre><p>On Android 10 and above (API 29+), ACTIVITY_RECOGNITION is a runtime permission the user must grant separately from location.</p><p>Each update the API returns includes an activity type:</p><p>STILLDevice stationary</p><p>WALKINGWalking</p><p>RUNNINGRunning</p><p>ON_FOOTOn foot (unspecified gait)</p><p>IN_VEHICLEIn a vehicle</p><p>ON_BICYCLECycling</p><p>TILTINGPhone being tilted</p><p>UNKNOWNUnclassified</p><p>The SDK derives a simple boolean from these: STILL, UNKNOWN, and TILTING → stationary. Everything else → moving.</p><p><strong>iOS — Core Motion (CMMotionActivityManager)</strong></p><p>iOS provides the equivalent through Core Motion. CMMotionActivityManager.startActivityUpdates() delivers a stream of CMMotionActivity objects with boolean flags — stationary, walking, running, automotive, cycling — along with a confidence level: .low, .medium, or .high.</p><p>Required Info.plist entry:</p><pre>&lt;key&gt;NSMotionUsageDescription&lt;/key&gt;<br>&lt;string&gt;We use motion data to detect when you&#39;ve stopped moving.&lt;/string&gt;</pre><p>Without this key, App Store review will reject your build with error 90683. Feel free to change the description of this key as per your usecase.</p><p><strong>How the engage/disengage cycle works</strong></p><ol><li><strong>Moving</strong> (WALKING, IN_VEHICLE, etc.) → start continuous GPS with a distance filter (e.g. 5m) → onLocation fires on each meaningful movement.</li><li><strong>Transition to still</strong> → start a debounce timer (stopTimeout, configurable in minutes).</li><li><strong>Still for the full </strong><strong>stopTimeout duration</strong> → declare stationary → stop GPS → start heartbeat timer (heartbeatInterval, configurable in seconds) → onHeartbeat fires; handler calls getCurrentPosition() for a single fresh fix.</li><li><strong>Moving again</strong> → cancel debounce → re-engage GPS.</li></ol><p>onMotionChange fires on each moving ↔ stationary transition, giving you a clean hook to update your backend and adjust polling behaviour.</p><p><strong>Drawbacks to be aware of:</strong></p><ul><li>Requires a separate motion permission on top of location — on Android 10+, this is a runtime grant the user must explicitly approve.</li><li>If the user denies motion permission, activity-based detection is unavailable and you need a fallback strategy.</li></ul><p><strong>Use this approach when:</strong> you want a general-purpose background location SDK and motion permission is acceptable as a core dependency of your feature.</p><h4>Approach 2: Location-Pattern Detection — The Radar Way</h4><p>Radar uses this alternative: infer motion from GPS itself using distance, dwell time, and speed — with no motion permission required.</p><p>The logic is straightforward. GPS already tells you where the user is and how fast they are moving. If you observe the pattern of consecutive fixes, you can determine moving vs stopped without touching the motion sensors at all.</p><p><strong>The three parameters that define the entire motion model:</strong><br>locationStopDistanceMeters: How close to the last fix counts as “not moving”. e.g 5 m</p><p>locationStopDurationSeconds:How long the user must stay within that radius before being declared stopped. e.g 45 seconds</p><p>locationResumeDistanceMeters: How far the user must move from the last fix to be declared moving again. e.g 12 m</p><p>That is the complete motion model. Three numbers, fully tunable.</p><p><strong>How stopped state is detected:</strong></p><p>While GPS is running, the SDK anchors on the user’s last location fix. If every subsequent fix lands within 5m of that anchor, a dwell timer starts. If the user stays inside that 5m bubble for 45 seconds, they are declared stopped.</p><p><strong>How moving state is detected from stopped:</strong></p><p>While stopped, each heartbeat fix is checked against the anchor point. If the user moves more than 12m from that anchor, they are declared moving again.</p><p>The 12m resume threshold is deliberately larger than the 5m stop radius. That gap is intentional — it prevents GPS jitter from repeatedly flipping the state back and forth when the user is barely shifting position indoors.</p><p><strong>Pros:</strong></p><ul><li>No motion permission required — stays entirely within your existing location permission scope</li><li>Simple and fully tunable — three numbers you control, no sensor classification pipeline to debug or worry about OEM-specific throttling</li><li>Significant battery saving — GPS turns off the moment dwell duration is met; the heartbeat timer is cheap by comparison</li></ul><p><strong>Drawbacks:</strong></p><ul><li>Slower to detect stop — must wait the full dwell duration (e.g. 45 seconds) before GPS disengages. Activity recognition can react in seconds since it is reading hardware sensors directly rather than waiting for a position dwell pattern.</li></ul><p>If motion permission is acceptable for your use case and fast stop detection matters — for example, a food delivery or navigation app — Activity Recognition is the stronger choice. If you want to stay within location permissions only and prefer a simpler, fully tunable model, location-pattern detection is the cleaner path.</p><p>Both approaches arrive at the same battery outcome during stationary phases. The difference is in how quickly they get there and what permissions they require to do it.</p><h3>Handling “While in Use” permission</h3><p>Whether you need to handle “While in Use” permission depends heavily on your app’s context.</p><p>For some apps — like a delivery driver app where the company instructs drivers to grant <strong>“Always Allow”</strong> before they can start working — the vast majority of users will have “Always Allow” granted. “While in Use” cases will be rare. You could choose to show a hard blocker when “Always Allow” is not granted and not offer any fallback at all.</p><p>For consumer-facing apps where the user makes their own permission choice freely, a meaningful portion will choose <strong>“While in Use.”</strong> Showing a hard blocker here would hurt retention. A graceful fallback is the right call.</p><p>Decide based on your user base. If you choose to support it, here is how to handle it correctly.</p><p><strong>Common to both Android and iOS</strong></p><p>When the user has only “While in Use” permission, do not register any geofences with the OS and do not invoke OS geofencing in any form. The OS will not deliver geofence events in background or quit state with this permission level, so registering them is pointless. If geofences were previously registered from a prior “Always Allow” grant, deregister them immediately when you detect the permission has been downgraded.</p><p>Your fallback here is location polling driven by a Haversine check — no OS geofencing at all.</p><p><strong>iOS</strong></p><p><strong>App open (foreground)</strong><br>Every time the app opens or transitions from background or quit state to foreground, run a Haversine check against your full list of place coordinates. If the user is inside any boundary, immediately start location polling and send pings to the backend on every interval. If the user is outside all boundaries, do not start polling. If polling was already running, stop it.</p><p><strong>App Background State<br></strong>iOS allows location access in the background with “While in Use” permission under specific conditions. Three things must be in place:</p><p><strong>1. Info.plist setup</strong><br> Your Info.plist must declare the following:</p><ul><li>UIBackgroundModes array must include location</li><li>NSLocationWhenInUseUsageDescription — purpose string for while in use permission</li><li>NSLocationAlwaysAndWhenInUseUsageDescription — purpose string for always permission</li></ul><p><strong>2. Xcode capability</strong><br> In Xcode → your target → Signing &amp; Capabilities → Background Modes → check “Location Updates.” Without this, iOS will not deliver location updates to your app in the background regardless of what you set in code.</p><p><strong>3. Keeping GPS active</strong></p><p>This is the critical constraint with “While in Use” permission that most developers miss.</p><p>iOS does not allow an app to turn on location services from the background with “While in Use” authorization. This means any approach that stops GPS and tries to restart it from background — including the SDK’s motion-aware algorithm which stops GPS when the user goes stationary — will fail. Once GPS stops, the app suspends within 30 seconds and cannot restart location from background.</p><p>You have two options:</p><p><strong>Option 1 — Keep GPS continuously on</strong><br> Call startUpdatingLocation() in the foreground and never call stopUpdatingLocation() for the duration of the session. iOS will not suspend the app because location services are continuously active. The trade-off is higher battery drain during stationary phases.</p><p><strong>How to implement continuous GPS keep-alive alongside the SDK</strong></p><p>If you are using Transistor Software SDK and want continuous GPS active for the entire session window — regardless of what the SDK’s motion engine decides — the cleanest approach is a second dedicated CLLocationManager in your host app. The SDK continues owning geofences, motion detection, and location events. This second manager exists for one purpose only: holding Apple&#39;s continuous-location background assertion so the process never suspends.</p><p><strong>Prerequisites</strong></p><ul><li>UIBackgroundModes in Info.plist must include location</li><li>User must have granted “Always” authorization. With “While in Use,” showsBackgroundLocationIndicator = true is also required and the blue bar will be visible to the user.</li><li>Do not set allowsBackgroundLocationUpdates = true without the Info.plist key — Apple can terminate the app.</li></ul><p><strong>How it works</strong><br>Create a small singleton with its own CLLocationManager separate from the SDK&#39;s. On startKeepAlive, configure it with allowsBackgroundLocationUpdates = true, pausesLocationUpdatesAutomatically = false, and call startUpdatingLocation. Never stop it until the session ends. On didUpdateLocations, do nothing — the SDK owns all product logic. On stopKeepAlive, call stopUpdatingLocation and reset the flags.</p><p>Expose startKeepAlive and stopKeepAlive to JS via a small native module.</p><p><strong>When to call it from JS</strong><br>Start the keep-alive when the user enters the critical window — preferably while the app is still in the foreground. An assertion started deep in background is weaker. Stop it the moment the window ends.</p><p>js</p><pre>// On entering critical window (e.g. inside tracked area):<br>NativeKeepAlive.startKeepAlive();<br><br>// On leaving:<br>NativeKeepAlive.stopKeepAlive();</pre><p><strong>Critical rules</strong></p><ul><li>didUpdateLocations on the keep-alive manager should be a no-op for all product logic. Do not fight the SDK.</li><li>Do not call startMonitoring(for:) on this manager. The SDK remains the sole geofence owner.</li><li>Start as early as possible — ideally while still in foreground.</li><li>Stop immediately when the session ends. Do not leave it running unnecessarily.</li></ul><p>The one-liner summary: the SDK owns geofencing and motion intelligence; your host app adds a second, dumb CLLocationManager that only calls startUpdatingLocation for the session you refuse to miss.</p><p><strong>Option 2 — Rely on the SDK’s motion-aware approach</strong><br>If you use Transistor Software SDK with preventSuspend: true, the SDK&#39;s motion-aware algorithm stops GPS when stationary and uses location pulses to extend background time. However this only works with <strong>Always</strong> authorization — not While in Use. With While in Use, once GPS stops the app suspends after 30 seconds and the pulse cannot restart it.</p><p><strong>Quit state</strong><br>Nothing can be done here. Do not invest any effort in handling this case.</p><p><strong>iOS — important rules</strong></p><ul><li>If the user upgrades to “Always Allow” at any point, stop the fallback “Allow while using” polling immediately. The fallback and the main OS geofencing path must never run simultaneously. Detect the permission change and switch paths cleanly.</li><li>If the user moves outside all boundaries while polling is active, stop polling. Never poll outside a known boundary — it wastes battery and produces irrelevant pings.</li></ul><p><strong>Android</strong></p><p>Android is more flexible here. A Foreground Service of type location works in all three app states — foreground, background, and quit — even with only &quot;While in Use&quot; permission. This has been confirmed through direct testing.</p><p><strong>App open (foreground)</strong><br>Same as iOS — run a Haversine check against your place coordinates on app open. If the user is inside a boundary, start the FGS immediately. The FGS notification will appear and polling will begin. If the user is outside all boundaries, do not start the FGS.</p><p><strong>Background and quit state</strong><br>Once the FGS is running, it stays alive across all three app states. Android delivers location updates to the FGS even when the app is in the background or killed, as long as the FGS has not been explicitly stopped. This is the key Android advantage over iOS for this permission level — one FGS start from the foreground covers everything.</p><p>The user can still stop the FGS from the Active Apps section. Handle that case the same way you handle it for “Always Allow” users — stop polling cleanly and let the backend reconcile any open session. Do not try to restart the FGS automatically after the user stops it.</p><h3>Observability and Debugging</h3><p>Once geofencing and background location tracking is live in production, failures will happen silently. A geofence event gets delayed by 6 minutes on a Xiaomi device. An FGS gets killed and nobody notices. A user revokes location permission and their session never closes. Without deliberate observability built into the system from day one, none of this is visible until a user complains — and most users do not complain, they just stop using the feature.</p><p>The foundation of observability here is the location ping itself. Every ping you send to the backend is an opportunity to attach metadata that tells you exactly what was happening on the device at the moment of the fix. At minimum, include:</p><ul><li>appState — foreground, background, or quit</li><li>locationSource — GPS, WiFi, or cellular</li><li>locationAccuracy — accuracy radius in metres returned by the OS</li><li>isGPSEnabled — whether the GPS toggle is on</li><li>permissionLevel — while in use or always allow</li><li>isBatteryOptimizationEnabled — Android only</li><li>batteryPercent — current battery level</li><li>appVersion — which build this came from</li><li>timestamp — exact time of the fix on the device</li><li>platform — android or ios</li><li>deviceModel — exact device model (e.g. Samsung Galaxy S23, iPhone 15 Pro)</li><li>userId — to tie all pings to a specific user for session reconstruction and debugging</li></ul><p>With this data flowing to your backend, you can build a simple dashboard that gives you real-time visibility into: which users have gaps in their pings, which devices are consistently late on geofence events, which app versions have higher FGS kill rates, and which permission levels correlate with worse tracking quality. This is what separates a feature that works in testing from one you can confidently operate in production.</p><p><strong>Specific Signals Worth Monitoring</strong></p><p><strong>Sessions with no closing ping</strong></p><p>User entered a geofence, pings started, but no exit ping ever arrived. The cause could be a missed OS exit event, a killed FGS, or a permission revocation mid-session. Auto-close these sessions after a configurable timeout using the last known location, flag them in your dashboard, and investigate patterns — if the same device model or app version appears repeatedly, it is a signal worth acting on.</p><p><strong>Ping gaps longer than 2x your polling interval</strong></p><p>If you poll every 30 seconds and a user has a 5-minute gap, something went wrong in that window. Log it with the metadata from the ping immediately before and after the gap. Over time, patterns emerge — gaps that correlate with specific Android versions, OEM battery management behaviour, or app states tell you exactly where to focus your reliability work.</p><p><strong>Location accuracy consistently above 100m</strong></p><p>This user likely has GPS off and WiFi scanning disabled. Their in-fence tracking is unreliable — coordinates you are receiving may be 100–500m off the actual position. Rather than silently accepting inaccurate data, detect this condition from the locationAccuracy and isGPSEnabled fields in your ping metadata and degrade gracefully. Options include: surfacing an in-app prompt asking the user to enable GPS, reducing the confidence weight of low-accuracy pings in your backend logic, or flagging the session as low-reliability for your analytics team.</p><p>The metadata layer is not optional for production systems. It is what gives your backend the context to make intelligent decisions, gives your team the visibility to catch silent failures, and gives your analytics team the signal quality data they need to trust what the location system is telling them.</p><h3>OEM-specific battery optimization on Android</h3><p><strong>AOSP</strong> stands for Android Open Source Project. It is the base, unmodified version of Android that Google maintains and publishes publicly. Think of it as “pure Android” — no manufacturer customizations, no extra apps, no modified battery management.</p><p><strong>OEM</strong> stands for Original Equipment Manufacturer. In the Android context, it refers to the device manufacturers — Samsung, Xiaomi, OnePlus, Oppo, Huawei, Vivo, and others — who take Google’s base Android (AOSP) and modify it before shipping it on their devices.</p><p>Google defines how Android should behave, but Samsung, Xiaomi, OnePlus, Oppo, Huawei, and other manufacturers add their own aggressive battery optimization layers on top. These OEM layers kill background services, delay geofence events, and restrict location access far more aggressively than stock Android — and they do it silently without telling your app.</p><p>Common OEM behaviors that will break your implementation:</p><ul><li>App is force-stopped after being in the background for a short period even without user action</li><li>FGS is killed despite being correctly declared and running — even with a visible notification</li><li>Geofence events are batched and delivered all at once instead of in real time</li><li>Location access is throttled or blocked entirely in background even with Always Allow permission</li></ul><p><strong>The FGS survival problem on OEM devices</strong></p><p>On paper, swiping an app away from Recents should remove the task — not tear down a correctly running FGS. In practice, this contract holds on AOSP and Pixel devices but often fails on OEM Android skins, especially older Android 12 builds from Xiaomi, Samsung, Oppo, and Huawei. On those devices, a Recents swipe or Clear All can kill the FGS entirely.</p><p>Developers usually try Settings → Apps → Battery → Unrestricted as a fix. That only exempts the app from AOSP Doze. OEM power managers sit on top of that layer and can still kill the FGS regardless. Unrestricted is necessary — but not sufficient on aggressive OEM skins.</p><p>If FGS survives on an emulator but dies on a specific OEM device, classify it as OEM kill policy — not a bug in your FGS implementation. This distinction matters when triaging production issues.</p><p><strong>How to validate:</strong> reproduce on an AOSP emulator or Pixel first. If FGS survives there but dies on a specific OEM device, the problem is OEM-specific, not your code.</p><p><strong>The correct architecture for this reality</strong></p><p>Do not design as if FGS immortality is guaranteed. Design for process death:</p><ul><li>While the process is alive: use FGS for visible tracking and live updates</li><li>After OEM process death: rely on OS geofence ENTER/EXIT events to wake the app, persist state durably, and reconcile on next app open</li></ul><p><strong>What you can do</strong></p><p>The go-to reference for this problem is <a href="https://dontkillmyapp.com/">dontkillmyapp.com</a>. It documents exactly what each major OEM does and provides per-device settings the user needs to change.</p><p>Your app should detect when battery optimization is active using PowerManager.isIgnoringBatteryOptimizations() and prompt the user to whitelist your app if not. Beyond that, you can optionally guide users through OEM-specific steps — Autostart, locking the app in Recents, or adding it to Never Sleeping Apps — using the vendor guides on dontkillmyapp.com.</p><p>Do not assume this is a minor edge case. In markets like India where Xiaomi, Samsung, and Oppo have very high market share, a large portion of your users will be on OEM-modified Android. Test on real OEM devices, not just stock Android emulators.</p><h3>Testing strategy</h3><p>You cannot physically drive to every location every time you make a code change. You need a way to simulate movement from your desk. Android emulator and iOS simulator can help a lot here. We did 70–80% of our developer testing through simulation without leaving our desks. Most bugs were reproducible in the simulated environment itself and could be debugged and fixed there. For the remaining 20–30%, we did on-site testing on real devices to validate everything in a real environment.</p><p>For a complete guide on how to set up location simulation, create GPX routes, simulate stationary dwell, control speed, and use AI to generate routes — I have written a dedicated article on this:<br><a href="https://medium.com/@varunkukade999/how-to-simulate-location-and-routes-in-android-and-ios-without-physically-moving-d324fa3eb917">How to Simulate Location and Routes in Android and iOS Without Physically Moving</a></p><p>Note: GPX simulation does not work for iOS killed-state testing. As soon as the app is killed, the simulator stops the GPX route. Use <a href="https://github.com/nexron171/SimVirtualLocation">https://github.com/nexron171/SimVirtualLocation</a> instead. This macOS app can simulate movement from point A to point B even while your app is killed. I ran into two limitations with it:<br>1. You cannot add intermediate points between A and B.<br>2. You cannot set a pace slower than 5 km/h.</p><p>On iOS, once the app is killed, I could not see logs in the Xcode console. This command captured them instead:</p><blockquote>: &gt; killrun.txt &amp;&amp; xcrun simctl spawn booted log stream — level debug — style compact — predicate ‘process CONTAINS “APP_NAME”’ 2&gt;&amp;1 | tee killrun.txt</blockquote><p>Replace APP_NAME with your app name and run it in Terminal. killrun.txt is created immediately, and all matching logs are written into it.</p><p>If you are doing AI-assisted coding, this debugging loop worked well for me:<br>1. Ask AI to add detailed logs across each part of the flow.<br>2. Run a manual simulator test, then give those logs back to AI. Ask it to validate every step and confirm whether behavior matched expectations. It will often catch small bugs. Repeat until the flow is solid.</p><p><strong>Testing on real devices</strong><br>For background and quit state testing, the simulator and emulator are not sufficient to get confidence. You need a real device. So go in real outside environments and then test your app and only after that go for production.</p><p>That covers everything — from OS fundamentals and permissions, to geofencing strategy and location tracking, to production-grade implementation across both platforms. What took months of research, testing, and iteration is now documented in one place. If this saved you even one week of trial and error, it has done its job.</p><p>Geofencing and background location tracking sounds straightforward on paper — draw a boundary, get an event, track the user. In practice, it is one of the most complex features to get right across Android and iOS because you are constantly negotiating between three competing forces: what your product needs, what the OS allows, and what the app stores will accept. Every decision in this article has a direct consequence on reliability, battery life, user trust, and store acceptance. Getting any one of them wrong costs weeks of debugging or a rejection.</p><p><strong>A few things worth carrying forward from this article:</strong></p><p><strong>The OS is not your enemy.</strong><br>Its restrictions exist to protect users from bad actors who abuse location access. If your feature genuinely benefits the user, the OS gives you everything you need to build it. Every workaround that fights the OS instead of working with it creates a fragile system that breaks on the next OS update. Work with the restrictions — they are the constraints that separate well-designed location systems from ones that get rejected or quietly fail in production.</p><p><strong>The backend should own the logic.</strong><br>Send pings, not events. Let the backend decide entry, exit, and edge cases. Every piece of tracking logic that lives in the app creates a dependency on an app release to fix a bug. Backends can be updated silently, instantly, and without going through App Review. Design for that from the start.</p><p><strong>Motion-aware tracking is not optional for long sessions.</strong><br>If your use case involves the user being stationary for more than a few minutes, implement it. Battery drain is the fastest way to lose user trust permanently — and it will show up in your reviews before it shows up in your dashboards.</p><p><strong>Play Store and App Store are not obstacles.</strong><br>They are checkpoints that force you to have a genuine, user-beneficial reason for every sensitive permission you request. If you cannot clearly explain why your feature needs background location or a location FGS, that is a signal the feature design needs rethinking — not the declaration. The teams that treat store review as a gate to get past tend to get rejected repeatedly. The teams that treat it as a forcing function for clear product thinking tend to get accepted on the first submission.</p><p>That is what this article series is about. Use it to guide AI toward the right implementation for your specific use case, rather than starting blind and discovering the walls one by one.</p><p><em>If this was useful, a clap or follow goes a long way — it helps this reach engineers who’d actually use it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe26d67bd3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Geofencing & Background Location Tracking in React Native 2026]]></title>
            <link>https://medium.com/@varunkukade999/part-1-geofencing-background-location-tracking-in-react-native-2026-800c269a15e4?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/800c269a15e4</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 13:43:57 GMT</pubDate>
            <atom:updated>2026-08-23T13:58:31.821Z</atom:updated>
            <content:encoded><![CDATA[<p>Why every SDK, library, and hack hits the same OS walls — and what you can actually rely on.</p><p>Over the last few weeks, I built geofencing and location tracking capability at my workplace. From researching platform internals and approval requirements to architecting and building a native IOS and Android SDK from scratch. This article is a distillation of everything that journey required me to understand.</p><p><strong>What Geofencing Actually Is</strong></p><p>Geofencing is a native OS capability — available on both Android and iOS — that lets you register a virtual circular boundary around a geographic coordinate. The OS monitors the device’s position against that boundary and notifies your app on entry or exit. The detection mechanism is built into the platform. You do not need to build it.</p><p>A few production use cases that illustrate the range of this capability:</p><ul><li>Automatically surface home controls as a user approaches their residence</li><li>Notify parents when a child arrives at a known location</li><li>Trigger emergency alerts when a device enters a disaster or evacuation zone</li><li>Alert customers when a delivery driver crosses a proximity threshold</li></ul><p>Once a geofence is registered, the OS owns the monitoring. After entry is detected, you can extend into active location tracking inside the geoefence — subject to the permission model each platform enforces. The OS APIs for this exist on both platforms. What is not straightforward is everything around them.</p><p>Now that you understand what geofencing is, let me give you two real-world examples that you have almost certainly experienced yourself — one for geofencing and one for background location tracking.</p><p><strong>Location tracking — Zomato, Swiggy, Uber</strong></p><p>When you order food on Zomato or Swiggy, or book a cab on Uber, you can see your rider or driver moving live on the map — updating every few seconds. That continuous live position streaming running silently in the background on rider/driver’s device is location tracking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTwCJUuXXtJceSkXQat3XQ.png" /></figure><p><strong>Geofencing — McDonald’s Ready on Arrival</strong></p><p>When you place a mobile order on the McDonald’s app and start driving toward the restaurant, the app silently detects the moment your phone crosses a virtual boundary around the restaurant — even when your phone is locked. The kitchen gets an alert: “This customer is 2–3 minutes away. Start preparing now.” By the time you walk in, your food is ready. McDonald’s reported a 62-second reduction in wait time per customer after deploying this. That silent boundary detection is geofencing. The feature is currently live in the US only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*tQP_sGdl8QXeBSaPuHcr7g.jpeg" /></figure><p>Two different mechanisms. Two different problems. Both covered in this article.</p><p><strong>Why This Article Exists<br></strong>Background location is one of the few areas in mobile development where the OS, the platform policies, and the user’s device are all actively working against what you’re trying to build — by design. Android and iOS make background location difficult intentionally. Battery life, user privacy, and platform trust are the constraints they are optimising for. Your feature requirements are secondary to those constraints.</p><p>The engineering challenge is not implementing the API. It is building a mental model of exactly where each platform draws the line — what it permits, what it quietly throttles, what it blocks entirely, and what triggers a rejection from App Review or the Play Store — and then designing your implementation to stay on the right side of all of those lines simultaneously.</p><p>Most teams approach this by reaching for an SDK or library first. What they find is that every SDK, paid or free, hits the same OS walls. The abstraction changes. The constraints do not. Understanding the constraints is the only thing that actually transfers.</p><p>This article documents the full research, the dead ends, the platform-specific gotchas, and the conclusions — so your team starts with a clear map rather than having to rediscover the same walls.</p><p>If you want to learn how to do AI-assisted R&amp;D on such complex topics, I’ve written a separate guide: <a href="https://medium.com/@varunkukade999/how-i-deep-research-unfamiliar-react-native-android-and-ios-topics-with-ai-74ae5c55d2d3">link</a>. I used same strategies to go deep on unfamiliar platform internals efficiently.</p><p><strong>A Note on How This Article Is Written</strong></p><p>This article is intentionally light on code. AI writes code well. What AI cannot do is tell you which approach is safe to ship and will work in real world, which permission flow App Review will accept, or where the OS will silently throttle you in production. That requires the kind of judgement that only comes from having gone wrong first.</p><p>The goal is to give you enough architectural understanding and decision context to guide AI toward the right implementation for your specific use case — not to give you code to copy.</p><p>Due to enormous amount of information, I have divided it into 3 articles. This is first part.</p><p><strong>What This Article Covers</strong></p><ul><li>Different App States</li><li>How location works in Android and iOS</li><li>Location Permission priming for Android</li><li>Location Permission priming for IOS</li><li>How to implement geofencing</li></ul><h3>Different App States</h3><p>Every location and geofencing decision in this article is shaped by one underlying reality: the OS behaves differently depending on whether your app is in the foreground, background, or quit state.</p><p><strong>Foreground</strong> — app is open and visible. Full location access, no restrictions.</p><p><strong>Background</strong><br>User has switched away but not closed the app. On iOS, background is not a single state — it has two distinct phases:</p><p><strong>Suspended in background</strong><br>When the app moves to background, iOS suspends it shortly after 5 seconds. After that the app cannot execute any code, fire timers, or receive location updates. It is frozen. Suspended does not mean killed — the app is still visible in the recent apps list and the user can bring it back to foreground without seeing any restart. It is just not allowed to do any work while suspended.</p><p>This is where most implementations break. Developers assume the app is “running in background” and expect work to continue — but the app is actually suspended and doing nothing.</p><p><strong>Active in background</strong><br>iOS can keep the app awake in background, but only when something gives it a reason to stay awake. There are two different mechanisms. Mixing them up is the root of most iOS background-location confusion.</p><p>Mechanism A — short background execution time</p><p>When the app first moves to background, iOS gives it a 5 seconds to finish pending work. You can request more 30 seconds with UIApplication.shared.beginBackgroundTask. When that window expires, iOS suspends the app. This is temporary work time — not continuous tracking.</p><p>Mechanism B — continuous location assertion</p><p>If your app called CLLocationManager.startUpdatingLocation() while it was still in the foreground (or while an earlier foreground-started session is still alive), and background location is correctly configured, iOS can hold a stronger “location is active” assertion. In that case the app can stay awake in background for a long time and keep receiving GPS updates — often for as long as that session stays on.</p><p>These two mechanisms are not the same thing.<br><strong>beginBackgroundTask</strong> ≈ short extra time.<br>Foreground-started <strong>startUpdatingLocation</strong> ≈ long-lived background GPS.</p><p><strong>Quit state : </strong>app process is not running. Two different cases —</p><p><strong>OS killed the app (memory pressure, jetsam): </strong>This can happen after IOS has suspended it in background state and now due to memory pressure or for preserving battery, ios kills the app. <br><strong>User force-quit the app : </strong>This can happen when app has been swiped away from recent apps.</p><p>In both above cases, IOS can still relaunch the app in the background for specific events like geofence entry or exit. More on this in the geofencing section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*AlB-Bjy8JuwiAj-xkuUX4g.png" /></figure><p>The goal across to reliably achieve two things in as many states as possible:</p><p><strong>Geofencing</strong> — register a virtual circular boundary around a coordinate. Get notified on entry and exit regardless of app state.</p><p><strong>Location tracking inside the fence</strong> — once entry is detected, track the user’s position within the boundary to capture movement.</p><p>We address these in sequence. Geofencing first, location tracking inside the fence second.</p><h3>How location works in Android and iOS</h3><p>Before getting into geofencing or background tracking, it is important to understand how location actually works at the OS level — because every decision you make later, from choosing a geofence radius to handling permission flows, traces back to what is covered in this section.</p><p>The first thing to understand: apps do not have direct access to device location. The OS does. The OS continuously maintains location awareness using available hardware and signals — GPS, WiFi, and cellular network — falling back to the next option if one is unavailable. If any app wants location, it must first request specific permissions from the user. If the user grants permission, the app can request location from the OS and receive it. If not, the OS denies it regardless of what the app asks for.</p><p>Both Android and iOS determine location through the same three sources, falling back from most to least accurate.</p><p>Both platforms determine location through the same three sources, in order of accuracy:</p><h4><strong>1. GPS</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dlC7vEnrPtRsnyctaabWXA.jpeg" /></figure><p>Check above image of GPS. When you enable this gps in android, you allow OS to successfully query your current location through gps. If you disable this, even OS doesn’t have access to your location through GPS. Hence it can’t give it to the app even if app has been granted with the permission.</p><h4><strong>How GPS works</strong></h4><p>GPS uses radio signals from satellites orbiting Earth to calculate your exact position.</p><p>Pros: No internet required — works completely offline. Most accurate source at sub-10m precision, making it the only viable option for small area tracking like a 50m or 80m geofence radius.</p><p>Cons: Slow to get a location fix the first time — 30 to 60 seconds cold start, reduced to 2 to 3 seconds with internet via A-GPS. Drains battery fastest. Works poorly indoors or anywhere with a blocked sky view, like parking garages or dense buildings.</p><p>On Android, GPS is a hardware toggle the user controls independently. When GPS is disabled, the OS loses access to satellite-based positioning entirely — and cannot provide it to your app even if location permission has been granted. This is an important edge case to handle: permission granted does not mean GPS available.</p><h4><strong>2. WiFi — fallback if GPS unavailable</strong></h4><p>WiFi triangulates your position using nearby WiFi access point MAC addresses matched against a crowd-sourced database.</p><p>Here is how that database works. Every WiFi router has a unique identifier called a MAC address. Google has spent years driving Street View cars around the world, quietly recording which router MAC addresses were seen at which GPS-verified coordinates. The result is a massive database of hundreds of millions of routers mapped to real-world locations. When your phone scans for nearby WiFi networks, it collects a list of visible MAC addresses — routers you do not even need to be connected to, just within range — and sends that list to Google’s servers. Google cross-references those MACs and returns your approximate location based on where those routers are known to be clustered. That is your WiFi-derived location fix.</p><p>Pros: Works indoors. Gets a location fix in seconds. On Android, there is a separate “WiFi scanning” setting that allows the device to scan nearby networks for positioning purposes even when WiFi is turned off — keeping this source available without an active WiFi connection.</p><p>Cons: If both WiFi and WiFi scanning are disabled, this source becomes completely unavailable. Accuracy varies — typically 15 to 40 metres in good conditions, but can degrade to 100 metres or more in areas with sparse WiFi coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXazy0vn4Ev01exo35hRxg.png" /></figure><p><strong>3. Cellular Network</strong></p><p>Uses signal strength and timing from nearby cell towers to approximate your position.</p><p>Pros: Fastest fix, lowest battery cost, works anywhere there is a signal.</p><p>Cons: Worst accuracy of the three — typically 100 to 500 metres in urban areas, and up to 1 to 2 kilometres in rural areas where tower density is low. Completely unsuitable for small-radius geofence detection.</p><blockquote>Hence in terms of location accuracy gps &gt; wifi &gt; cellular network.</blockquote><h4>How iOS differs from Android</h4><p>iOS uses the same three sources — GPS, WiFi, and cellular — but combines them through Apple’s Core Location framework, which automatically selects the best available source based on the accuracy level your app requests. Apple also maintains their own independent WiFi router database, built the same way as Google’s — iPhones with a GPS lock quietly and anonymously record nearby router MAC addresses and their real-world coordinates over time.</p><p>The meaningful platform difference is in user control. Android exposes each source as a separate toggle. A user can disable GPS while keeping WiFi positioning active, which directly affects what your app can rely on at runtime — and which you need to account for in your implementation.</p><p>iOS gives the user no such granularity. The only control available is a single master switch — Settings → Privacy &amp; Security → Location Services — which governs all three sources together. There is no way for a user to disable GPS while keeping WiFi positioning active. Apple intentionally designed it this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HU7c5HT0aO7vrlTk.png" /></figure><p>The practical consequence: iOS location behaviour is more predictable for you as a developer, but you have less visibility into which underlying source is being used. Android gives you more to work with — and more edge cases to handle.</p><p>This distinction between the two platforms will come up repeatedly as we go deeper into geofencing behaviour and background tracking constraints.</p><h3>Location Permission priming for Android</h3><p>Before writing a single line of location code, you need to understand how Android categorises location access — because the permission you request determines what the OS will and will not give you, regardless of what your code asks for at runtime.</p><p>The most widely used library for handling permissions in React Native is <a href="https://github.com/zoontek/react-native-permissions">react-native-permissions</a>.</p><h4><strong>Foreground-only location access</strong></h4><p>If your app only needs location while it is open and visible, you request foreground location permission. Android presents the user with a native permission dialog offering “While using the app” as an option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*SSJ-BrS8SRV3LQt_" /></figure><p>If the user selects this, the OS will provide location only while your app is in the foreground. The moment the app moves to background or quit state, location access is cut off. The OS enforces this — it is not something you can work around in code.</p><p>There is, however, one legitimate exception worth knowing. Through deep research into Android developer documentation and permission behaviour, there is exactly one way to access a user’s location in background or quit state while holding only “While using the app” permission — legally, with full user consent, and in a way Play Store accepts. We will cover this later in the article. If you already know what it is, drop it in the comments.</p><p>Users can also change their permission selection at any time through device settings. Your app needs to handle that gracefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*TGbKKAXzaNX9w9vh" /></figure><h4>Background and quit state location access</h4><p>For background location access, the Android documentation covers the full permission model here: <a href="https://developer.android.com/develop/sensors-and-location/location/permissions/background">Access location in background</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTahJegPd7s3m1nTkPMBLQ.png" /></figure><p>The critical platform behaviour to understand: on Android 11 and above, the native permission dialog no longer includes an “Allow all the time” option. You cannot present a popup and have the user grant background location in one step. Instead, you must navigate the user to the device’s location settings page where they can grant “Allow all the time” themselves.</p><p>This is not optional. It is the only path Android provides for background location on modern OS versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*7L-Xi0MaBi72gQyq-v4m-w.png" /></figure><h4>Play Store approval — read this before implementing anything</h4><p>Getting background location working in code is only half the problem. Getting it accepted by the Play Store is the other half — and teams consistently underestimate this part.</p><p>Before writing your permission flow, read this policy guide in full: <a href="https://support.google.com/googleplay/android-developer/answer/9799150?hl=en">Understanding location in the background permissions</a>.</p><p>Read it line by line. Do not skim it. Every point listed there is a potential rejection reason. Our app went through the full Play Store and App Store approval process for background location — and the points below are the ones that matter most based on that real experience.</p><p>The following are not suggestions. Missing any of these will get your submission rejected.</p><h4><a href="https://support.google.com/googleplay/android-developer/answer/9799150?sjid=614740484162030974-NC#Does%20your%20app%20need%20access%20to%20location%20in%20the%20background?">Does your app need access to the location in the background?</a></h4><p>Before implementing anything, answer this honestly: is background location required for your app’s core functionality — meaning the app is broken or significantly degraded without it — or is it a convenience feature?</p><p>The Play Store makes this distinction explicitly, and reviewers enforce it. Background location is approved when it provides meaningful, direct value to the user. It is rejected when it primarily serves the app owner’s interests — analytics, advertising, or engagement tracking dressed up as a feature. User safety use cases get the highest approval priority, followed by user convenience. If your use case falls outside these, reconsider before investing in the implementation.</p><p>To validate your use case before building, use this prompt with Claude:</p><blockquote>We are trying to submit an Android app to the Play Store <br>with background location permission.</blockquote><blockquote>Here is the purpose/reason for asking for background <br>location: [“mention reason here”].</blockquote><blockquote>Here is the all-in-one guide for Android Play Store policy <br>for getting approved for background location permissions: <br><a href="https://support.google.com/googleplay/android-developer/answer/9799150">https://support.google.com/googleplay/android-developer/answer/9799150</a></blockquote><blockquote>Webfetch the above article, go through it carefully line <br>by line, and rate this out of 10 for getting the app <br>approved by the Play Store.</blockquote><p>If you have codebase access in Cursor, run the same prompt in Cursor chat so AI can validate against your full app context, not just the stated reason</p><h4><a href="https://support.google.com/googleplay/android-developer/answer/9799150?sjid=614740484162030974-NC#Prominent%20in-app%20disclosure">Prominent in-app disclosure</a></h4><p>How you ask for background location permission is as important as why you ask for it. The Play Store requires what they call a prominent in-app disclosure — a clear, dedicated screen shown to the user before the permission request, explaining exactly how their location is accessed, collected, used, and shared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkgwEzsQfE-AhDT5IHpEhg.png" /></figure><p>The recommended disclosure phrasing is:</p><blockquote>“[This app] collects location data to enable [feature], [feature], and [feature] even when the app is closed or not in use.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*vhMsvX_AhEjSuo1t" /></figure><p>The flow differs by Android version:</p><ul><li><strong>Android 10 and below</strong> — you can trigger a native permission popup directly after showing the disclosure.</li><li><strong>Android 11 and above</strong> — you cannot prompt for background location directly. After the user confirms the disclosure, you must navigate them to the app’s location settings page where they manually set it to “Allow all the time.” The disclosure screen should dismiss automatically once the permission is granted.</li></ul><p>To validate your disclosure UI before submitting, use this prompt:</p><blockquote>We are trying to submit an Android app to the Play Store <br>with background location permission.</blockquote><blockquote>Here is the purpose/reason for asking for background <br>location: [“mention reason here”].</blockquote><blockquote>Here is the prominent in-app disclosure we are showing <br>inside the app: [“describe the steps and attach UI screenshots”].</blockquote><blockquote>Here is the all-in-one guide for Android Play Store policy:<br><a href="https://support.google.com/googleplay/android-developer/answer/9799150">https://support.google.com/googleplay/android-developer/answer/9799150</a></blockquote><blockquote>Webfetch the above article, go through it carefully line <br>by line and rate this out of 10 for getting the app <br>approved by the Play Store.</blockquote><h4><a href="https://support.google.com/googleplay/android-developer/answer/9799150?sjid=614740484162030974-NC#Privacy%20policy%20both%20in%20your%20app%20and%20on%20its%20store%20listing%20page">Declaration in privacy policy</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gunppsbf02T6hE7xXrRROQ.png" /></figure><p>Your app’s privacy policy must explicitly declare how you collect, use, and share background location data. This is not a formality — Play Store reviewers open the attached privacy policy themselves and validate it against their requirements before making an approval decision.</p><p>If your existing privacy policy does not mention background location, update it before submission. This is one of the most common and most avoidable rejection reasons.</p><h4><a href="https://support.google.com/googleplay/android-developer/answer/9799150?sjid=614740484162030974-NC#Permissions%20declaration%20form">Permissions Declaration Form</a></h4><p>When you submit your app in the Play Console and background location is detected in your AndroidManifest.xml, you will be required to fill out a declaration form with two questions:</p><ol><li>What is the main purpose of your app?</li><li>Why does your app need background location access? Why is “While using the app” permission insufficient?</li></ol><p>The form suggests mentioning one feature. In practice, mentioning a maximum of two strong, well-justified features works in your favour — it gives reviewers more context and, if you are rejected, their feedback will tell you exactly which feature they had concerns with. If they push back on two, fall back to one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQeWzGOlHKNB4vwOP8mDnQ.png" /></figure><h4><a href="https://support.google.com/googleplay/android-developer/answer/9799150?sjid=614740484162030974-NC#Video%20demonstration">Video demonstration</a></h4><p>Attaching videos is mandatory after filling out the declaration form. Record the following:</p><p><strong>Permission disclosure video</strong> — show the complete flow a user follows to reach the in-app disclosure screen. Keep the disclosure visible for at least 5 seconds, then navigate to settings, grant “Allow all the time,” and return to the app.</p><p><strong>Feature video(s)</strong> — demonstrate each feature that justifies background location, one video per feature. Show the feature working as it actually does — do not stage or exaggerate. Keep each video under 1.5 to 2 minutes.</p><p>Upload all videos to a single location — Google Drive or unlisted YouTube. Name each video clearly. Ensure all links are publicly accessible before submitting.</p><h4>Additional Sign in details</h4><p>In Play Console → Monitor and Improve → Policy and Programs → App Content, find the Sign-in Details section and fill in working login credentials so the reviewer can access and test the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SqKj7-tmIcs0yiKEiccDg.png" /></figure><p>Beyond standard login instructions, add a separate entry titled <strong>“How to check Background Location Permission Disclosure”</strong> if verifying your disclosure requires steps that are not obvious from login alone — for example, if it involves restricted account states or specific setup conditions. Format it as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wE5JIaWlhQBeQwkSxNmmg.png" /></figure><p>Format:</p><blockquote>Video: [public link]<br>Steps:<br>1.<br>2.<br>3.</blockquote><p>If a reviewer can reach and verify your disclosure simply by following the standard login flow, this additional entry is not needed. Use your judgement based on how your app’s disclosure is triggered.</p><h4>The Consistency Rule — Most Important Point in This Section</h4><p>Your core purpose statement, your prominent in-app disclosure, your privacy policy, and your video demonstrations must all describe the same thing, using consistent language.</p><p>Reviewers cross-check all four against each other. If any one of them contradicts or diverges from the others — even subtly — the submission is rejected. Lock the core reason early, write it down clearly, and use it as the single source of truth across every submission artifact.</p><h3>Location Permission priming for IOS</h3><p>iOS handles location permission differently from Android — both in how the dialogs work and in how the App Store review process operates. Understanding the exact flow before you build saves significant rework later.</p><p>The most widely used library for handling permissions in React Native is <a href="https://github.com/zoontek/react-native-permissions">react-native-permissions</a>.</p><p><strong>Foreground-only location access</strong></p><p>On iOS, you can ask the user for location permission through the following native popup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*3eL-6SdqPSJnXAjA" /></figure><p><strong>iOS 14 and above (modern dialog)</strong></p><p>The permission dialog on iOS 14 and above has three buttons — Allow Once, Allow While Using App, and Don’t Allow — along with a map thumbnail and a Precise location toggle.</p><p>The Precise toggle is worth understanding separately. When Precise is on, iOS uses GPS to determine location. When Precise is off, it falls back to WiFi and cellular, giving only an approximate location at roughly city level — around 3km radius. For any feature that depends on small-radius accuracy, Precise must be on. If your geofence radius is 50m or 80m, approximate location is completely unusable. You cannot force the user to turn Precise on, but you can explain why it matters during your permission priming screen.</p><p>Selecting “Allow While Using App” gives your app location access only while it is in the foreground. The moment the app moves to background or quit state, location access stops.</p><p><strong>iOS 13 and below (legacy dialog)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*MlVGp4Wm5v00svTu.png" /></figure><p>Older devices see a simpler two-button dialog — Don’t Allow and Allow — with no map preview and no Precise toggle. “Allow” grants either foreground or background access depending on what your app requested. This applies to a very small percentage of active devices today, but worth being aware of.</p><p>Users can change their location permission at any time through device settings. Handle this state change gracefully in your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*bvTttFW1LJKUObXw.jpg" /></figure><h4>Background location access</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*VWQssjCTJ8Eyv_ciovbhkQ.jpeg" /></figure><p>On iOS, background location is not granted in a single step. Apple enforces a deliberate two-step flow:</p><p><strong>Step 1</strong> — Your app calls requestWhenInUseAuthorization(). The user sees the standard dialog and selects &quot;Allow While Using App.&quot;</p><p><strong>Step 2</strong> — Your app then calls requestAlwaysAuthorization(). iOS shows a separate upgrade dialog asking the user to choose between &quot;Keep Only While Using&quot; or &quot;Change to Always Allow.&quot;</p><p>Apple introduced this two-step flow intentionally — to ensure users make a conscious, separate decision about background access rather than accidentally granting it during the initial permission prompt.</p><p>You cannot skip Step 1 and request Always permission directly. The two-step sequence is a hard iOS requirement, not a convention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMTrhGNdj8gLJSSjU7kagQ.png" /></figure><p>IOS 12 and below experience:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*AYooOKskQBUYgEJW.png" /></figure><p><strong>Prominent in-app disclosure for iOS</strong></p><p>You can reuse the same prominent in-app disclosure screen you built for Android on iOS as well. When it comes to the actual permission flow after the disclosure, you have two options:</p><p><strong>Option 1 — Common experience across both platforms</strong><br> After the user confirms the disclosure, navigate them to the app’s location settings on both Android and iOS, where they can manually change to “Always Allow.” This keeps your implementation simple and avoids maintaining separate platform flows.</p><p><strong>Option 2 — Platform-specific experience</strong><br> On Android, navigate to settings. On iOS, trigger the native two-step upgrade popup directly inside the app.</p><p>If you want to keep things simple and avoid handling different Android and iOS version logic separately, Option 1 is the recommended path. Navigating to settings works reliably across all OS versions on both platforms.</p><h4><strong>IOS App store guidelines for background location access:</strong></h4><p>The App Store does not have a separate declaration form like the Play Store does. There is no structured submission checklist to fill out. However, the quality of justification Apple expects is equivalent — and the review process is just as thorough.</p><p>The same four elements apply:</p><p><strong>1. Core purpose justification</strong><br> Apple expects a clear explanation of why background location is required for your core feature and why “While Using the App” permission alone is insufficient. Use the same one or two features you documented for Android.</p><p><strong>2. Prominent in-app disclosure</strong><br> Reuse the same disclosure experience from Android. No need to build a separate iOS flow.</p><p><strong>3. Privacy policy</strong><br> Apple does not explicitly require a privacy policy declaration the way Google does, but reviewers may check it. Keep your privacy policy updated with background location usage regardless.</p><p><strong>4. Video demonstration</strong><br> Record the same set of videos as Android — one showing the disclosure flow, and one or two showing each feature that uses background location.</p><p><strong>How to provide all this information to Apple</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnmucA-4Nu7JW_22llypkA.png" /></figure><p>When creating a new release in TestFlight or submitting a new version in App Store Connect, you will see a Notes field for the reviewer. This is your only channel to communicate everything — sign-in credentials, purpose, feature explanations, and video links. Apple reviewers read these notes before opening your app. Make them clear, structured, and complete.</p><p>Use this format:</p><pre>TEST ACCOUNT FLOW<br>[Step by step sign-in instructions using the credentials above]<br><br>LOCATION PERMISSION FLOW<br>- We first request &quot;While Using the App&quot; location only<br>- &quot;Always&quot; is never force-requested on first launch<br>- Our &quot;Always&quot; disclosure appears only after the user <br>  grants &quot;While Using the App&quot; permission<br><br>HOW TO SEE THE ALWAYS DISCLOSURE <br>(Follow bg_location_permission_disclosure.mov)<br>[Step by step instructions to reach and view the <br>in-app disclosure inside the app]<br><br>WHY ALWAYS LOCATION IS NEEDED<br>[What your app does and why &quot;Always&quot; location is <br>required. Keep to 2-3 sentences maximum]<br><br>VIDEOS:<br>bg_location_permission_disclosure.mov | <br>bg_location_feature1.mov | <br>bg_location_feature2.mp4<br><br>Feature 1: [Feature title] (bg_location_feature1.mov)<br>What the video shows: [Step by step explanation]<br>Why this matters: [User value]<br>Why Always is required: [Why &quot;While Using&quot; is insufficient]<br><br>Feature 2: [Feature title] (bg_location_feature2.mp4)<br>What the video shows: [Step by step explanation]<br>Why this matters: [User value]<br>Why Always is required: [Why &quot;While Using&quot; is insufficient]</pre><p>Apple reviewers sign in to your app, verify the permission disclosure themselves, watch the attached videos, and evaluate whether your use case genuinely justifies background access before making their decision. Be accurate in both the videos and the notes. Do not exaggerate or stage any part of the flow — reviewers are experienced and will notice.</p><h3>How to implement Geofencing?</h3><p>Geofencing is not something you build — it is something the OS provides. You register a set of coordinates and a radius with the OS. The OS creates a virtual boundary, monitors the device’s position against it using whatever location signals are available — GPS, WiFi, or cellular — and delivers entry and exit events to your app when a boundary transition happens. Your app does not need to be open for any of this to work. The OS runs the monitoring independently.</p><p>What you are responsible for is setting the right conditions so those events are delivered reliably, across all app states, on both platforms. That is where the real implementation work lives.</p><p><strong>What Geofencing Requires on Android and iOS:</strong></p><p><strong>1. Always Allow location permission — non-negotiable on both platforms</strong><br>On iOS, “Always Allow” is required both to register geofences and to receive entry and exit events reliably. Without it, geofencing on iOS is effectively non-functional.</p><p>On Android, geofences can technically be registered with “While Using the App” permission, but transition events will not be delivered when the app is in background or killed state. For geofencing to work across all app states on Android, “Always Allow” is required.</p><p>The reason this permission matters so much is tied directly to how geofencing works. Once geofences are registered, the OS monitors boundaries on your behalf — your app does not need to be running. “Always Allow” is what gives the OS permission to wake your app and deliver events even when it is completely closed. Without it, the OS has no authority to do so.</p><p><strong>2. Optionally required</strong></p><p>Beyond the permission itself, there are several device-level conditions that affect how accurately and how quickly geofence events are delivered. None of these are hard requirements — geofencing will still function without them — but the impact on real-world accuracy is significant enough that you should communicate them to the user.</p><p><strong>Android — GPS enabled<br></strong>The single biggest accuracy factor on Android. With GPS, you get sub-10m precision. Without it, the OS falls back to WiFi (15–40m) or cellular (100–500m). For a geofence with an 80m radius, cellular accuracy makes boundary detection unreliable. Communicate the importance of GPS to the user and prompt them to enable it if it is off. If they decline, geofencing will still work — just with degraded accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_Kwbdi-3Nk0fsjarxJnCg.png" /></figure><p><strong>Android — Power Saving Mode<br></strong>Global power saving mode reduces location update frequency and can delay geofence event delivery. Technically worth addressing — but too invasive to ask users to disable a system-wide setting. Most users will not comply, and the ask damages trust without reliable payoff. Skip this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvOrcbrK2cy2x1IUokd5FQ.png" /></figure><p><strong>Android — Per-app battery optimisation set to Unrestricted<br></strong>Android applies background processing restrictions to individual apps as part of battery management. When your app is restricted, geofence event delivery in background can be delayed or dropped. Ask the user to set your app to “Unrestricted” in battery settings. This is a targeted, app-specific ask — users are more likely to comply with this than a system-wide setting change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csfM_mltF5HNw0GfCi1U5Q.png" /></figure><p><strong>iOS — Precise Location enabled<br></strong>iOS allows users to grant approximate location instead of precise location, giving only city-level accuracy at roughly 3km radius. For geofencing with a radius of 70–150m, approximate location makes boundary detection unreliable. Check whether Precise Location is enabled and prompt the user to turn it on if it is not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PfJ4XijkP0-Y7rOj.jpg" /></figure><p><strong>iOS — Background App Refresh<br></strong>Background App Refresh being disabled reduces the time available for background tasks and can delay geofence events. However, iOS manages this automatically and it only degrades during Low Power Mode, which is a temporary user-initiated state. Not worth interrupting the user flow for. Skip this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SE8FNF_yuqz_ktao4Uj-lQ.png" /></figure><h4>Decision Framework: What to Ask, What to Skip</h4><p>Rather than prompting users for everything, be deliberate. Here is how to think about it:</p><p><strong>Must ask — geofencing does not work reliably without this:</strong></p><ul><li>Always Allow location permission on both platforms</li></ul><p><strong>Worth asking — high impact on accuracy:</strong></p><ul><li>GPS enabled on Android — the difference between sub-10m and 100–500m accuracy</li><li>Precise Location on iOS — the difference between 80m radius detection working or not</li></ul><p><strong>Ask if timing sensitivity matters for your use case:</strong></p><ul><li>Per-app battery optimisation on Android — directly affects how quickly events are delivered in background</li></ul><p><strong>Skip entirely:</strong></p><ul><li>Power Saving Mode on Android — system-wide, too invasive, low compliance rate</li><li>Background App Refresh on iOS — managed by the OS, only degrades temporarily, not worth the interruption</li></ul><p>The underlying principle: ask for conditions that have a material, direct impact on your feature working correctly. Every additional ask you make reduces user trust and compliance with the asks that actually matter. Be selective.</p><h4>Geofencing Libraries and SDKs — What We Evaluated and What Actually Works</h4><p>When we started researching geofencing implementation options in React Native, we found several libraries and SDKs at different points on the spectrum from abandoned open source to fully managed paid solutions. Here is a complete evaluation of everything we tried, what worked, what did not, and the reasoning behind our final decision.</p><p><strong>1. </strong><a href="https://github.com/mauron85/react-native-background-geolocation"><strong>mauron85/react-native-background-geolocation</strong></a><strong> — Do not use</strong></p><p>Pros: None worth mentioning.</p><p>Cons:</p><ul><li>Built for old React Native versions and uses deprecated native Android and iOS libraries. The Android native code still targets compileSdkVersion = 28 and targetSdkVersion = 28 — which is Android 9. Modern Android requires targeting SDK 34+.</li><li>Native code is written in Java instead of Kotlin, which is the outdated pattern.</li><li>The Android and iOS ecosystems have changed significantly over the last several years and this library has not kept up.</li><li>No one has been actively maintaining it for years. It is effectively a dead library.</li></ul><p>Not worth investing time in, even if you are considering forking it.</p><p><strong>2. </strong><a href="https://github.com/hariks789/react-native-background-geolocation"><strong>hariks789/react-native-background-geolocation</strong></a><strong> — Do not use</strong></p><p>This is a fork of a fork — originally forked from darron1217/react-native-background-geolocation, which was itself forked from mauron85/react-native-background-geolocation.</p><p>Pros: None worth mentioning.</p><p>Cons:</p><ul><li>Does not include geofencing at all. The repo itself says in its Geofencing section: “Try using react-native-boundary. Let’s keep this plugin lightweight as much as possible.” — confirming it was never designed for geofencing.</li><li>Still uses the same outdated native dependencies as the original — compileSdkVersion = 28 and targetSdkVersion = 28, which is Android 9. Modern Android requires targeting SDK 34+.</li><li>Native code is written in Java, not Kotlin.</li><li>Last release was v0.7.0 in May 2022 — over 3 years ago with no activity since. Only 14 stars and 9 forks.</li><li>Before you can even use it, you have to handle background location permissions yourself for all Android and iOS versions.</li><li>Would require implementing complete native geofencing from scratch anyway, making the fork pointless.</li></ul><p>Do not go down this path.</p><p><strong>3. </strong><a href="https://github.com/rn-org/react-native-geofencing"><strong>rn-org/react-native-geofencing</strong></a><strong> — Promising, but not production-ready on its own</strong></p><p>Pros:</p><ul><li>Last commit was around nine months ago, meaning it was being actively maintained until recently.</li><li>We set it up, tested geofencing, and it worked correctly in both foreground and background states.</li><li>Uses up-to-date native dependencies with no deprecated libraries.</li><li>Does not handle permissions internally — which is fine since we handle permissions in our app anyway.</li></ul><p>Cons:</p><ul><li>Did not work in the killed or quit state, which was a hard requirement for us.</li></ul><p>If killed state support is not a requirement for your use case, this library is a reasonable starting point for development and concept validation. If it is a requirement, this is not a production-ready solution on its own.</p><p><strong>4. </strong><a href="https://transistorsoft.com/shop/react-native-background-geolocation"><strong>Transistor Software — react-native-background-geolocation</strong></a><strong> — Best complete option</strong></p><p>Pricing: One-time perpetual license — $399 for one app or $599 for three apps. All features are available for free on debug builds. A paid API key is only required for release builds, meaning you can fully evaluate it before committing.</p><p>Pros:</p><ul><li>Actively maintained since inception. The owner regularly monitors and responds to GitHub issues.</li><li>Excellent documentation. The wiki explains in depth how the SDK works internally.</li><li>Handles all location permission flows automatically for all Android and iOS versions.</li><li>Geofencing works correctly in foreground, background, and quit state on both Android and iOS when set up correctly.</li><li>Includes an intelligent motion detection algorithm that saves battery during location tracking — especially valuable on iOS where background battery constraints are tighter.</li><li>Maintains its own SQLite database to store geofences beyond the OS limits — 20 on iOS and 100 on Android. You can register thousands of geofences and the SDK intelligently swaps them in and out with the OS based on the user’s proximity.</li><li>Includes built-in location tracking inside a geofence — covers the second half of what this article addresses.</li></ul><p>Cons:</p><ul><li>Native SDK is not open source, so no customisation is possible beyond what the SDK exposes through its API.</li></ul><p><strong>5. </strong><a href="https://radar.com/product/geofencing"><strong>Radar</strong></a><strong> — Enterprise-grade, fully managed</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WRzD9WEIqTRfyIr_QCWPQ.png" /></figure><p>Pros:</p><ul><li>Offers everything the Transistor SDK offers and more.</li><li>Highly accurate. While standard OS geofencing works reliably only at 100–200m radius, Radar claims accuracy down to 10–20m. This is achieved not through OS geofencing APIs but through continuous location polling.</li><li>A full-fledged company built entirely around location tracking — well maintained, accurate, and thoroughly documented.</li><li>Effectively a fully managed solution. Good for teams that do not want any in-house location engineering and are comfortable paying for it.</li></ul><p>Cons:</p><ul><li>Subscription-based commercial pricing.</li><li>No sandbox or trial account to test before onboarding. You have to get fully onboarded before you can evaluate it properly.</li></ul><p><strong>What We Ended Up Doing</strong></p><p>We forked rn-org/react-native-geofencing as a starting point, deeply studied and reverse engineered the features of both the Transistor Software SDK and Radar, and built our own full-fledged native Android and iOS SDK — combining the best ideas from both with our own customisations on top.</p><p><strong>What You Should Do</strong></p><p><strong>If you are validating the concept:</strong><br>Start with Transistor SDK example app on a debug build. It will get you up and running quickly.</p><p><strong>If you need a production-ready solution and are comfortable with a one-time cost &amp; less customization:</strong><br>Go with the <a href="https://transistorsoft.com/shop/react-native-background-geolocation">Transistor Software SDK</a>. It handles everything — permissions, geofencing, location tracking, quit state, battery optimisation — across both platforms. The documentation is thorough, the SDK is battle-tested, and the one-time fee is worth avoiding weeks of in-house engineering. For most teams, this is the right call.</p><p><strong>If you need 10–20m radius accuracy and want a fully managed solution with zero in-house engineering:</strong><br><a href="https://radar.com/product/geofencing">Radar</a> is the option. Be prepared for subscription pricing and a sales-led onboarding process before you can test anything.</p><p><strong>If you want full control, no ongoing costs, and are willing to invest the engineering time:</strong><br>Fork <a href="https://github.com/rn-org/react-native-geofencing">rn-org/react-native-geofencing</a>, study how Transistor and Radar work internally, and build your own SDK. With AI, this is significantly more achievable today than it was two years ago. You end up with something fully customised to your needs with no external dependency or recurring cost.</p><p><strong>Do not spend time on mauron85 or hariks789. Both are dead ends.</strong></p><h4>Geofencing Strategy</h4><p>With the right library or SDK chosen, the next question is how to structure your geofencing implementation correctly. This section covers the full strategy — from registration to event handling — including the edge cases that are not obvious until you hit them in production.</p><p><strong>Registration Strategy</strong></p><p>Whenever the user opens the app and has “Always Allow” permission granted, register your geofences with the OS. The coordinates and radii for those geofences should come from your backend — not be hardcoded in the app. This keeps your backend as the single source of truth for exactly which coordinates and radii are actively registered at any point.</p><p>Both platforms impose OS-level limits on how many geofences can be active simultaneously — 20 on iOS and 100 on Android. How you handle this depends on your scale.</p><p><strong>If you are using the Transistor Software SDK:</strong><br>The SDK maintains its own SQLite database to store an unlimited number of geofences, overcoming the OS limits entirely. You can register thousands of geofences and the SDK intelligently swaps them in and out with the OS based on the user’s current location. You just keep providing coordinates to the SDK and it handles the rest.</p><p><strong>If you are building your own SDK:</strong></p><p><strong>Case 1 — Within OS limit</strong><br>If your total number of geofences will always stay within the OS limit, you do not need any swapping strategy. Register all geofences once and the OS will track all of them. When the user visits any of those locations — even if the app is closed — the OS delivers the entry or exit event correctly. The OS does this efficiently using low-power signals like cell towers and WiFi when the user is far from any boundary, and only ramps up location accuracy when the user is actually approaching one. You pay no significant battery cost for geofences the user is nowhere near.</p><p><strong>Case 2 — Exceeding OS limit</strong><br> If your geofences change based on the user’s location and can exceed the OS limit, you need a dynamic management strategy:</p><ul><li>Maintain a local SQLite database to store all your geofence coordinates. Storing them in SQLite does not mean the OS will track them — it is just your local store.</li><li>From the coordinates in SQLite, register only the nearest ones with the OS based on the user’s current location.</li><li>Every time the backend sends an updated set of coordinates based on the user’s current location:</li><li>Register any new coordinates not already registered with the OS.</li><li>Deregister any existing OS geofences that are no longer in the new set.</li></ul><p>This way, SQLite holds hundreds of coordinates but only the relevant nearest ones are actively tracked by the OS at any point.</p><p>One important clarification: within the OS limit, the OS monitors all registered geofences at all times. If you try to register more than the limit, the behaviour is not guaranteed — iOS does not automatically pick the closest ones for you. Extra registrations may be silently ignored or fail. This is why you need to manage the list yourself — only register what is within the OS limit at any given time, based on the user’s current location, and update it as the user moves.</p><p>Treat the OS geofence registry as a live, managed list — not a set-and-forget configuration. Keep it tightly in sync with what the backend considers the user’s relevant nearby geofences.</p><p><strong>Q&amp;A — Edge Cases That Matter in Production</strong></p><p><strong>1. What happens if the user is already inside a geofence at registration time?</strong></p><p>This catches many developers off guard. If you register a geofence and the user is already physically inside that boundary at the time of registration, the OS does not automatically fire an entry event — it only fires on boundary crossings.</p><p>The handling differs by platform:</p><ul><li><strong>Android</strong> — provides a built-in flag during geofence registration that tells Location Services to immediately fire an entry event if the device is already inside the geofence at the time of registration. No extra work needed.</li><li><strong>iOS</strong> — no such flag exists. After registering a geofence, you need to explicitly ask iOS to check the user’s current state relative to that region. iOS will respond asynchronously telling you whether the user is already inside, outside, or in an unknown state. If the response says inside, treat it as an entry and handle it accordingly.</li></ul><p><strong>2. Minimum radius</strong></p><ul><li>Apple does not publish a hard minimum, but from developer experience, anything below 200m starts becoming unreliable.</li><li>Google’s official docs recommend a minimum of 100–150m for consistent detection, based on typical WiFi location accuracy.</li><li><strong>Practical rule:</strong> If your use case needs accuracy below 50m, do not rely on native OS geofencing on either platform. Use continuous location polling instead.</li></ul><p><strong>3. Exit event delay</strong></p><p>Exit event delay does not happen only due to small geofence radius. It can also happen because of how the OS works by design. On iOS, the system waits for the user to cross the boundary and remain on the other side for at least 20 seconds before sending the exit notification. This is intentional — to avoid unnecessary events caused by GPS jitter near the boundary. Your backend and testing strategy needs to account for this delay and not treat a missing exit event as a bug.</p><p><strong>4. What happens when the user revokes location permission?</strong></p><p>If the user revokes “Always Allow” after geofences are registered, the OS stops delivering geofence events. Your app needs to detect the permission change once it is open and handle the state gracefully.</p><ul><li><strong>If the user degrades to “Allow While Using”</strong> — you can have a fallback. Use a library like <a href="https://turfjs.org/">turf</a> to create virtual boundaries in code and track entries and exits yourself by comparing the user’s location against those boundaries. This works when the app is in foreground and background, but not in quit state. It is better than no tracking at all, and here you are not relying on the OS geofencing mechanism at all.</li><li><strong>If the user selects “Don’t Allow”</strong> — nothing can be done. Once the app is open and you detect this, deregister all geofences from the OS and stop any location tracking entirely.</li></ul><p><strong>5. What happens to geofences when the app is reinstalled?</strong></p><ul><li><strong>Android</strong> — geofences are cleared and must be re-registered in the following cases: device reboot, app uninstalled and reinstalled, app data cleared, or Google Play Services data cleared. A regular app update without uninstalling does not clear geofences. Always re-register geofences on app launch as a safety measure to cover all these scenarios reliably.</li><li><strong>iOS</strong> — region monitoring persists across both app updates and reinstalls at the OS level. No extra work needed.</li></ul><p><strong>6. Geofence expiry on Android</strong></p><p>Android lets you optionally set an expiration duration for each geofence. Once that duration passes, Location Services automatically removes it. If you want geofences to stay active indefinitely, explicitly set the expiration to NEVER_EXPIRE when registering. Always be explicit about this — relying on default behaviour here can lead to geofences silently disappearing and events stopping without any obvious reason.</p><p><strong>7. Can geofences be registered from background or quit state?</strong></p><ul><li><strong>Quit state</strong> — where the app is completely killed — neither Android nor iOS can register new geofences since no code is executing.</li><li><strong>Android background state</strong> — registration is possible since the API only requires a Context, which background components like services and broadcast receivers have.</li></ul><p>This means if your backend sends new coordinates while the app is in quit state, you cannot act on them until the user opens the app. Always register or refresh geofences on every app open to ensure they are up to date.</p><p><strong>8. What happens when the device has no network connectivity? -&gt; This will be answered in later part of article.</strong></p><p><strong>9. Do geofences survive a device reboot?</strong></p><ul><li><strong>Android</strong> — geofences do not survive a device reboot by default. You must listen for the device boot broadcast and re-register your geofences when the device restarts. If you skip this, your geofences silently disappear after a reboot and you will spend hours debugging why events stopped firing.</li><li><strong>iOS</strong> — region monitoring persists across reboots automatically. No extra work needed.</li></ul><p>Both Transistor SDK and Radar handle Android reboot re-registration out of the box.</p><p>Below 50m, native OS geofencing is the wrong tool entirely — the OS simply cannot reliably detect crossings at that precision and exit events get delayed significantly. Use continuous location polling instead, which we cover after we finish geofencing.</p><p><strong>Note on location accuracy with geofence events:</strong> when the OS delivers a geofence entry or exit event, it may include the last known location — which could be stale. Do not rely on it. Always fetch a fresh location fix immediately after receiving the event before sending anything to your backend.</p><h4>How geofencing works at OS level?</h4><p>This is about what the operating system actually does after your app registers a geofence. Not your app logic, not your SDK — the OS services that store the fence, track the user, and fire entry/exit.</p><p><strong>What “registering a geofence” really means</strong></p><p>When your app calls the geofencing API, nothing runs inside your app process to watch the user.</p><p>Instead:</p><ol><li>Your app sends a geofence definition to a system location service.</li><li>That service stores the fence (center lat/lng, radius, identifiers, which transitions you care about: enter, exit, dwell).</li><li>Your app may exit or be killed. The fence stays registered in the system service.</li></ol><p>On Android, this usually goes through Google Play Services (GMS) Location Services, which sits on top of the Android location stack. Your geofences live in GMS, not in your APK’s memory.</p><p>On iOS, this goes to locationd — Apple’s system location daemon. Your regions live there, not in your app.</p><p>So “registered with the OS” means: stored in a persistent system service that outlives your app process.</p><p><strong>How the OS knows where the user is</strong></p><p>The OS does not keep GPS on 24/7 for geofencing. That would drain the battery in hours.</p><p>Location comes from a pipeline of sources, merged into one “best estimate”.</p><p><strong>Android: Fused Location Provider (FLP)</strong></p><p>GMS Fused Location Provider picks which sources to use based on:</p><ul><li>App foreground vs background</li><li>Battery saver / Doze mode</li><li>Motion state (still vs moving)</li><li>What permissions you granted</li><li>What other apps are requesting</li></ul><p>When your app is foreground and actively requesting high-accuracy location, FLP uses GPS heavily. Updates are frequent.</p><p>When your app is background or killed, FLP throttles updates. GPS is used less often or not at all. Wi‑Fi scans and cell tower fixes dominate. Updates arrive in batches, sometimes minutes apart.</p><p><strong>iOS: Core Location + </strong><strong>locationd</strong></p><p>Same idea, different name. locationd decides when to wake radios and how accurate a fix needs to be.</p><p>For region monitoring (circular geofences), iOS uses a low-power monitoring mode. It does not run continuous GPS for every registered region. It relies heavily on cell tower changes and Wi‑Fi network changes to infer “user moved enough that we should re-check regions.”</p><p>When your app is foreground with active high-accuracy tracking, locationd can use GPS more aggressively and re-check regions more often</p><p><strong>How entry/exit is actually computed</strong></p><p>The OS does not draw a circle on a map and watch a dot cross the line in real time.</p><p>Internally it works more like this:</p><ol><li>Store each geofence as: center point + radius (+ optional dwell time on Android).</li><li>Periodically (or on a “significant movement” signal), get a location fix from the fused pipeline.</li><li>Compute distance from that fix to the geofence center (haversine or equivalent).</li><li>Compare to the previous state: was the user inside or outside?</li><li>If state changed (outside → inside = ENTER, inside → outside = EXIT), emit an event.</li></ol><p><strong>Dwell (Android only)</strong>: You can ask for an event only after the user stays inside for N milliseconds. The OS tracks “inside since timestamp” internally.</p><h4>Accuracy of events:</h4><p><strong>App open (foreground) while entry/exits</strong></p><ul><li>The OS wakes GPS more often and Location fixes are fresh and accurate.</li><li>Region re-checks happen closer to real time.</li><li>Enter/exit events arrive sooner and closer to the true boundary crossing.</li></ul><p><strong>App background while entry/exits.</strong></p><p>If you keep the location fetch active even in app background state, OS will keep the GPS active and hence you will see very good accuracy. Otherwise it will fallback to WiFi and Cellular Data and accuracy can be worse similar to quit state entry/exits.</p><p><strong>App Quit State while entry/exits</strong></p><p>This can happen due to OS killed the app (memory pressure, jetsam) or User force-quit the app (swiped away from recent apps)</p><p>In both of above situations os can relaunch the app in the background for only specific events:</p><ul><li>Outer geofence <strong>ENTER</strong> — user arrives at the tracked location</li><li>Outer geofence <strong>EXIT</strong> — user leaves the tracked location</li></ul><p><strong>IOS relaunch from quit state story:</strong></p><p>Now ios relaunched app in background for specific events, it keeps the app in background only for short time and hence we cannot track continously. Even if we have <strong>startUpdatingLocation</strong> running/gps active, IOS doesn’t keep app in background for consistent long periods. It suspends it.</p><p>There are two completely different stories.</p><ol><li>User opens the app (foreground). Your code starts continuous location: <strong>startUpdatingLocation</strong>(). User presses Home / switches apps. App goes to background, but location is already running. Because location updates were started while the app was in foreground and allowed to hold a stronger location session, iOS can keep the process awake and keep GPS delivery going for a long time. What you observe in testing: is Arrival / pings continue, App stays “alive” in background for longer duration, it feels like background tracking “just works”.</li><li>App is quit (OS killed OR user force-quit). Geofences were already registered earlier. User later crosses a registered boundary. iOS relaunches your app in background just to deliver ENTER or EXIT. Here ios gives you a short wake to handle that event. You can show a local notification, send a ping, start some work. But this wake is not the same as Story 1.</li></ol><p><strong>Apple engineers have been explicit about this 2nd story: </strong>You may call <strong>startUpdatingLocation</strong>() from background after a region wake. Core Location may start updates. But iOS does NOT give you the same long-lived “stay awake” assertion you get when that call was made in foreground. After the allowed background time is spent, the app is suspended again. While suspended, your JS/native timers freeze. You are not tracking.</p><p><strong>Typical budget on this path (current practical model): </strong>~10 seconds for the geofence / region wake work + up to ~30 seconds more.<br>= about 40 seconds of useful execution at best</p><blockquote>References: Apple forum</blockquote><blockquote>1) Starting location updates in background does not keep the app awake the way a foreground start does: <a href="https://developer.apple.com/forums/thread/10774">https://developer.apple.com/forums/thread/10774</a></blockquote><blockquote>2) Modern guidance: continuous updates generally need to be started in foreground; region/geofence wakes are not the same as that path: <a href="https://developer.apple.com/forums/thread/776698">https://developer.apple.com/forums/thread/776698</a>, <a href="https://developer.apple.com/forums/thread/787607">https://developer.apple.com/forums/thread/787607</a></blockquote><blockquote>3) Separate iOS 16.4+ privacy / continuous-location throttling discussion<br>(blue indicator / accuracy / distance filter): <a href="https://developer.apple.com/forums/thread/726945">https://developer.apple.com/forums/thread/726945</a></blockquote><p>What <strong>Transistor Software SDK offers for IOS:</strong></p><p><strong>In addition to above, SDK has internal stationary geofence exit:</strong> The SDK sets up its own ~200m boundary around the last known position before the app terminates (requires stopOnTerminate: false). If the user moves more than ~200m from that point, the app relaunches in background.</p><p>Note: even with stopOnTerminate: false, the SDK&#39;s ~200m stationary boundary only helps detect large movement after force-quit. It cannot resume tracking inside a primary geofence where the user is already present and has quit the app.</p><p><strong>Killed-State Geofence Entry — What Actually Determines Reliability on Android and IOS</strong></p><p>After extensive killed-state testing, one OS fact became impossible to ignore: OS does not keep GPS running for your geofences when the app is killed. GPS is the most accurate source — and the most expensive for battery — so for region monitoring in killed state, OS relies on cheaper signals first.</p><p><strong>How OS determines your location for geofencing when app is killed</strong></p><p>OS uses three sources in order of accuracy:</p><ul><li><strong>GPS</strong> — only used if another app on the device is already actively using it. If Apple/Google Maps with navigation is open during your fence crossing, OS has a hot GPS fix and your geofence fires almost immediately.</li><li><strong>WiFi</strong> — does not need to be connected to a router. Just having WiFi enabled is enough. OS scans nearby access points and uses their MAC addresses to determine location. This is the sweet spot for geofencing accuracy.</li></ul><blockquote>Note: Android has special “WiFi scanning config” in settings which scans for wifi even if wifi is off.</blockquote><ul><li><strong>Cellular network</strong> — least accurate. Used as a last resort when both GPS and WiFi are unavailable.</li></ul><p>You cannot force OS to run continuous GPS just for your killed app’s geofences. The OS decides the source based on what is available and what other apps are doing.</p><p><strong>How geofence radius must account for this</strong></p><p>The source OS uses directly determines what radius will work reliably:</p><p>GPS (another app active) — 50–100m<br>WiFi enabled- 100–200m<br>Cellular only (WiFi off) — 200m+</p><p>You cannot change the radius dynamically based on which source OS is using — you register one radius and it applies regardless. OS recommendation is <strong>200m+</strong> as the safe choice that works across all conditions.</p><p>Our real test results confirmed this:</p><ul><li><strong>100m radius, WiFi on (not connected), cellular for internet</strong> → app relaunched from killed state 100% of the time</li><li><strong>100m radius, WiFi off, cellular only</strong> → app relaunched only 1–2 out of 5 attempts</li><li><strong>250m+ radius, WiFi off, cellular only</strong> → app relaunched 100% of the time</li></ul><p><strong>The real lesson from testing</strong></p><p>We spent considerable time iterating through code changes trying to fix geofence reliability — only to eventually discover the code was never the problem. The way we were testing was wrong.</p><p>When the app is open or in background and consistently consuming GPS, the OS will always deliver geofence events correctly. That gives a false sense of confidence. The real challenge only appears in killed state, where accuracy depends entirely on environmental factors you do not control.</p><p>If app is open or in background → OS uses GPS consistently → events are reliable → do not use this as your reliability benchmark.</p><p>If app is killed → OS uses whatever signal is cheapest and available → reliability varies by environment.</p><p><strong>Correct test setup for OS killed-state geofence</strong></p><p><strong>Setup:</strong> radius 200m · Always permission · Precise Location on (for ios) · WiFi enabled (does not need to be connected)</p><p><strong>Steps:</strong></p><ol><li>Confirm geofence is registered with OS</li><li>Swipe-kill the app</li><li>Move at least 200–300m past the edge of the geofence and stay outside for at least 5 minutes</li><li>Enter the fence and dwell for at least 20–30 seconds — do not open the app</li><li>App should relaunch in background</li></ol><p>If the app does not relaunch after following these steps exactly, the issue is in your code. Fix that before testing other variables. Between each test, allow a few minutes — consecutive rapid tests produce unreliable results as the OS needs time to reset its geofence state.</p><h4>CRITICAL: What we fixed on IOS to make killed-state geofencing reliable</h4><p>Two things were missing that caused geofence events to be lost or never delivered after the app was killed.</p><p><strong>1. Re-register regions with OS on every launch</strong></p><p>On every app launch from killed state — whether the user opens it manually or iOS relaunches it for a geofence event — you must re-register all geofences with the OS immediately using . Do not assume previously registered regions survived the kill.</p><p><strong>2. Call </strong><strong>requestStateForRegion before React Native boots</strong></p><p>After re-registering, immediately call requestStateForRegion for all regions. This asks iOS to check whether the user is currently inside any boundary and synthesize an entry event if so. This covers the case where the user was already inside a geofence when the app was killed — iOS will not fire ENTER on its own, so you must request the state check to detect it.</p><p><strong>Critical ordering:</strong> both of these must happen before React Native boots. If you bootstrap geofencing after the RN bridge starts, you risk missing the entry event in the brief background window iOS gives you (~10 seconds) when it relaunches the app for a region event. Native first, RN second.</p><p>In our AppDelegate, GeofencingCoordinator.bootstrap(launchOptions) runs before factory.startReactNative(...) for exactly this reason. The launchOptions check for .location key tells us whether iOS relaunched the app for a location event, which gates the entry synthesis logic correctly.</p><pre>// AppDelegate.swift<br>override func application(<br>    _ application: UIApplication,<br>    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil<br>) -&gt; Bool {<br>    let locationKeyPresent = launchOptions?[.location] != nil<br>    // 1. Bootstrap geofencing BEFORE React Native starts<br>    GeofencingCoordinator.bootstrap(<br>        launchOptions: launchOptions,<br>        isOSRelaunch: locationKeyPresent<br>    )<br>    // 2. Then start React Native<br>    factory.startReactNative(withModuleName: &quot;YourApp&quot;, in: window, launchOptions: launchOptions)<br>    return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>}<br><br>// GeofencingCoordinator.swift<br>static func bootstrap(launchOptions: [UIApplication.LaunchOptionsKey: Any]?, isOSRelaunch: Bool) {<br>    // Step 1 - Re-register all saved geofences with OS<br>    let savedGeofences = loadSavedGeofences() // your persistence layer<br>    for geofence in savedGeofences {<br>        locationManager.startMonitoring(for: geofence)<br>    }<br>    // Step 2 - Request current state for all regions<br>    // This synthesizes ENTER if user is already inside a boundary<br>    for region in locationManager.monitoredRegions {<br>        locationManager.requestState(for: region)<br>    }<br>}<br><br>// CLLocationManagerDelegate<br>func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {<br>    if state == .inside {<br>        // Treat as entry - user is inside this boundary right now<br>        handleGeofenceEntry(region: region)<br>    }<br>}</pre><h4>How to handle geofence events</h4><p>Handling the geofencing event differs based on the app state while it was triggered.</p><p><strong>Geofence event triggered while in open/background state:</strong></p><p>Popular library <a href="https://github.com/transistorsoft/react-native-background-geolocation/wiki/Geofence-Features#listening-to-geofence-events"><strong>react-native-background-geolocation</strong></a><strong> </strong>by TransistorSoft, allows you to listen to geofence events through <a href="https://docs.transistorsoft.com/react-native/Geofence/#listening-for-events"><strong>onGeofence</strong></a> subscriber.</p><pre>bgGeo.addGeofence({<br>        identifier: &quot;Home&quot;,<br>        radius: 200,<br>        latitude: 47.2342323,<br>        longitude: -57.342342,<br>        notifyOnEntry: true<br>    });<br>    <br>    bgGeo.onGeofence(function(geofence, taskId) {<br>        try {<br>            var identifier = geofence.identifier;<br>            var action     = geofence.action;<br>            var location   = geofence.location;<br>            console.log(&quot;- A Geofence transition occurred&quot;);<br>            console.log(&quot;  identifier: &quot;, identifier);<br>            console.log(&quot;  action: &quot;, action);<br>            console.log(&quot;  location: &quot;, JSON.stringify(location));<br>        } catch(e) {<br>            console.error(&quot;An error occurred in my code!&quot;, e);<br>        }<br>        // Be sure to call #finish!!<br>        bgGeo.finish(taskId);<br>    });</pre><p>This code exists along with the all other geofence code.</p><p><strong>Geofence event triggered while in app killed state:</strong></p><p>If your app is in killed state and OS sends the geofence entry/exit event to the app, you would need to handle it through headless mode. <strong>TransistorSoft </strong>already handles headless mode. Check <a href="https://github.com/transistorsoft/react-native-background-geolocation/wiki/Android-Headless-Mode">this</a>.</p><p><strong>index.js</strong></p><pre>// SDK headless must register BEFORE AppRegistry.registerComponent (Android quit-state).<br>BackgroundGeolocation.registerHeadlessTask(async event =&gt; {<br>  if (event.name !== &#39;geofence&#39;) return;<br>  await handleGeofenceHeadlessEvent(event.params, event.taskId);<br>});</pre><p>In this case, OS launches the app in the background and starts the app process. SDK will deliver the event inside the callback which is passed to <strong>registerHeadlessTask</strong>.</p><p>In the app open/background state, this code will not get triggered. Index.js headless task comes into picture only when app is killed.</p><p>In TransistorSoft SDK remember to have <a href="https://docs.transistorsoft.com/react-native/AppConfig/#enableheadless"><strong>enableHeadless</strong></a> config value as true</p><p>You can certainly have common reusable code to handle the event which makes api call to backend.</p><p><strong>Two Approaches for Handling Geofence Events further:</strong></p><p><strong>Approach A — Backend owns event tracking ✅ Recommended</strong></p><p>When the app receives a geofence event from the OS, it does not forward the event directly to the backend. Instead, it fetches a fresh current location fix and sends that location ping to the backend. The backend then does all the heavy lifting — it knows which geofences are registered, validates whether the incoming location falls inside any of them, and records entry and exit accordingly.</p><p>The backend handles all edge cases cleanly:</p><ul><li>If two consecutive pings show the user inside the same fence, it records only one entry.</li><li>If an exit ping arrives without a prior entry, it ignores it or flags it.</li><li>If an entry arrives for fence B before an exit was recorded for fence A, it closes fence A first, then opens fence B.</li></ul><p>Each ping from the app can also carry useful metadata alongside the location:</p><pre>isGPSEnabled<br>isAlwaysPermissionGranted<br>batteryPercent<br>appVersion<br>appState (foreground / background / quit)<br>isBatteryOptimizationEnabled<br>locationAccuracy</pre><p>This metadata lets you build a powerful observability dashboard — see exactly how reliable your tracking is per device, per user, and per app state. Your analytics team can use this data to make product decisions: how long users spend at geofences, which geofences they visit, drop-off patterns, and more.</p><p>The biggest advantage of this approach is long-term maintainability. If your event tracking logic changes — new edge case, new business rule — you update the backend. No app release required.</p><p><strong>Approach B — App owns event tracking</strong></p><p>When the app receives an entry or exit event from the OS, it forwards that event directly to the backend. The backend is purely a storage layer — it accepts and stores whatever the app sends without doing any calculation.</p><p>This is simpler to build initially but has real downsides:</p><ul><li>If the OS delays or misses an event — which happens in quit state — that gap is permanently recorded as a missed visit with no way to recover it.</li><li>Any change to event tracking logic requires a new app release and goes through Play Store and App Store review.</li><li>Accuracy is fully dependent on the OS. You have no layer to correct or reconcile inconsistencies.</li></ul><p><strong>Which approach to choose:</strong></p><ul><li>Go with <strong>Approach A</strong> if you are building for production and care about accuracy, analytics, and long-term maintainability. The additional backend work upfront pays off significantly over time.</li><li>Go with <strong>Approach B</strong> only if you are building a quick prototype or MVP and want to validate the concept before investing in backend infrastructure.</li></ul><p>That covers the — how the OS manages location, what permissions actually mean at the OS level, and what Play Store and App Store expect before you even write a line of tracking code. Also we now have the geofencing strategy in place.</p><p>In the next article, we go hands-on: what how to track user location inside a geofence once entry is detected. But location polling is not as easy as it sounds. The real question is how to actually make it work reliably on Android and iOS — across foreground, background, and killed state — in the hands of real users on real devices.</p><p>Here is next part: <a href="https://medium.com/@varunkukade999/part-2-geofencing-background-location-tracking-in-react-native-2026-ffe26d67bd3a">Part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=800c269a15e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Extend iOS App Background Execution Time in Swift]]></title>
            <link>https://medium.com/@varunkukade999/how-to-extend-ios-app-background-execution-time-in-swift-a391b2aa7846?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a391b2aa7846</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 05:24:45 GMT</pubDate>
            <atom:updated>2026-08-02T05:24:45.522Z</atom:updated>
            <content:encoded><![CDATA[<p>Stop your iOS app from suspending after 30 seconds — a complete implementation guide.</p><p>When your app moves to the background, iOS does not keep it running indefinitely. There are two distinct background states you need to understand before any of this makes sense.</p><p><strong>Suspended</strong> is the default. Shortly after your app enters the background, iOS freezes it. No code runs. No timers fire. No network calls complete. The app is still in memory and visible in the app switcher, but it is completely frozen. This happens automatically within seconds.</p><p><strong>Active in background</strong> is what you get when you explicitly ask iOS for more time. You do this by calling UIApplication.shared.beginBackgroundTask. This tells iOS: &quot;I have work to finish, please do not suspend me yet.&quot; iOS grants you a short execution window — currently around 30 seconds — during which your code can continue running.</p><p>beginBackgroundTask is the correct first step. The problem is the 30-second limit. For most use cases that need the app alive for minutes — not seconds — 30 seconds is not enough. And you cannot simply call beginBackgroundTask again when the first one expires to chain unlimited time. Apple does not allow this. In practice, stacking overlapping tasks burns the shared budget faster and can lead to termination.</p><p>So the question becomes: how do you legitimately extend background execution beyond 30 seconds?</p><p>This article walks through exactly how the technique works and how to implement it.</p><h3><strong>The key insight</strong></h3><p>You do not extend background time by creating more tasks.</p><p>You extend it by briefly performing location work.</p><p>When CLLocationManager delivers a location update while your app is in the background, iOS treats the app as doing legitimate location work and <strong>refreshes</strong> the background execution budget. Your same background task stays alive because backgroundTimeRemaining jumps back up.</p><pre>before location update:  backgroundTimeRemaining ≈ 5s<br>after location update:   backgroundTimeRemaining ≈ 28s</pre><p>That refresh is the entire foundation of this technique.</p><h3><strong>Two approaches that follow from this</strong></h3><p>Now that you know location activity refreshes the budget, two strategies are possible.</p><p><strong>Approach 1 — Keep GPS always on</strong></p><p>Call startUpdatingLocation() when the session starts and never call stopUpdatingLocation(). As long as location updates are flowing, iOS treats the app as actively doing location work and will not suspend it. Simple to implement. Reliable.</p><p>The problem is battery. When startUpdatingLocation() is active, the GPS chip is powered and sampling constantly — even when the user is completely stationary. Whether or not your delegate receives every fix depends on distanceFilter, but the hardware never stops running. There is no new location information to act on, yet the chip burns through battery the entire time.</p><p>Continuous GPS draws roughly 150–200mA constantly. On a 45-minute session where the user is mostly stationary, this visibly drains the battery and your app appears at the top of the user’s battery usage stats.</p><p><strong>Approach 2 — Pulse GPS on and off (this article)</strong></p><p>The GPS pipeline is completely off between pulses. Every ~30 seconds, the app briefly wakes the GPS chip for 2–3 seconds, gets a fix which refreshes the budget, and shuts it down again. Waking for a single fix every 30 seconds uses roughly 5% of continuous GPS draw — eliminating the battery drain entirely during stationary phases.</p><p>The trade-off is complexity. The rest of this article explains exactly how to implement it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2VkPTY7KOyhH3eaYA_IfA.jpeg" /></figure><h3><strong>Who this is for</strong></h3><p>This pattern is useful if:</p><ul><li>Your app already has a legitimate need for background location</li><li>You have been granted <strong>Always</strong> authorization — this technique requires it. When In Use is not sufficient because iOS does not permit turning location on from the background without Always authorization. The pulse will fail silently and the app will suspend.</li><li>You need the app to stay awake for extended periods while the user is stationary — for example, waiting at a location for 20–40 minutes</li></ul><p>This is not a general-purpose trick for arbitrary background work. It depends on location. If your app does not have a real location use case, do not use this.</p><h3>Prerequisites</h3><p>Before any of this works, three things must be in place.</p><p><strong>1. Background location mode in Info.plist</strong></p><p>xml</p><pre>&lt;key&gt;UIBackgroundModes&lt;/key&gt;<br>&lt;array&gt;<br>  &lt;string&gt;location&lt;/string&gt;<br>&lt;/array&gt;</pre><p>Without this key, setting allowsBackgroundLocationUpdates = true can cause Apple to terminate your app immediately.</p><p><strong>2. Always Location authorization</strong></p><p>Always authorization is required. This technique relies on briefly turning on location services from the background. iOS does not permit this with When In Use authorization — the pulse will fail silently and the app will suspend.</p><p><strong>3. Background location flags on your location manager</strong></p><p>swift</p><pre>locationManager.allowsBackgroundLocationUpdates = true<br>locationManager.showsBackgroundLocationIndicator = true</pre><p>Only set these after permission is granted and only if UIBackgroundModes contains location. Add a guard:</p><p>swift</p><pre>private func canEnableBackgroundLocation() -&gt; Bool {<br>    let modes = Bundle.main.object(<br>        forInfoDictionaryKey: &quot;UIBackgroundModes&quot;<br>    ) as? [String]<br>    let hasLocationMode = modes?.contains(&quot;location&quot;) == true<br>    let status = locationManager.authorizationStatus<br>    return status == .authorizedAlways &amp;&amp; hasLocationMode // Always only<br>}</pre><h3>The problem with beginBackgroundTask</h3><p>Most developers first try chaining background tasks:</p><p>swift</p><pre>var taskId = UIBackgroundTaskIdentifier.invalid<br>taskId = UIApplication.shared.beginBackgroundTask {<br>    UIApplication.shared.endBackgroundTask(taskId)<br>    // ❌ Do NOT call beginBackgroundTask here<br>}</pre><p>UIApplication.shared.backgroundTimeRemaining starts around 30 seconds and counts down. When it hits zero, iOS calls your expiration handler and suspends the app.</p><p>The common instinct is: “create another background task before the first one expires.” This does not work reliably. Apple does not want apps stacking infinite overlapping background tasks. In practice it burns the shared budget faster and can lead to termination.</p><h3>The algorithm</h3><p>Here is the loop in plain language:</p><ol><li>App enters background and needs to stay awake</li><li>Create exactly <strong>one</strong> background task</li><li>If the user is moving, startUpdatingLocation() is already active and delivering fixes — GPS stays on and iOS will not suspend the app. When movement stops and location updates go silent, stop GPS explicitly to begin the pulse loop</li><li>Read how much background time remains</li><li>Schedule a timer to fire 5 seconds before that time runs out</li><li>When the timer fires, call startUpdatingLocation()</li><li>When a location fix arrives, stop location updates</li><li>Wait 3 seconds, schedule the next pulse from the refreshed remaining time</li><li>Repeat until keep-alive is no longer needed</li></ol><p><strong>Key rules:</strong></p><ul><li>Maintain one background task, not many</li><li>Never create a new task inside the expiration handler</li><li>Never create a new task when a location fix arrives</li><li>Never leave continuous GPS on the whole time</li></ul><h3>Constants</h3><p>These values come from production-tested implementation:</p><p>swift</p><pre>private static let fireBeforeExpirySeconds: TimeInterval = 5<br>private static let immediatePulseThresholdSeconds: TimeInterval = 10<br>private static let onSuspendSyntheticRemainingSeconds: TimeInterval = 20<br>private static let maxSchedulableRemainingSeconds: TimeInterval = 30<br>private static let pulseTimeoutSeconds: TimeInterval = 15<br>private static let acquisitionBufferSeconds: TimeInterval = 3</pre><p>fireBeforeExpirySeconds = 5 — Fire the location pulse 5 seconds before remaining time ends</p><p>immediatePulseThresholdSeconds = 10 — If the delay would be under 10 seconds, pulse immediately instead of scheduling a timer</p><p>onSuspendSyntheticRemainingSeconds = 20 — When the app enters background with an existing task, behave as if 20 seconds remain. This means the first pulse fires at the 15-second mark.</p><p>maxSchedulableRemainingSeconds = 30 — Do not schedule a pulse when remaining time is above 30 seconds. In the foreground, remaining time is huge. Only schedule when you are actually in background with a real finite budget.</p><p>acquisitionBufferSeconds = 3 — After stopping GPS, wait 3 seconds before reading remaining time and scheduling the next pulse.</p><p>pulseTimeoutSeconds = 15 — If no location fix arrives within 15 seconds of starting the pulse, stop waiting and continue the loop anyway.</p><h3>Implementation</h3><h4>Step 1: Create a dedicated location manager</h4><p>Use a separate CLLocationManager for keep-alive pulses only. Do not mix this with your main tracking manager.</p><pre>final class BackgroundKeepAlive: NSObject, CLLocationManagerDelegate {<br><br>    private let locationManager = CLLocationManager()<br>    private var backgroundTasks = Set&lt;UIBackgroundTaskIdentifier&gt;()<br>    private var preventSuspendTasks = Set&lt;UIBackgroundTaskIdentifier&gt;()<br>    private var preventSuspendTimer: Timer?<br>    private var acquisitionBufferWork: DispatchWorkItem?<br>    private var pulseTimeoutWork: DispatchWorkItem?<br>    private var isRunning = false<br>    private var isAcquiringBackgroundTime = false<br>    private var isUpdatingLocation = false<br><br>    override init() {<br>        super.init()<br>        locationManager.delegate = self<br>        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters<br>        locationManager.distanceFilter = kCLDistanceFilterNone<br>        locationManager.pausesLocationUpdatesAutomatically = false<br>        locationManager.activityType = .other<br>    }<br>}</pre><p>Notes:</p><ul><li>kCLLocationAccuracyHundredMeters is enough to trigger a budget refresh</li><li>pausesLocationUpdatesAutomatically = false prevents iOS from pausing updates while stationary</li><li>kCLDistanceFilterNone ensures location events fire even without movement</li></ul><p>Apply background flags whenever authorization changes:</p><pre>private func applyBackgroundFlags() {<br>    let allow = canEnableBackgroundLocation()<br>    locationManager.allowsBackgroundLocationUpdates = allow<br>    locationManager.showsBackgroundLocationIndicator = allow<br>}<br><br>func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {<br>    applyBackgroundFlags()<br>}</pre><h4>Step 2: Start with exactly one background task</h4><pre>func start() {<br>    guard !isRunning else { return }<br>    startPreventSuspend(reason: &quot;start&quot;)<br>}<br><br>private func startPreventSuspend(reason: String) {<br>    isRunning = true<br>    applyBackgroundFlags()<br>    acquireBackgroundTime(reason: reason)<br>    _ = createBackgroundTask(reason: reason)<br>}</pre><p>Creating the task:</p><pre>@discardableResult<br>private func createBackgroundTask(reason: String) -&gt; UIBackgroundTaskIdentifier {<br>    var taskId: UIBackgroundTaskIdentifier = .invalid<br>    taskId = UIApplication.shared.beginBackgroundTask { [weak self] in<br>        // Expiration handler: ONLY end this task.<br>        // NEVER call beginBackgroundTask here.<br>        self?.stopPreventSuspendTask(taskId, reason: &quot;forceKill&quot;)<br>    }<br>    if taskId != .invalid {<br>        backgroundTasks.insert(taskId)<br>        preventSuspendTasks.insert(taskId)<br>    }<br>    return taskId<br>}</pre><p><strong>Critical:</strong> the expiration handler only ends the task. It never creates another one.</p><h4>Step 3: When movement stops and location updates go silent, stop GPS explicitly</h4><p>Call acquireBackgroundTime whenever you want to stop GPS.</p><pre>private func acquireBackgroundTime(reason: String) {<br>    isAcquiringBackgroundTime = false<br>    locationManager.stopUpdatingLocation()<br>    cancelPulseTimeout()<br>    scheduleAcquisitionBuffer(reason: reason)<br>}<br><br>private func scheduleAcquisitionBuffer(reason: String) {<br>    acquisitionBufferWork?.cancel()<br>    let work = DispatchWorkItem { [weak self] in<br>        guard let self = self, self.isRunning else { return }<br>        self.pleaseStayAwake(reason: reason)<br>    }<br>    acquisitionBufferWork = work<br>    DispatchQueue.main.asyncAfter(<br>        deadline: .now() + Self.acquisitionBufferSeconds,<br>        execute: work<br>    )<br>}</pre><p>The 3-second buffer gives the system time to settle after stopping location before you read backgroundTimeRemaining and schedule the next pulse.</p><h4>Step 4: Read remaining time and schedule the pulse timer</h4><pre>private func pleaseStayAwake(reason: String) {<br>    guard isRunning else { return }<br>    if preventSuspendTasks.isEmpty { return }<br>    let remaining = UIApplication.shared.backgroundTimeRemaining<br>    if preventSuspendTimer != nil { return }<br>    if !remaining.isFinite || remaining &gt; Self.maxSchedulableRemainingSeconds { return }<br>    startPreventSuspendTimer(remaining: remaining, reason: reason)<br>}<br><br>private func startPreventSuspendTimer(remaining: TimeInterval, reason: String) {<br>    stopPreventSuspendTimer()<br>    guard isRunning else { return }<br>    let delay = remaining - Self.fireBeforeExpirySeconds<br>    if delay &lt; Self.immediatePulseThresholdSeconds {<br>        onPreventSuspendTimer()<br>        return<br>    }<br>    let timer = Timer(timeInterval: delay, repeats: false) { [weak self] _ in<br>        self?.onPreventSuspendTimer()<br>    }<br>    RunLoop.main.add(timer, forMode: .common)<br>    preventSuspendTimer = timer<br>}<br><br>private func stopPreventSuspendTimer() {<br>    preventSuspendTimer?.invalidate()<br>    preventSuspendTimer = nil<br>}</pre><p>The maxSchedulableRemainingSeconds = 30 guard is important. In foreground, backgroundTimeRemaining returns a huge value. Only schedule when actually in background with a real finite budget.</p><h4>Step 5: Fire the pulse</h4><pre>private func onPreventSuspendTimer() {<br>    guard isRunning else { return }<br>    preventSuspendTimer = nil<br>    applyBackgroundFlags()<br>    isAcquiringBackgroundTime = true<br>    if isUpdatingLocation { return }<br>    locationManager.startUpdatingLocation()<br>    schedulePulseTimeout()<br>}<br><br>private func schedulePulseTimeout() {<br>    cancelPulseTimeout()<br>    let work = DispatchWorkItem { [weak self] in<br>        guard let self = self, self.isAcquiringBackgroundTime else { return }<br>        self.acquireBackgroundTime(reason: &quot;timeout&quot;)<br>    }<br>    pulseTimeoutWork = work<br>    DispatchQueue.main.asyncAfter(<br>        deadline: .now() + Self.pulseTimeoutSeconds,<br>        execute: work<br>    )<br>}<br><br>private func cancelPulseTimeout() {<br>    pulseTimeoutWork?.cancel()<br>    pulseTimeoutWork = nil<br>}</pre><p>The pulse timeout ensures the loop never gets permanently stuck waiting for a fix that never comes.</p><h4>Step 6: Handle the location fix — do NOT create a new task</h4><pre>func locationManager(<br>    _ manager: CLLocationManager,<br>    didUpdateLocations locations: [CLLocation]<br>) {<br>    if isUpdatingLocation { return }<br>    if isAcquiringBackgroundTime {<br>        guard locations.last != nil else { return }<br>        cancelPulseTimeout()<br>        // Fix refreshed the budget. Loop continues.<br>        // CRITICAL: Do NOT create a new background task here.<br>        acquireBackgroundTime(reason: &quot;didUpdateLocations&quot;)<br>        return<br>    }<br>    locationManager.stopUpdatingLocation()<br>}<br><br>func locationManager(<br>    _ manager: CLLocationManager,<br>    didFailWithError error: Error<br>) {<br>    if isAcquiringBackgroundTime {<br>        cancelPulseTimeout()<br>        acquireBackgroundTime(reason: &quot;didFailWithError&quot;)<br>    }<br>}</pre><p>You already have one background task. The location fix refreshes the budget for that task. Creating another task here breaks the single-task invariant.</p><h4>Step 7: Handle app entering background</h4><p>When the app backgrounds, foreground-scheduled timers are unreliable. Re-arm correctly:</p><pre>func rearmOnEnterBackground() {<br>    applyBackgroundFlags()<br>    if !preventSuspendTasks.isEmpty {<br>        isRunning = true<br>        startPreventSuspendTimer(<br>            remaining: Self.onSuspendSyntheticRemainingSeconds,<br>            reason: &quot;onSuspend&quot;<br>        )<br>        return<br>    }<br>    startPreventSuspend(reason: &quot;onSuspend&quot;)<br>}</pre><p>Wire it from your app lifecycle:</p><pre>NotificationCenter.default.addObserver(<br>    self,<br>    selector: #selector(appDidEnterBackground),<br>    name: UIApplication.didEnterBackgroundNotification,<br>    object: nil<br>)<br><br>@objc private func appDidEnterBackground() {<br>    keepAlive.rearmOnEnterBackground()<br>}</pre><p>The synthetic 20-second remaining means the first pulse fires at the 15-second mark, safely before the 30-second window expires.</p><h4>Step 8: End a task cleanly</h4><p>swift</p><pre>private func stopPreventSuspendTask(<br>    _ taskId: UIBackgroundTaskIdentifier,<br>    reason: String<br>) {<br>    guard taskId != .invalid else { return }<br>    if backgroundTasks.contains(taskId) {<br>        UIApplication.shared.endBackgroundTask(taskId)<br>    }<br>    backgroundTasks.remove(taskId)<br>    preventSuspendTasks.remove(taskId)<br>    if preventSuspendTasks.isEmpty {<br>        stopPreventSuspendTimer()<br>    }<br>}</pre><h4>Step 9: Stop everything cleanly</h4><pre>func stop() {<br>    guard isRunning || isAcquiringBackgroundTime || !backgroundTasks.isEmpty else { return }<br>    isRunning = false<br>    isAcquiringBackgroundTime = false<br>    isUpdatingLocation = false<br>    pulseTimeoutWork?.cancel()<br>    pulseTimeoutWork = nil<br>    acquisitionBufferWork?.cancel()<br>    acquisitionBufferWork = nil<br>    stopPreventSuspendTimer()<br>    locationManager.stopUpdatingLocation()<br>    endAllBackgroundTasks()<br>}<br><br>private func endAllBackgroundTasks() {<br>    for id in backgroundTasks {<br>        UIApplication.shared.endBackgroundTask(id)<br>    }<br>    backgroundTasks.removeAll()<br>    preventSuspendTasks.removeAll()<br>}<br></pre><h3><strong>Separating keep-alive from your actual work</strong></h3><p>Keep-alive and your business logic should be completely separate.</p><ul><li><strong>Keep-alive:</strong> only renews background time via location pulses. Knows nothing about your business logic.</li><li><strong>Worker timer:</strong> does your actual periodic work — sending data, checking conditions, running computations.</li></ul><pre>final class BackgroundWorker {<br>    private var timer: Timer?<br>    private var intervalSeconds: TimeInterval = 60<br><br>    func start() {<br>        timer?.invalidate()<br>        timer = Timer.scheduledTimer(<br>            withTimeInterval: intervalSeconds,<br>            repeats: true<br>        ) { [weak self] _ in<br>            self?.doWork()<br>        }<br>        if let timer {<br>            RunLoop.main.add(timer, forMode: .common)<br>        }<br>        doWork()<br>    }<br><br>    func stop() {<br>        timer?.invalidate()<br>        timer = nil<br>    }<br><br>    private func doWork() {<br>        // Your background work here.<br>        // Runs only while keep-alive keeps the process schedulable.<br>    }<br>}</pre><p>Gate both together:</p><pre>func syncKeepAlive(shouldRun: Bool, enteredBackground: Bool = false) {<br>    if shouldRun {<br>        if enteredBackground {<br>            keepAlive.rearmOnEnterBackground()<br>        } else {<br>            keepAlive.start()<br>        }<br>        worker.start()<br>    } else {<br>        keepAlive.stop()<br>        worker.stop()<br>    }<br>}</pre><p>The worker depends on keep-alive being active. Keep-alive does not know anything about the worker.</p><h3>What success looks like</h3><p>When this works correctly, you will observe this sequence in logs:</p><ol><li>App enters background</li><li>One background task begins</li><li>GPS stops, 3-second buffer runs</li><li>Timer scheduled from real backgroundTimeRemaining</li><li>Near expiry, startUpdatingLocation() fires</li><li>A location fix arrives</li><li>stopUpdatingLocation() is called</li><li>backgroundTimeRemaining jumps back up</li><li>3-second buffer runs again</li><li>Next timer scheduled</li><li>Loop continues</li></ol><p>Your worker timer keeps firing every 60 seconds. Keep-alive is doing its job.</p><p>If everything dies after ~30 seconds and never recovers, the pulse is not refreshing the budget. Check:</p><ul><li>UIBackgroundModes includes location</li><li>Permission is Always or valid When In Use setup</li><li>allowsBackgroundLocationUpdates == true</li><li>You are actually calling startUpdatingLocation() before expiry</li><li>You are not ending the background task too early</li><li>You are not creating tasks inside the expiration handler</li></ul><h3>Adding diagnostics</h3><p>During development, add NSLog at every state transition so you can see the loop in Xcode&#39;s console even while the app is backgrounded:</p><p>swift</p><pre>private func diag(_ message: String) {<br>    let remaining = UIApplication.shared.backgroundTimeRemaining<br>    let remainingStr = remaining.isFinite &amp;&amp; remaining &lt; 1_000_000<br>        ? String(format: &quot;%.1fs&quot;, remaining) : &quot;fg/inf&quot;<br>    NSLog(&quot;[KeepAlive] %@ bgRemaining=%@ tasks=%d&quot;,<br>          message, remainingStr, backgroundTasks.count)<br>}</pre><p>Watch for:</p><ul><li>bgRemaining jumping back up after PULSE_COMPLETE — that is the refresh working</li><li>bgRemaining only decreasing — the pulse is not refreshing and the app will suspend</li><li>BG_TASK_BEGIN FAILED — iOS refused the task (app may be trying to start while already suspended)</li></ul><h3>Common mistakes</h3><p><strong>1. Creating a new background task on every location fix</strong></p><p>swift</p><pre>// ❌ Wrong<br>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {<br>    _ = createBackgroundTask()<br>}<br><br>// ✅ Right<br>acquireBackgroundTime(reason: &quot;didUpdateLocations&quot;)</pre><p><strong>2. Creating a new task inside the expiration handler</strong></p><p>swift</p><pre>// ❌ Wrong<br>beginBackgroundTask { _ = createBackgroundTask() }<br><br>// ✅ Right<br>beginBackgroundTask { endBackgroundTask(taskId) }</pre><p><strong>3. Leaving continuous GPS on as a lazy shortcut</strong><br> That is Approach 1. Valid, but accept the battery cost honestly.</p><p><strong>4. Scheduling from foreground remaining time</strong><br> In foreground, backgroundTimeRemaining is huge. The maxSchedulableRemainingSeconds = 30 check handles this.</p><p><strong>5. Missing Info.plist background mode</strong><br> Without location in UIBackgroundModes, setting background location flags can terminate your app immediately.</p><h3><strong>Mental model</strong></h3><p>Think of iOS background time like a parking meter.</p><ul><li>beginBackgroundTask puts coins in once</li><li>The meter counts down</li><li>A brief location pulse adds more time to the same meter</li><li>You do not install a second meter next to the first one</li><li>You keep feeding the same one with legitimate location activity</li></ul><h3>Final note</h3><p>iOS does not give unlimited background execution for free.</p><p>But if your app already has a valid background location use case, you can stay runnable for extended periods by holding one background task, periodically doing a short location pulse, letting iOS refresh the background time budget, and then turning location off again.</p><p>That is how you go from suspended in 30 seconds to still running minutes later.</p><p>Use it only when location permission and product purpose justify it. Keep the implementation disciplined: one task, short pulses, clean stop.</p><p><em>If this was useful, a clap or follow goes a long way — it helps this reach engineers who’d actually use it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a391b2aa7846" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Simulate Location and Routes in Android and IOS Without Physically Moving]]></title>
            <link>https://medium.com/@varunkukade999/how-to-simulate-location-and-routes-in-android-and-ios-without-physically-moving-d324fa3eb917?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d324fa3eb917</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 20:25:31 GMT</pubDate>
            <atom:updated>2026-07-22T20:45:27.902Z</atom:updated>
            <content:encoded><![CDATA[<p>When building location-aware features, there comes a point where you need to test them without physically moving. Maybe you are testing a delivery tracking flow, a fitness route recorder, a geofencing trigger, or a navigation feature. Walking or driving to real locations every time you want to verify something is slow, unreliable, and impossible to reproduce consistently.</p><p>Both Android and iOS give you built-in tools to simulate location — either a single fixed point or a full moving route — directly from your development environment. No physical movement needed. Same test, same route, perfectly reproducible every time.</p><p>This article covers how to do both: setting a one-time location fix and simulating a moving route.</p><h3><strong>Android</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLc_MJZgOOmKyGtbCa9sYg.png" /></figure><p>When you click on the “…” dots on the Android emulator, you see Extended Controls. Click on Location. You will see an “Enable GPS signal” toggle — keep this enabled. Disabling it reduces location accuracy during testing, the same way turning off GPS on a real device would.</p><p>You will see two tabs: Single Points and Routes.</p><p><strong>Single Points</strong><br>This lets you set a fixed location on the emulator. Click anywhere on the map to drop a pin, save the point, and click <strong>“Set Location”.</strong> The emulator will now report that coordinate as the device’s current location. Reload the app once to pick up the newly set location.</p><p><strong>Routes</strong><br>This lets you simulate movement along a path from point A to point B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSvJjr4S2kNbIAqDQeDjPg.png" /></figure><p>Click <strong>“Import GPX/KML” </strong>choose your GPX file, and click <strong>“Play Route”</strong> The emulator will move along the route in real time, updating the device’s location as it travels through each point.</p><p><strong>What is a GPX file?</strong></p><p>GPX stands for GPS Exchange Format. It is a standard XML file format used to store location data — a sequence of coordinates with timestamps that together describe a path or movement.</p><p>Think of it like a recording of a journey. Each point in the file says: “at this exact moment in time, the device was at this latitude and longitude.” When you feed this file to an emulator or simulator, it replays that journey — moving the virtual device through each coordinate in sequence, at the pace defined by the timestamps.</p><p>Here is what a minimal GPX file looks like in structure:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;gpx version=&quot;1.1&quot; creator=&quot;YourApp&quot; xmlns=&quot;http://www.topografix.com/GPX/1/1&quot;&gt;<br>  &lt;trk&gt;<br>    &lt;name&gt;My Test Route&lt;/name&gt;<br>    &lt;trkseg&gt;<br>      &lt;trkpt lat=&quot;37.7749&quot; lon=&quot;-122.4194&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:00:00.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.7750&quot; lon=&quot;-122.4190&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:00:05.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>    &lt;/trkseg&gt;<br>  &lt;/trk&gt;<br>&lt;/gpx&gt;</pre><p>Each &lt;trkpt&gt; is one location fix. It has:</p><ul><li>lat and lon — the coordinate</li><li>&lt;ele&gt; — elevation in metres (can be 0 if you don&#39;t care about it)</li><li>&lt;time&gt; — exact UTC timestamp for when the device should be at this point</li></ul><p><strong>How speed is controlled</strong></p><p>The emulator or simulator does not read a <strong>“speed”</strong> field. Speed is implied by how far apart two coordinates are and how much time separates them. If two points are 10 metres apart and the timestamps are 2 seconds apart, the device moves fast. If the timestamps are 30 seconds apart, it moves slowly. You control the simulated speed entirely through the gap between timestamps.</p><p>This means:</p><ul><li>Walking pace → points close together, small time gaps (~5–10 seconds between each)</li><li>Driving pace → points further apart or larger time gaps</li><li>Stationary → same coordinate repeated with increasing timestamps</li></ul><p><strong>How to simulate staying in one place</strong></p><p>Repeat the exact same coordinate multiple times with increasing timestamps. The device stays at that point for the entire duration. For example, to simulate a user sitting in a cafe for 2 minutes:</p><pre>&lt;trkpt lat=&quot;37.7755&quot; lon=&quot;-122.4180&quot;&gt;<br>  &lt;time&gt;2026-01-01T08:02:00.000Z&lt;/time&gt;<br>&lt;/trkpt&gt;<br>&lt;trkpt lat=&quot;37.7755&quot; lon=&quot;-122.4180&quot;&gt;<br>  &lt;time&gt;2026-01-01T08:02:30.000Z&lt;/time&gt;<br>&lt;/trkpt&gt;<br>&lt;trkpt lat=&quot;37.7755&quot; lon=&quot;-122.4180&quot;&gt;<br>  &lt;time&gt;2026-01-01T08:03:00.000Z&lt;/time&gt;<br>&lt;/trkpt&gt;<br>&lt;trkpt lat=&quot;37.7755&quot; lon=&quot;-122.4180&quot;&gt;<br>  &lt;time&gt;2026-01-01T08:04:00.000Z&lt;/time&gt;<br>&lt;/trkpt&gt;</pre><p>Same coordinate, timestamps 30 seconds apart, for 2 minutes total. The device sits still for that entire window.</p><p><strong>You do not need to create GPX files by hand</strong></p><p>This is where AI becomes very useful. GPX files are structured and predictable — exactly the kind of output AI generates well. You describe your route in plain English and AI writes the file for you.</p><p>Here is a sample GPX file you can use as a reference template. Share this file with AI along with your route description and it will generate a correctly structured file matching your path:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;gpx version=&quot;1.1&quot; creator=&quot;TestRoute&quot; xmlns=&quot;http://www.topografix.com/GPX/1/1&quot;&gt;<br>  &lt;metadata&gt;<br>    &lt;name&gt;Sample Test Route&lt;/name&gt;<br>    &lt;time&gt;2026-01-01T08:00:00.000Z&lt;/time&gt;<br>  &lt;/metadata&gt;<br>  &lt;trk&gt;<br>    &lt;name&gt;Start outside — Enter boundary — Dwell — Exit&lt;/name&gt;<br>    &lt;trkseg&gt;<br><br>      &lt;!-- PHASE 1: OUTSIDE — walking toward target area --&gt;<br>      &lt;trkpt lat=&quot;37.774500&quot; lon=&quot;-122.419800&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:00:00.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.774600&quot; lon=&quot;-122.419600&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:00:07.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.774700&quot; lon=&quot;-122.419400&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:00:14.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br><br>      &lt;!-- PHASE 2: CROSS BOUNDARY — enter target area --&gt;<br>      &lt;trkpt lat=&quot;37.774800&quot; lon=&quot;-122.419200&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:00:21.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.774900&quot; lon=&quot;-122.419000&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:00:28.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br><br>      &lt;!-- PHASE 3: STATIONARY — sitting at a cafe for 2 minutes --&gt;<br>      &lt;trkpt lat=&quot;37.775000&quot; lon=&quot;-122.418900&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:00:35.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.775000&quot; lon=&quot;-122.418900&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:01:05.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.775000&quot; lon=&quot;-122.418900&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:01:35.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.775000&quot; lon=&quot;-122.418900&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:02:05.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.775000&quot; lon=&quot;-122.418900&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:02:35.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br><br>      &lt;!-- PHASE 4: MOVING AGAIN — walking out of area --&gt;<br>      &lt;trkpt lat=&quot;37.774900&quot; lon=&quot;-122.418700&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:02:45.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br>      &lt;trkpt lat=&quot;37.774800&quot; lon=&quot;-122.418500&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:02:55.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br><br>      &lt;!-- PHASE 5: OUTSIDE — crossed boundary, left area --&gt;<br>      &lt;trkpt lat=&quot;37.774600&quot; lon=&quot;-122.418200&quot;&gt;<br>        &lt;ele&gt;10&lt;/ele&gt;<br>        &lt;time&gt;2026-01-01T08:03:05.000Z&lt;/time&gt;<br>      &lt;/trkpt&gt;<br><br>    &lt;/trkseg&gt;<br>  &lt;/trk&gt;<br>&lt;/gpx&gt;</pre><p><strong>How to prompt AI to generate your GPX</strong></p><p>Give AI the following information and it will produce a complete, correctly structured GPX file:</p><ul><li><strong>Start point</strong> — coordinates of where the route begins</li><li><strong>End point</strong> — coordinates of where it ends</li><li><strong>Any intermediate stops</strong> — coordinates of places to visit along the way</li><li><strong>Dwell time at each stop</strong> — how long to stay stationary (“sit at the park for 3 minutes”, “wait at the cafe for 10 minutes”)</li><li><strong>Speed at each segment</strong> — walking, jogging, driving, cycling</li><li><strong>Any boundaries to cross</strong> — “enter this circular area with radius 100m centered at these coordinates”</li></ul><p>Example prompt you can give AI:</p><blockquote><em>“Generate a GPX file for the following route. Start at [coordinates], walk at normal pace toward [coordinates], enter a circular area of 100m radius centered at [coordinates], walk slowly around inside it for 2 minutes, sit stationary at [coordinates] for 5 minutes simulating waiting at a cafe, then walk out of the area and exit to [coordinates]. Use timestamps starting from 2026–01–01T08:00:00Z. Use the attached GPX file as the exact format reference — keep the same structure, same timestamp format, same XML tags.”</em></blockquote><p>AI will generate a GPX file with the right number of track points, correct timestamp spacing for each speed, and repeated coordinates for stationary phases. You then drop that file directly into the Android emulator.</p><p>You can click on “Play route” and see if its working as expected. You can do further tweaks inside GPX as required.</p><h3>IOS</h3><p>For iOS, you can similarly create a GPX file and simulate location routes directly in Xcode without physically moving.</p><p>Go to <strong>Xcode → your scheme name at the top → Edit Scheme → Run → Options tab</strong>.</p><p><strong>Or Xcode -&gt; Product -&gt; Scheme -&gt; Edit Scheme → Run → Options tab.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-ZUSdiulj8X1EyeheFj_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0MX41FQCJNdwqLAV252Rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QU-5ZZyWzfaAiZB2LFQdg.png" /></figure><p>Check <strong>“Allow Location Simulation.”</strong> Inside the <strong>Default Location dropdown</strong>, choose your GPX file by clicking <strong>“Add GPS Exchange to Workspace”.</strong> Then build/rebuild the app. As soon as it launches on the simulator, iOS starts simulating the route in your GPX from the beginning. You can open the Maps app on the simulator to visually watch the movement in real time. Every time you rebuild the app, the route restarts from the first point in the file.</p><p><strong>iOS GPX format is different from Android</strong></p><p>This is the most important thing to know. Android uses &lt;trkpt&gt; tags inside a &lt;trk&gt; and &lt;trkseg&gt; wrapper. iOS uses &lt;wpt&gt; (waypoint) tags placed directly under the root &lt;gpx&gt; tag — no track wrapper at all. If you use the Android format on iOS, the simulation will not work. You must use the iOS format and vice versa</p><pre>&lt;?xml version=&quot;1.0&quot; ?&gt;<br>&lt;gpx version=&quot;1.1&quot; creator=&quot;TestRoute&quot;&gt;<br>  &lt;wpt lat=&quot;37.7749&quot; lon=&quot;-122.4194&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:00:00.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.7750&quot; lon=&quot;-122.4190&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:00:12.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>&lt;/gpx&gt;</pre><p>Each &lt;wpt&gt; is one location point. Same fields as Android — lat, lon, &lt;ele&gt; for elevation, &lt;time&gt; for the timestamp. Speed is still controlled by how far apart coordinates are and how much time separates them. Stationary phase is still done by repeating the same coordinate with increasing timestamps.</p><p><strong>Sample iOS GPX</strong></p><p>Use this as your format reference. Share it with AI along with your route description. Keep the format identical — only change the coordinates, timestamps, and route description:</p><pre>&lt;?xml version=&quot;1.0&quot; ?&gt;<br>&lt;gpx version=&quot;1.1&quot; creator=&quot;TestRoute&quot;&gt;<br><br>  &lt;!-- PHASE 1: START OUTSIDE — walking toward target at normal pace --&gt;<br>  &lt;!-- Steps every 12 seconds, small lon increment = walking speed --&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.419800&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:00:00.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.419634&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:00:12.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.419468&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:00:24.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.419302&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:00:36.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.419136&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:00:48.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br><br>  &lt;!-- PHASE 2: CROSS BOUNDARY — entering target area --&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418970&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:01:00.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418804&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:01:12.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br><br>  &lt;!-- PHASE 3: STATIONARY — sitting at a park for 3 minutes --&gt;<br>  &lt;!-- Same coordinate repeated, 12 seconds apart --&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:01:24.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:01:36.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:01:48.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:02:00.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:02:12.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:02:24.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:02:36.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:02:48.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:03:00.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:03:12.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:03:24.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:03:36.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:03:48.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774500&quot; lon=&quot;-122.418700&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:04:00.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br><br>  &lt;!-- PHASE 4: MOVING AGAIN — turning and walking out --&gt;<br>  &lt;!-- Changing both lat and lon = diagonal movement / turn --&gt;<br>  &lt;wpt lat=&quot;37.774480&quot; lon=&quot;-122.418550&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:04:12.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774460&quot; lon=&quot;-122.418400&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:04:24.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774440&quot; lon=&quot;-122.418250&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:04:36.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br><br>  &lt;!-- PHASE 5: OUTSIDE — crossed boundary, left area --&gt;<br>  &lt;wpt lat=&quot;37.774420&quot; lon=&quot;-122.418100&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:04:48.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br>  &lt;wpt lat=&quot;37.774400&quot; lon=&quot;-122.417950&quot;&gt;<br>    &lt;ele&gt;10&lt;/ele&gt;<br>    &lt;time&gt;2026-01-01T08:05:00.000Z&lt;/time&gt;<br>  &lt;/wpt&gt;<br><br>&lt;/gpx&gt;</pre><p><strong>How timestamps control speed</strong></p><p>Look at the early part of the sample file. From 08:00:00 to 08:03:00, the longitude increases by roughly 0.0000166 per 12-second step — a slow walking pace. Then around 08:04:00, the increments get smaller — the device slows down. Around 08:08:00, the increments get larger again — it picks up pace. All of this is just timestamp spacing and coordinate distance. No speed field exists. AI understands this and will calculate the right coordinate spacing for whatever speed you describe.</p><p><strong>How to prompt AI to generate your iOS GPX</strong></p><p>Same approach as Android, but explicitly tell AI to use the iOS waypoint format. Give AI:</p><ul><li>Start and end coordinates</li><li>Any stops along the way with dwell time (“sit at a cafe for 5 minutes”, “wait at a park for 10 minutes”)</li><li>Speed at each part (“walking”, “jogging”, “driving”)</li><li>Any boundaries to cross and at what radius</li></ul><p>Example prompt:</p><blockquote><em>“Generate a GPX file for iOS location simulation. Start at [coordinates], walk at normal walking pace toward [coordinates], enter a circular boundary of 100m radius centered at [coordinates], slow down and walk around inside it, sit stationary at [coordinates] for 5 minutes simulating waiting at a cafe, then walk out and exit at [coordinates]. Use timestamps starting at 2026–01–01T08:00:00Z with 12 seconds between each waypoint. Use the attached GPX file as the exact format reference — use </em><em>&lt;wpt&gt; tags directly under </em><em>&lt;gpx&gt;, no </em><em>&lt;trk&gt; or </em><em>&lt;trkseg&gt; wrapper, same XML structure, same timestamp format.&quot;</em></blockquote><p>AI will generate a complete file with the correct number of waypoints, correct timestamp spacing for the speed you described, and repeated coordinates for stationary phases. Drop it into Xcode, rebuild, and your route plays immediately.</p><h3>iOS Simulator location options</h3><p>Once your app is running on the simulator, you can also control location simulation directly from the simulator menu. Go to the simulator window → Features → Location. You will see the following options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2H3tg5BkvXU2iMWsOJtnw.jpeg" /></figure><p><strong>None</strong><br>Disables all location simulation. The simulator reports no location to the app at all. Use this when you want to test how your app behaves when location is completely unavailable. If you select this, your GPX file is ignored entirely.</p><p><strong>Custom Location<br></strong>You can enter the lat long co-ordinates and simulator location will be set with that. This is what you select when you want the simulator to play your GPX file. When this is chosen, the simulator sets your one time location and picks up the GPX you set in Xcode’s scheme and simulates movement along it. This is your go-to option for testing any location-based feature with a custom route.</p><p><strong>City Run</strong><br>A pre-built running route through a city at jogging pace. Useful for quickly testing a fitness or tracking feature without creating your own GPX. Selecting this overrides your GPX file — the simulator ignores it and uses this built-in route instead.</p><p><strong>City Bicycle Ride</strong><br>A pre-built cycling route through a city at cycling pace. Same behaviour — overrides your GPX file.</p><p><strong>Freeway Drive</strong><br>A pre-built driving route at highway speed. Good for testing features that depend on fast movement or vehicle detection. Also overrides your GPX file.</p><p><strong>Apple</strong><br>Sets the location to Apple’s headquarters in Cupertino, California as a fixed single point. No movement. Useful as a quick sanity check when you just need a valid location fix and don’t care about movement.</p><p>The rule is simple: if you want your custom GPX to play, select Custom Location option. Any other option overrides your GPX and the simulator uses its own built-in path or fixed point instead.</p><p><strong>Important — you cannot combine options</strong></p><p>There is no way to mix your custom GPX with any of the built-in routes. I spent a good amount of time confused about this during testing, so worth calling out explicitly.</p><p>Here is exactly how each combination behaves:</p><p><strong>Load GPX in Xcode scheme + select Custom Location in simulator</strong><br> → Simulator sets simulator location as Custom Location co-ordinates and plays your GPX. This is the only combination that uses your file.</p><p><strong>Load GPX in Xcode scheme + select None in simulator</strong><br> → Simulator reports no location at all. Behaves exactly as if location services are turned off. Your GPX is completely ignored.</p><p><strong>Load GPX in Xcode scheme + select Freeway Drive / City Run / City Bicycle Ride / Apple in simulator</strong><br> → Simulator throws away your GPX entirely and uses the selected built-in route. Your file is ignored.</p><p>The only way your GPX gets used is: load it in the Xcode scheme before building, then select <strong>Custom Location</strong> in the simulator after the app launches. Everything else ignores your file.</p><p>Location simulation is one of those things that looks like it should take 10 minutes to set up and somehow takes half a day the first time. Between format differences, Xcode scheme settings, simulator overrides, and figuring out why your GPX is being ignored — there are enough small traps to slow anyone down.</p><p>Once it clicks though, it becomes one of the most valuable tools in your workflow. A well-crafted GPX file lets you reproduce any location scenario in seconds, share it with teammates so everyone tests the same route, and catch bugs that would otherwise require a physical trip to a real location.</p><p>Use AI to generate your GPX files. Describe your route in plain English, hand it the format reference, and it will do the coordinate math for you. What used to take an hour of manual coordinate calculation now takes two minutes.</p><p><em>If this was useful, a clap or follow goes a long way — it helps this reach engineers who’d actually use it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d324fa3eb917" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Deep Research Unfamiliar React Native, Android, and IOS topics with AI]]></title>
            <link>https://medium.com/@varunkukade999/how-i-deep-research-unfamiliar-react-native-android-and-ios-topics-with-ai-74ae5c55d2d3?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/74ae5c55d2d3</guid>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 06:53:04 GMT</pubDate>
            <atom:updated>2026-06-21T06:57:13.259Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical workflow for building deep technical understanding and making engineering decisions faster.</p><p>As React Native engineers, we constantly have to pick up technologies we’ve never touched before.</p><p>Push notifications. Deep linking. In-app purchases. Bluetooth. Camera APIs. Widgets. Some native Android or iOS capability your product suddenly needs.</p><p>The challenge is not finding information. The challenge is building enough understanding to actually answer:</p><ul><li>How does this technology work under the hood?</li><li>What are the real platform limitations?</li><li>Which implementation approach makes sense for my use case?</li></ul><p>Today, AI can cut through this dramatically. But only if you use it correctly.</p><p>I also use AI heavily as a research partner — to understand unfamiliar technologies deeply, from scratch, on my own timeline.</p><p>Over the last year, this has helped me go from zero knowledge to production-grade clarity on several complex Android and iOS topics — much faster than documentation, blog posts, or videos alone ever could.</p><p>This article explains the exact workflow I use.</p><h3>The Old Way</h3><p>Before AI, picking up an unfamiliar technology took weeks. Stack Overflow rabbit holes. Documentation you barely understand because you don’t have the vocabulary yet. A colleague who’s slightly less lost than you.</p><p>The problem was never intelligence. It was time and access.</p><p>AI changes this. But only if you use it correctly.</p><p>Most engineers use it like Google — type a question, get an answer, move on. That works for quick lookups. For actual research, it fails. Research is a structured conversation where <em>you</em> are steering — building a mental model, testing it against reality, challenging answers, and arriving at something concrete and usable.</p><p>The strategies below show exactly how to do that.</p><h3>What This Is Not</h3><p>This won’t make you a domain expert. After these sessions, I don’t have the lived expertise that comes from years of building in a specific area. There are edge cases I haven’t seen, patterns that only reveal themselves over time.</p><p>What I do have: precise, verified understanding of the specific question I went in to answer. I know the decision I needed to make, why I made it, and how to defend it.</p><p>In most production contexts, that’s exactly what’s needed — and it’s available in days, not months.</p><p>Know the difference. Use this for what it’s actually good at.</p><h4><strong>Quick note before we start:</strong></h4><p>Do your research in Claude, ChatGPT, or your preferred AI chat tool — not Cursor or any coding assistant. Coding tools are heavily optimized for writing and editing code. Their system prompts work against you when you’re trying to learn or research something deeply.</p><p>That said, if your research is tied to your existing codebase, don’t ignore it. Use Cursor to extract the relevant context first — what tech stack you’re using, which versions, how the relevant flow works, what already exists. Get that as a clean summary. Then bring it into Claude or ChatGPT as a source of truth at the start of your research session. Best of both worlds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*rDD7kvFc9yoKP492-QLFWg.jpeg" /></figure><h3>Strategy 1: Lead With Context, Not Questions</h3><p>Most people open with a question. “How does Android Foreground Service work?” or “What’s the best approach for background location?”</p><p>Wrong starting point.</p><p>Before asking anything, give the AI everything it needs: what you’re trying to build, what you already tried, why it failed, and what decision you need to reach.</p><p>Here’s how I opened a session on precise mobile location detection:</p><blockquote>Goal: Detect user entry into geographic zones (~20m radius). <br>What I tried: react-native geolocation library. It failed — native geofencing APIs have accuracy floors around 100–200m. I need to decide the right architecture. <br>Here are my constraints: [constraints]. <br>Here’s what I already know: [knowledge]. <br>Here’s where I’m confused: [confusion].</blockquote><p>No question yet. Just context.</p><p>Think of it as briefing a consultant. A consultant walking in blind gives generic advice. One who knows your problem, constraints, and what’s already failed gives advice that fits <em>you</em>.</p><p>Write the brief first. Then ask.</p><h3>Strategy 2: Bring Your Own Options. Ask AI to Evaluate Them.</h3><p>“What should I do?” is the worst research question you can ask.</p><p>The AI will answer with one option — probably the most common one — and you’ll have no way to know what it didn’t consider.</p><p><strong>Better move:</strong> think enough to generate 2–4 options yourself. Then ask for a comparative evaluation.</p><p>When researching Android Foreground Service types, I didn’t ask “which type should I use?” I said:</p><blockquote>“Here are 4 options I see: <br>1. specialUse type only, <br>2. two separate FGS instances, <br>3. switching between them dynamically, <br>4. combining multiple types. Evaluate each against my constraints. <br>Tell me which is best and why the others fall short.”</blockquote><p>Now the AI is forced to compare — not just recommend. It surfaces tradeoffs you hadn’t seen.</p><p>There’s a second benefit: once you’ve generated options, you can actually judge whether the AI’s evaluation is correct. You have opinions. You can push back.</p><p>Arrive with options. Never arrive empty-handed.</p><h3>Strategy 3: Declare Your Ignorance Explicitly</h3><p>Most engineers hide how much they don’t know when asking questions. That’s exactly backwards for research.</p><p>When I started researching NFC and HCE — the technology behind tap-to-pay — I said directly:</p><blockquote>“Assume I am a complete beginner. I don’t know anything about this.”</blockquote><p>And when a term came up I didn’t understand:</p><blockquote>“What is ‘terminal’ here? Does a payment device have a terminal itself?”</blockquote><p>Without this instruction, the AI fills in assumed knowledge — skips definitions, uses jargon, references concepts you’ve never seen. You walk away with an answer you only half understood.</p><p>With it, everything is explained from the ground up. You don’t just get the answer — you get the framework to understand <em>why</em> it’s the answer.</p><p>Declare your ignorance. The AI will serve you better for it.</p><h3>Strategy 4: Narrow Scope Deliberately</h3><p>Research conversations naturally expand. You ask one thing, the AI mentions three related things, you follow threads — and fifteen topics later you’ve decided nothing.</p><p>Whenever a session got too wide, I cut it explicitly:</p><blockquote>“For now, let’s focus on Android only. Don’t mention iOS.”</blockquote><p>Or:</p><blockquote>“Let’s resolve this one question fully before moving to the next.”</blockquote><p>This matters more than it sounds. When absorbing something unfamiliar, you can only truly process so much at once. Five insights delivered together means two retained. One insight, fully understood, means one permanently learned.</p><p>Going wide feels like progress. It rarely is.</p><p>Go narrow. Go deep. Move on only when the current thing is solid.</p><h3>Strategy 5: Demand Web Evidence, Not AI Memory</h3><p>At some point in every session, the AI will give you a confident answer from its training data.</p><p>Don’t accept it.</p><p>AI training data has a cutoff. On niche, platform-specific behavior — iOS Keychain internals, Android API changes, certification requirements — it can be confidently, completely wrong. Not uncertain. <em>Confident and wrong.</em> That’s dangerous.</p><p>Whenever recency mattered, I blocked it from memory:</p><blockquote>“Check the web first. Give me your analysis and all the web links I should explore as evidence. Don’t answer from training data alone.”</blockquote><p>Then I’d go verify those links myself.</p><p>For official platform behavior:</p><blockquote>“Web fetch all the links above. If that’s not enough to reach a conclusion, check the official Apple documentation directly.”</blockquote><p>The evidence hierarchy is: official docs → recent web sources → AI training data. AI is excellent for structure and reasoning. For ground truth on platform APIs, always push it to the web first.</p><p><em>One honest note: some things AI genuinely can’t find — certain certification costs, proprietary pricing, vendor-specific details. If it’s drawing blanks after searching, you’ll need to research that part yourself.</em></p><h3>Strategy 6: Inject Real Test Results to Course-Correct</h3><p>Theory and reality don’t always match. Especially on mobile.</p><p>You can have a clean theoretical discussion with AI — and then run a real device test that completely contradicts it. Most engineers get confused and start doubting themselves.</p><p>Don’t. Trust the test.</p><p>When researching Android Foreground Service behavior for background location, the AI gave me a clear answer on which permissions were required. I ran a device test with a specific configuration and observed something completely different.</p><p>I came back with the exact sequence:</p><blockquote>“I just tested this.<br>Here’s exactly what I did: [steps]. <br>Here’s exactly what happened: [result]. <br>This contradicts what you said earlier. Explain why.”</blockquote><p>This forces the AI to reconcile theory with observed reality — not double down on theory. Often the explanation reveals something subtle the initial answer missed. Sometimes it just reveals the AI was wrong.</p><p>Your device test is the highest-quality evidence in any conversation. It’s real. It’s your exact setup. It’s undeniable.</p><p>When reality contradicts the answer, inject it and demand a reconciliation.</p><h3>Strategy 7: Set Confidence Thresholds With Real Stakes</h3><p>“Is this correct?” is a weak question. It invites a weak answer — <em>“yes, generally speaking, though it depends on…”</em></p><p>Instead, set an explicit bar and tell the AI what’s riding on it.</p><p>When researching whether a specific type of tracking is possible in iOS’s fully killed app state, I said:</p><blockquote>“I need to be completely certain before making any decisions based on this. If someone verifies this directly with a core Apple engineer tomorrow, it has to hold up. Give me that level of certainty on every line. If you’re not sure about something, tell me explicitly — don’t give me confident-sounding answers that aren’t solid.”</blockquote><p>This does two things. It tells the AI the stakes are real. And it gives it explicit permission to say “I’m not sure” — without which, AI tends to hide uncertainty behind polished language.</p><p>Caveats get surfaced. Assumptions get flagged. You know exactly what’s solid and what isn’t.</p><p>Set the bar explicitly. Watch the answer quality change.</p><h3>Strategy 8: Split One Problem Into Sub-Questions</h3><p>Complex problems almost always have multiple distinct issues inside them. Treating them as one gets you one blended answer — and you miss that each piece has a different root cause.</p><p>Split before you ask.</p><p>When debugging a Face ID issue after app reinstall, two things were broken simultaneously:</p><ol><li>The permission prompt wasn’t appearing</li><li>Face ID wasn’t validating even when the screen showed up</li></ol><p>Instead of “why is Face ID broken?”, I split them:</p><blockquote>“Main question: why didn’t it ask for Face ID permission? Second question: why didn’t it validate Face ID when the screen appeared? Treat these as two separate problems.”</blockquote><p>They had completely unrelated root causes. The permission issue was iOS persisting TCC state across reinstalls at the OS level. The validation issue was a silent fallback in the authentication policy that triggers without any visible error. One blended answer would have missed both.</p><p>Any time a question feels complicated, ask yourself: is this actually two questions? Split them, sequence them, answer one at a time.</p><p>A focused question gets a precise answer. A blended question gets a blended answer — and blended answers create the illusion of understanding without the substance.</p><h3>Strategy 9: Write Your Understanding First. Ask AI to Audit It.</h3><p>Most people use AI as a teacher — ask, receive, absorb. That’s passive. And passive research has a hidden problem: you think you understood, but you never verified that you did.</p><p>After enough of a conversation to form an understanding, stop asking questions. Write out what you understood — in your own words. Then ask the AI to go through it line by line.</p><p>When researching iOS location behavior across app states — foreground, background, suspended, killed — I wrote out the entire thing myself. Every state, every scenario, what’s possible and what isn’t. Tables, bullet points, edge cases. Then:</p><blockquote>“This is my complete understanding. Go through it line by line, very carefully. Tell me where I’m wrong, where I’m missing something, and where I’ve got it right.”</blockquote><p>Writing it yourself surfaces the gaps immediately. You can follow an explanation perfectly and still be unable to reconstruct it. The moment you try to write it, you find exactly what you only half understood.</p><p>Asking AI to audit instead of explain flips the dynamic — it’s now responding to <em>your</em> model, not building its own. You own the understanding. The AI is just the validator.</p><p>Don’t receive explanations. Write your understanding. Get it audited. That’s how you actually know you got it.</p><h3>Strategy 10: Reverse-Engineer How Famous Paid Tools Solve the Same Problem</h3><p>When you’re stuck on a hard technical problem, there’s a good chance someone has already solved it and built a product around it.</p><p>Don’t ask for a generic solution. Point directly at that product and ask the AI to reverse-engineer how it works under the hood.</p><p>When I hit a hard iOS location limitation — certain tracking simply isn’t possible in specific app states — I didn’t just accept the theoretical answer. I said:</p><blockquote>“Radar is a well-known production-grade location SDK. They’ve clearly already solved this. Go deep on what they’re actually doing under the hood.”</blockquote><p>Along with this I shared Radar’s documentation links, guides, and technical references for the AI to work through.</p><p>This produces completely different quality research. A general question gets a general answer. Pointing at a real production tool forces engagement with an actual proven implementation — what techniques are being used, what tradeoffs were made, and why.</p><p>Any time you’re stuck, ask: who has already solved this? Then ask the AI to open it up.</p><h3>Strategy 12: Don’t Leave Research as a Conversation. Convert It Into Something Usable.</h3><p>Research that stays inside a chat window has limited value.</p><p>At the end of every major session, I’d ask the AI to convert the conclusions into a standalone artifact — a structured technical document, a written position on a decision, a clear explanation of why something won’t work and what to do instead.</p><blockquote>“Based on everything we concluded, give me a clean written position on this. Someone who wasn’t in this conversation should be able to read it and fully understand the decision and the reasoning behind it.”</blockquote><p>I treated the AI as the drafter. I was the editor who owned the claim.</p><p>There’s a secondary benefit here: if the AI can’t produce a clean, coherent artifact, it means the research itself isn’t solid yet. Muddled output is a signal to go back and close the gaps.</p><p>Research isn’t done when you understand something. It’s done when you can produce something from that understanding.</p><p>Always convert.</p><h4>The Research Loop — How a Full Session Actually Runs</h4><p>The strategies above aren’t separate techniques you pick from a menu. They form a loop — a sequence that plays out across every serious research session.</p><h3>What This Means for Engineers in the AI Era</h3><p>Deep accumulated knowledge in a specific domain is no longer a monopoly. AI gives anyone access to it on demand. The engineer who spent five years becoming the iOS location expert can be caught up to — in days — by someone with the right research methodology.</p><p>What AI cannot replace is structured thinking. Knowing when to push back, when to trust an answer, when to narrow scope, when to demand evidence. That’s still entirely human. The strategies in this article aren’t AI techniques. They’re thinking techniques that use AI as a surface.</p><p>Engineers who develop this skill can enter any unfamiliar domain with confidence and come out with something real. That’s a different kind of engineer than what existed five years ago.</p><h3>The Real Skill</h3><p>The engineers who thrive won’t be the ones who know the most. They’ll be the ones who can learn anything — fast, rigorously, and in a way that produces real output.</p><p>Every strategy here started as something I did instinctively in a research session. I didn’t set out to build a methodology. I just noticed what worked.</p><p>Then I fed my own conversations into AI and asked it to extract the patterns. This article is the result.</p><p>That’s not a footnote. That’s the whole point.</p><p><em>If this was useful, a clap or follow goes a long way — it helps this reach engineers who’d actually use it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74ae5c55d2d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Stopped Writing Code for 6 Months. Here’s What 250,000 AI-Generated Lines Taught Me]]></title>
            <link>https://medium.com/@varunkukade999/the-best-engineers-of-the-next-decade-wont-be-the-best-coders-d4fd418f1712?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4fd418f1712</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 14:39:39 GMT</pubDate>
            <atom:updated>2026-06-21T05:19:23.545Z</atom:updated>
            <content:encoded><![CDATA[<p>Six months ago, I stopped writing code.</p><p>Not because I burned out. Not because I switched roles. I just… stopped. And in those six months, I shipped more than I ever did when I was heads-down in an IDE.</p><p>At my work, I shipped products. Orchestrated agents that wrote 2,50,000+ lines of code across entire new codebases, even rewriting pre-ai era codebases. Wrote complete technical documentations. Built demo videos of a product — entirely through AI (Cursor + browser mcp + playwright). Did deep technology research that used to take weeks. Reverse-engineered a SaaS tool we were paying for and prototyped an in-house alternative.</p><p>And here’s the part that’ll surprise you: I’m not running some expensive enterprise AI setup. Most of this runs on a cursor $20 subscription. The edge isn’t budget. It’s approach.</p><p>If you’re a software engineer reading this — especially a senior one — I’m not here to scare you. I’m here to tell you what the job actually looks like right now, from someone who’s been living it. Because the conversation online is mostly noise. Either “AI will replace everyone” panic or “AI is just costlier than humans” dismissal. Neither is right.</p><p>The real shift is quieter. And more interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9D77cYXeCrpPrvVp-iWmQ.png" /></figure><h3>The Job Didn’t Disappear. It Changed Shape.</h3><p>Every technology wave has felt threatening until people figured out how to ride it. That’s not a comfort — it’s a pattern.</p><p>The engineers who got displaced weren’t replaced by machines. They were replaced by engineers who knew how to use the machines.</p><p>What’s changing now isn’t whether you write code. It’s whether you can <strong><em>think clearly enough</em></strong> to direct an AI that writes it for you. That’s a different skill. And honestly? Many people may be terrible at it — not because they’re not smart, but because they’ve never been trained to communicate with the precision that great prompting requires.</p><p>The engineers who will thrive aren’t the ones who resist this. They’re the ones who become so good at thinking, understanding, orchestrating or communicating with AI that they multiply their output by 5x, 10x, without multiplying their hours.</p><p>Here’s what I’ve learned.</p><h3>AI Orchestration Is Here to Stay</h3><p>Here’s how I think about where this is heading.</p><p>The skill that will matter most isn’t coding. It’s learning how to communicate with AI, teach it, and get real work out of it. The engineer of the near future is an techincal agent manager — is not somehow who knows the syntax. Its someone who knows technical + product direction of product, someone who orchestrates multiple AI agents simultaneously toward a coherent product goal.</p><p>But here’s what nobody talks about enough: to orchestrate AI well, you need to be able to verify it and direct it to achieve business outcome. And to verify &amp; direct it, you need judgment, domain &amp; product knowledge. The ability to look at what the AI produced and know — instinctively, technically — whether it’s going in the right direction or quietly heading off a cliff.</p><p>This becomes more and more important based on the scale of product. You can’t rely completely on AI / vibe coding for a product serving millions of customers daily / lot of concurrent users. One wrong technical decision by it &amp; will collapse the revenue and profits in future.</p><p>AI has vast knowledge. Far more than any single human. But it has no compass. It doesn’t know if it’s in right direction according to expectation of us. It just generates confidently in whatever direction the context points it. <em>You</em> are the compass + context. If you can’t evaluate the output, you can’t catch the drift. And AI drifts.</p><p>This is why judgment and domain knowledge aren’t becoming less important — they’re becoming the only things that matter. AI is a force multiplier. If your judgment is strong, it amplifies good decisions at speed. If your judgment is weak, it amplifies bad ones just as fast, and with more confidence.</p><p>The other underrated skill: learning speed. How fast can you grasp a new concept, a new domain, a new technology you’ve never touched? AI gives you access to expertise you don’t have. But you need enough baseline understanding to ask the right questions, push back when something feels wrong, and know when you’re out of your depth. The engineers who will thrive aren’t just good orchestrators — they’re fast learners who can expand their surface area of judgment continuously.</p><p>The org chart implications of this are significant. A company running 1000 people today will run 100–150 managing 800 agents in a few years. In early-stage startups it goes further — one person owning an entire product end to end. No frontend team. No backend team. No separate QA. Just an engineer with strong enough judgment to drive the whole thing.</p><p>Think about what that actually means. If AI does frontend work in a fraction of the time — where does that freed time go? More frontend, or backend, or testing, or all three. The role boundaries dissolve. The bottlenecks disappear. What remains is: <em>can you think clearly about the whole product, and verify what’s being built?</em></p><p>That’s the job. And honestly, it’s a more interesting than what came before it.</p><h3>First: Forget TokenMaxxing. Do ValueMaxxing.</h3><p>The most common mistake I see is people trying to squeeze more output per prompt. More lines of code. More features. More content. Just… more.</p><p>That’s the wrong optimization.</p><p>The question isn’t <em>how much</em> can the AI produce. It’s <em>how much business value</em> flows from each token you spend. One well-crafted prompt that correctly ships a feature is worth infinitely more than ten sloppy prompts that produce code you have to throw away.</p><p>Call it ValueMaxxing. Every token you spend should be working toward the highest-leverage outcome. If it isn’t, you’re just burning credits to feel productive.</p><h3>The Prompt Is the Job Now</h3><p>There’s a saying I keep coming back to: <em>“If I have five hours to finish a task, I’ll spend four writing the prompt.”</em></p><p>That sounds extreme until you’ve experienced what a bad prompt costs you. Wrong architecture. Hallucinated edge cases. Code that works in isolation and breaks everything in context. You don’t save time by writing a quick prompt. You just move the rework to later.</p><p>Here’s how I think about prompting now:</p><p><strong>Write it, then become the AI.</strong> Before you send anything, re-read your prompt and imagine you’re the model receiving it. Would you know exactly what to do? Or would you be filling in gaps with assumptions? Every assumption the AI makes is a potential failure point.</p><p><strong>Front-load context like you’re briefing a new hire.</strong> I assume the AI knows nothing about my codebase, my product, my constraints, my team’s decisions. Not because it’s dumb — but because context is cheap and assumptions are expensive. More context means better retrieval, better reasoning, better output.</p><p><strong>Say what you don’t want. Two or three times.</strong> This sounds redundant until you’ve watched an AI confidently do the exact thing you were trying to prevent. Repeating your constraints isn’t nagging. It’s signal amplification. The AI takes it seriously.</p><p><strong>End every prompt with: “Ask me if any doubts.”</strong> AI doesn’t ask questions. It assumes. And some assumptions will cost you. This one sentence changes the dynamic — it’s an explicit invitation to surface uncertainty instead of bury it.</p><p><strong>Never write your own prompts from scratch.</strong> I use Claude to write the prompt. I give it my rough thinking, my constraints, what I want to avoid, and ask it to produce a structured prompt I can use. Then I review that prompt, refine it, and give it to the agent doing the actual work. Yes, it’s a layer of indirection. It’s worth every second.</p><h3>Context Engineering: The Thing Nobody Talks About Enough</h3><p>Prompt engineering gets all the attention. Context engineering is where the real leverage is.</p><p>Here’s what I mean. Every time you start a new agent session, you’re starting from scratch. If you’ve been repeating your product context, team conventions, architectural decisions, and coding standards in every single prompt — you’re doing it wrong.</p><p>Build a single source of truth for your context. Your product’s purpose. The decisions you’ve made and why. What patterns to follow and which to avoid. What already exists that the AI should be aware of. Store it somewhere every agent session can access — a CLAUDE.md, cursor rules, a shared doc — wherever makes sense in your setup.</p><p>This isn’t just about saving tokens. It’s about consistency. The AI that works on your codebase today should behave the same as the one that works on it next week. That only happens if the context is stable and accessible.</p><p>Correct rules and context improve output quality by at least 50%. That’s not an estimate. That’s what I’ve experienced.</p><h3>The Foundation Is Everything</h3><p>AI is only as good as what you build on.</p><p>Give it a bad architecture, unclear conventions, or a messy codebase as context — and even the best model will faithfully extend the mess. It won’t warn you. It won’t push back. It’ll just build confidently on a cracked foundation.</p><p>This is the part most people skip when they talk about AI-generated code. They focus on the output. But the input — the foundation you hand it — determines everything.</p><p>At my workplace, we recently shipped a product built entirely with an AI-first approach in 5x-10x less time &amp; with 2x less people in the team compared to pre-ai era. Every step human-guided, every output reviewed before it moved forward. The result was something I genuinely didn’t expect: virtually zero production bugs. Not fewer than usual. Almost none.</p><p>That changed how I think about this whole space.</p><p>AI, when directed well, is remarkably consistent. It doesn’t have bad days. It doesn’t cut corners at 11pm before a deadline. It doesn’t carry baggage from the last sprint. When the foundation is solid and the context is clean, it produces code that’s more reliable than what most teams ship under normal conditions.</p><p>Which leads to an obvious conclusion: every legacy codebase is eventually getting rewritten through AI. Not as an experiment — as a business decision. The technical debt sitting in most companies today was written by humans under pressure, over years, with shifting requirements and inconsistent standards. AI will clean it up better than any refactor sprint ever could.</p><p>The foundation was always the most important part of building software. AI just made that more true.</p><h3>Simulate a Team. Even If You’re Working Alone.</h3><p>One of the more counterintuitive things I’ve started doing: simulating a software development hierarchy through agents.</p><p>Lead engineer. Senior engineers. Junior engineers. Each with different roles in the pipeline.</p><p><strong>You give the “senior” the planning responsibility — break down the problem, design the approach. The “lead” review plan for approach, choosen strategy for scale, regressions and edge cases. The “juniors” execute discrete, well-scoped tasks.</strong></p><p>or</p><p><strong>You give the “lead” the planning responsibility — break down the problem, design the approach. The “seniors” review for regressions and edge cases. The “juniors” execute discrete, well-scoped tasks.</strong></p><p>or if you dont have any limits on tokens + unlimited AI budget,</p><p><strong>use lead for everything.</strong></p><p>But its bad approach. Think — In real world, does lead execute everything by itself? No. They delegate the tasks.</p><p>This is called model routing. This sounds theatrical. But here’s why it works: Lead agent is very good at thinking and designing the solution which works across the future scale of product. Junior agent is very bad at planning but is very good at execution once it knows what to execute. You use the strengths accordingly.</p><h3>Give the Task Weight</h3><p>One of the strangest things I’ve discovered is that AI performs noticeably better when it understands what is actually at stake.</p><p>Most prompts only describe the task:</p><blockquote><em>Build this feature.</em></blockquote><blockquote><em>Fix this bug.</em></blockquote><blockquote><em>Refactor this component.</em></blockquote><p>But that’s not how real engineering works. In reality, every technical decision exists inside a larger context. Users depend on the product. Revenue depends on the product. Other engineers depend on the product. Future architectural decisions depend on the product.</p><p>When humans understand the consequences of failure, they naturally become more careful. More thorough. More skeptical of their own assumptions.</p><p>I’ve found AI behaves similarly. AI, by default, doesn’t take you seriously. It optimizes for plausibility, not rigor. Give it a generic task and it’ll often produce a generic answer. Not because the model is bad, but because you’ve given it no signal about how careful it needs to be.</p><p><strong>The quality of reasoning changes when you communicate the weight of the problem.</strong></p><p>Instead of only describing the task, describe the environment:</p><ul><li>This is a production system.</li><li>Real users depend on this workflow.</li><li>Regressions have business consequences.</li><li>Incorrect assumptions can impact customers.</li><li>The output will be reviewed and deployed, not discarded.</li><li>Other engineers are depending on this solution being correct.</li></ul><p>The goal isn’t drama. The goal is context. Without context, the AI optimizes for producing a plausible answer. With context, it starts optimizing for producing a correct answer.</p><p>I’ve consistently noticed that when I provide stakes, accountability, and context around why something matters, the quality of reasoning improves. The model explores more edge cases. It becomes more conservative about risky changes. It spends more effort validating assumptions. It asks better questions.</p><p>I’ve even found that explicitly communicating the seriousness of a task helps:</p><blockquote><em>This is a critical production change.</em></blockquote><blockquote><em>Incorrect assumptions here could impact customers.</em></blockquote><blockquote><em>Take your time. Challenge your own conclusions. Verify your reasoning before responding.</em></blockquote><p>I can’t fully explain why this works. My guess is that the model has learned from millions of examples where words like “critical”, “production”, “customer-facing”, and “high-risk” are associated with more rigorous engineering behavior.</p><p>Whatever the reason, the effect is noticeable. Most importantly, the AI stops treating the task like an isolated coding exercise and starts treating it like a change being made to a living system. That’s ultimately what engineering is. Not writing code. Understanding the consequences of writing the wrong code.</p><p>The best prompts don’t just describe the task.</p><p>They describe the responsibility that comes with it.</p><h3>The Pipeline That Actually Works</h3><p>For any significant piece of work, I follow a specific sequence. Not optional. Every time.</p><ol><li><strong>Plan in Composer.</strong> Generate a detailed plan with good amount of context on what and how I want it. Not code — just the plan.</li><li><strong>Review with a higher model (Opus).</strong> Ask it specifically: <em>“Do you see any regression risks or architectural issues with this plan? Be blunt. Don’t just agree.”</em> Ask it to produce a handoff document.</li><li><strong>Feed the handoff back.</strong> Update the plan based on the review. Now the executing agent gets a cleaner brief.</li><li><strong>Execute in Composer.</strong> One task per prompt. One thing at a time.</li><li><strong>Review output with Opus.</strong> Fresh instance. Fresh eyes. No context bias from the execution session.</li></ol><p>The verification step matters more than people realize. Don’t verify in the same session that produced the work. Open a new chat. The AI doesn’t know what it was trying to do — it can only evaluate what’s actually there. That’s exactly what you want.</p><p>Think about your workplace:</p><p>You don’t ask the engineer who wrote the feature to be the only reviewer.</p><p>Same rule applies here.</p><h3>One Prompt. One Task. Non-Negotiable.</h3><p>Humans lose focus when context-switching between tasks. So does AI.</p><p>When you ask an agent to do five things in one prompt, it does five things poorly. Worse, it does them simultaneously, and you lose the ability to course-correct at each step.</p><p>One prompt. One task. It feels slower. It isn’t. The rework you avoid more than compensates.</p><h3>How to Actually Fix Bugs</h3><p>Most people prompt their AI agent to fix a bug. That’s the mistake.</p><p>Think about how you’d actually solve it yourself. First, you find the root cause. Then you fix it. Those are two separate cognitive tasks, and conflating them is how you get patches that hide symptoms instead of solving problems.</p><p>I’ve started prompting in two distinct phases:</p><p><strong>Phase 1:</strong> <em>“Debug the root cause first and go deep. Until you are 100% confident on the root cause, don’t tell me. Keep digging.”</em></p><p><strong>Phase 2:</strong> Once I have the root cause confirmed — then I prompt for the fix.</p><p>This produces dramatically better outcomes. The AI focuses. The root cause is understood. The fix actually addresses it.</p><p>Before either phase — ask the agent to deep-read the existing code first. Not to change anything. Just to understand. This prevents the worst failure mode: an AI that writes code without understanding what’s already there.</p><h3>Build the Self-Reflection Loop</h3><p>Standard AI interaction: you ask → it answers → done.</p><p>What you actually want: it acts → it reflects on its own output → it critiques itself → it fixes the gaps → it acts again → it moves forward autonomously.</p><p>You can build this explicitly into your prompts. Ask it to complete the task, then evaluate its own output against the original goal, then identify what’s missing or risky, then address those gaps, then repeat.</p><p>This is especially valuable for planning tasks, architectural decisions, and anything where edge cases matter. The AI catches things on the third pass that it missed on the first.</p><p>Use it for loops too. Ask it to refactor. Then ask it again for refactoring opportunities. Then again. Every pass finds something new.</p><h3>Invert The Prompt</h3><p>Instead of asking:</p><blockquote><em>“How should we build this?”</em></blockquote><p>Ask:</p><blockquote><em>“How would this fail in production?”</em></blockquote><p>or</p><blockquote><em>“Why would this architecture become a disaster in 18 months?”</em></blockquote><p>AI is often better at criticism than creation.</p><p>The fastest way to improve a design is to attack it first.</p><h3>Force Explicit Confidence Levels</h3><p>One trick I use:</p><p>Ask the AI to assign confidence.</p><p>Example:</p><blockquote><em>Confidence: 92%<br>Reasons confidence could be wrong:<br>Missing assumptions:<br>What I would verify next:<br>What would take confidence to 95+%</em></blockquote><p>This forces uncertainty to become visible.</p><p>The biggest AI failures aren’t wrong answers.</p><p>They’re wrong answers delivered with confidence.</p><h3>Decision Documents &gt; Prompts</h3><p>Most people obsess over prompts.</p><p>The best AI operators obsess over decisions.</p><p>Whenever AI helps make an important architectural decision, save:</p><ul><li>What was decided</li><li>Why it was decided</li><li>Alternatives considered</li><li>Tradeoffs accepted</li></ul><p>Then feed those documents into future sessions.</p><p>Otherwise AI keeps rediscovering the same decisions and suggesting things you’ve already rejected.</p><p>A company’s future context isn’t its codebase.</p><p>It’s its decision history.</p><p><strong>Line:</strong></p><blockquote><em>AI forgets. Decision documents remember.</em></blockquote><h3>The Context Window Is Your New RAM</h3><p>One mistake I see constantly: people stay in the same AI conversation for far too long.</p><p>At first, this feels productive. The AI knows your project, remembers earlier decisions, and seems deeply familiar with the work. But underneath, something important is happening.</p><p>Every time you send a message, the model isn’t just reading your latest prompt. It’s processing your prompt alongside the conversation history that still fits inside its context window.</p><p>That context window is finite.</p><p>As conversations grow, the system has to make tradeoffs. Older parts of the discussion get compressed, summarized, or dropped entirely to make room for newer information. The AI tries to preserve what it thinks is important, but “important” doesn’t always match what <em>you</em> consider important.</p><p>That architectural decision you made 50 prompts ago? The critical constraint you mentioned at the beginning? The subtle product requirement that should never be violated? Those details can gradually disappear from the active context.</p><p>The result is what I call <strong>context drift</strong>.</p><p>The AI starts producing outputs that look reasonable but slowly move away from the original intent. Engineers often interpret this as the model becoming worse. In reality, the model may simply no longer remember the assumptions it was operating under.</p><p>If you’ve ever thought:</p><blockquote><em>“Why is it suddenly ignoring instructions I’ve already given it?”</em></blockquote><p>This is usually why.</p><p>Long-running conversations create an illusion of continuity. The AI feels like it remembers everything. It doesn’t.</p><p>The solution isn’t bigger prompts. It’s context management. When a project becomes large, start fresh sessions regularly.</p><blockquote>Move critical decisions into persistent documentation (like cursor rules). Keep a living source of truth for architecture, requirements, conventions, and constraints. Treat conversations as temporary working memory, not permanent storage.</blockquote><p>Because in an AI-first workflow, your context window is the equivalent of RAM.</p><p>And just like RAM, once it fills up, things start getting forgotten.</p><h3>The Bigger Picture</h3><p>I think companies are moving toward very small, very capable teams. Not because they want to cut costs — but because a team of engineers who can each direct AI across multiple verticals outperforms larger teams working the old way. Frontend. Backend. DevOps. Research. All of it.</p><p>The engineers who survive this aren’t the ones who can write the most code. They’re the ones who can think clearly about systems, communicate precisely, and orchestrate multiple agents toward a coherent goal.</p><p>You have to deeply understand what you’re building to prompt for it effectively. Vague thinking produces vague output. There’s nowhere to hide.</p><p>If you’ve been treating AI as a shortcut, you’re leaving most of the value on the table.</p><p>The real opportunity is in becoming someone who thinks better, communicates better, and directs better — using AI as a multiplier on judgment, not a replacement for it.</p><p>To stay updated on future articles, don’t forget to follow me! After following, you’ll get future articles right in your email inbox. Also, give this post <strong>50 claps 👏</strong> if you enjoyed this post and learned something useful. Your enthusiasm and support fuel my passion for sharing knowledge in the tech community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4fd418f1712" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading Hyperfuel: New Architecture, Expo Migration, 16 KB page size and edge to edge support]]></title>
            <link>https://medium.com/@varunkukade999/upgrading-hyperfuel-new-architecture-expo-migration-16-kb-page-size-and-edge-to-edge-support-f97518456b8f?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f97518456b8f</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 11:59:40 GMT</pubDate>
            <atom:updated>2025-11-03T11:59:40.337Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently at my workplace, Altir, we successfully migrated our production app, Hyperfuel, to React Native’s new architecture.</p><p>Believe me — this was hard. This was our first time upgrading React Native as a team, and we learned a lot along the way. It would have been manageable if it were just a minor version upgrade, but our migration came packed with multiple critical changes happening simultaneously:</p><ul><li><strong>Migration to the New Architecture</strong> — Moving Hyperfuel from the old bridge-based architecture to the new JSI-based architecture</li><li><strong>16KB Memory Page Size Support</strong> — Adapting our Android app to support devices with 16KB memory page sizes</li><li><strong>Android 15+ Targeting</strong> — Updating our target SDK to meet Android 15 requirements</li><li><strong>Edge-to-Edge UI</strong> — Implementing edge-to-edge display on Android 15+ devices</li><li><strong>Expo Library Migration</strong> — Moving various libraries to their Expo-managed counterparts</li><li><strong>Dependency Updates</strong> — Upgrading numerous third-party libraries to their latest versions</li></ul><p><strong>The Scale of Our Migration</strong></p><p>Hyperfuel uses <strong>50+ third-party libraries</strong>, making compatibility a major concern. Beyond standard app functionality, we also support <strong>live tiles</strong> that display real-time information using:</p><ul><li><strong>Android Foreground Services</strong> — We had forked the Notifee library, added custom layout code, and deployed it to production. During this migration, we updated to the latest version while resolving numerous conflicts.</li><li><strong>iOS Live Activities</strong> — We were using a native module to bridge between iOS and the JavaScript environment. As part of this migration, we converted it to a Turbo Module to align with the new architecture.</li></ul><p><strong>Why This Writeup Matters</strong></p><p>The motive of this writeup is simple: <strong>to save you time</strong>.</p><p>This migration took us countless hours of research, trial and error, and debugging sessions — effort we don’t want you to waste. This comprehensive guide will help you navigate your own new architecture migration with far less friction, whether you’re maintaining a simple app or a complex production system like ours.</p><p><strong>Why Upgrading Matters</strong></p><p>Upgrading to new React Native versions is essential to keep pace with the rapidly evolving React Native ecosystem. Every new version brings:</p><ul><li>Performance optimizations</li><li>New features and APIs</li><li>Better tooling and developer experience</li><li>Critical security patches</li></ul><p>About <strong>7–8 months ago</strong>, we had already completed extensive research on the migration process. Here’s what we learned from that research:</p><h3>⚙️ New Architecture (Fabric + TurboModules + JSI)</h3><p>The new architecture removes the bridge and introduces faster, more direct communication between JS and Native layers using <strong>JSI (JavaScript Interface)</strong>.</p><p><strong>Key Components:</strong></p><ol><li><strong>JSI (JavaScript Interface):</strong></li></ol><ul><li>Enables <strong>direct calls</strong> between JS and Native (no JSON serialization).</li><li>Much faster and <strong>synchronous</strong> when needed.</li><li>Allows JS to hold <strong>references to native objects</strong> directly.</li></ul><p><strong>2. TurboModules:</strong></p><ul><li>New way of building native modules using JSI.</li><li>Modules are <strong>lazily loaded</strong> (loaded only when needed), reducing startup time.</li></ul><p><strong>3. Fabric Renderer:</strong></p><ul><li>New rendering system for UI components.</li><li>Uses <strong>C++ shared code</strong> between platforms.</li><li>Offers <strong>synchronous UI updates</strong>, <strong>better performance</strong>, and <strong>layout consistency</strong> across Android and iOS.</li></ul><p><strong>4. Codegen:</strong></p><ul><li>Automatically generates type-safe interfaces between JS and Native using TypeScript/Flow annotations.</li><li>Reduces boilerplate and runtime errors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uo6TaVyCjVzHpZV46bF4qg.jpeg" /></figure><p>Upgrading to new architecture requires following at the start:</p><h4><strong>Deciding Which React Native Version to Upgrade To</strong></h4><p>React Native started supporting the new architecture as an opt-in feature long ago, but the team made it <strong>stable and enabled by default in version 0.76.0</strong>. This made our choice obvious.</p><p>The decision to enable the new architecture by default in 0.76.0 was only possible due to tremendous effort poured into fixing bugs and resolving issues in earlier versions. All that groundwork meant 0.76.0 could be released as a truly <strong>stable version</strong> with the new architecture ready for production use.</p><p><strong>Why 0.76.0 Was the Right Choice:</strong></p><ul><li><strong>Stability First</strong> — The new architecture was battle-tested and production-ready, not experimental</li><li><strong>Default Enablement</strong> — No complex configuration or feature flags needed</li><li><strong>Smaller Bundle Sizes</strong> — Android apps became <strong>3.8 MB smaller</strong> out of the box</li><li><strong>Community Support</strong> — Being the first stable release meant better documentation and community knowledge</li></ul><p>For teams considering migration, we strongly recommend targeting <strong>0.76.0 or later</strong>. Earlier versions with opt-in new architecture support might work, but you’d be taking on additional risk and complexity that has already been resolved.</p><h4><strong>Check Which Expo Version Supports the New Architecture</strong> <em>(Only if you want to install Expo alongside bare React Native)</em></h4><p>For this upgrade, we decided to migrate some of our libraries to Expo modules. We’ll discuss the “why” in detail later, but here’s what you need to know about version alignment.</p><p>We already had <strong>Expo SDK 49</strong> enabled in our project. Expo only maintains the <strong>latest 3 SDKs</strong>, and at the time of our migration, the latest SDK released by Expo was <strong>SDK 54</strong>. This meant we needed to decide which Expo version to upgrade to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYTJ-ajFcSTajqk-euUEZw.png" /></figure><p><strong>Understanding Expo’s Release Model</strong></p><p>The Expo framework is built on top of React Native. Every time Expo releases a new SDK, it comes packaged with:</p><ul><li>A specific React Native version</li><li>Specific versions of all Expo modules tested thoroughly with that React Native version</li></ul><p>This tight integration means <strong>less maintenance burden</strong> for the modules you use — a major advantage that influenced our decision to migrate some third-party libraries to Expo.</p><p><strong>Choosing Expo SDK 52</strong></p><p>Since we decided to target React Native <strong>0.76.0</strong>, Expo SDK 52 was the obvious choice. <strong>It’s critical to sync your core React Native version with Expo’s internal React Native version</strong> — mismatches can lead to subtle bugs and compatibility issues.</p><p><strong>Pro Tip:</strong> Expo SDKs always target the <strong>latest patch version</strong> within a minor React Native release. For example, if Expo SDK 52 says it supports React Native 0.76, it actually supports <strong>0.76.9</strong> (or whatever the latest patch is). You can verify this by checking Expo’s package.json:<br> 👉 <a href="https://github.com/expo/expo/blob/sdk-52/package.json">https://github.com/expo/expo/blob/sdk-52/package.json</a></p><p>This means when you install Expo SDK 52, you’ll automatically get the most stable patch version of React Native 0.76, which includes all the latest bug fixes.</p><h4><strong>Check if Every Library You Use is Compatible with the New Architecture</strong></h4><p>We use <strong>50+ third-party libraries</strong> in Hyperfuel, and it’s absolutely necessary that <strong>each library supports the new architecture</strong>. Even if just one library doesn’t support it, you can’t proceed with the upgrade — doing so could introduce compatibility issues that surface later in production.</p><p><strong>Our Research Process</strong></p><p>We went through each library’s GitHub page methodically, checking:</p><ol><li><strong>Issues section</strong> — Looking for bug reports related to new architecture</li><li><strong>Pull Requests section</strong> — Checking for pending compatibility PRs</li><li><strong>README</strong> — Looking for explicit new architecture support statements</li><li><strong>Discussions section</strong> — Finding community conversations about compatibility</li><li><strong>Releases section</strong> — Reviewing changelogs for new architecture mentions</li><li><strong>React Native Directory</strong> — Final verification at <a href="https://reactnative.directory/">https://reactnative.directory</a></li></ol><p><strong>What We Found</strong></p><p>Most of the time, we discovered one of these scenarios:</p><ol><li>The author had already released a new version supporting the new architecture</li><li>Someone had raised an issue requesting new architecture support (helping us gauge timeline)</li><li>The README clearly mentioned whether it supported the new architecture</li><li>A PR was already pending to be merged with new architecture support</li></ol><p><strong>The Blockers</strong></p><p>At the end of our research, we had a clear picture of which libraries were ready and which weren’t. Two critical libraries used in our app were <strong>blockers</strong>:</p><ul><li><strong>react-native-maps</strong> — No new architecture support</li><li><strong>@stripe/stripe-react-native</strong> — No new architecture support</li></ul><p>Since these were essential to our app’s functionality, <strong>we decided to wait</strong>.</p><p><strong>The Waiting Game</strong></p><p>For the next <strong>7–8 months</strong>, we constantly monitored new architecture updates across the ecosystem. Recently, both react-native-maps and @stripe/stripe-react-native released new versions with new architecture support.</p><p>Finally, we were ready to start upgrading to <strong>React Native 0.76.9</strong> and <strong>Expo SDK 52</strong>. But then we came across this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qvKsftOQb3auAfcfLOOVA.png" /></figure><p><strong>The 16KB Page Size Requirement</strong></p><p>Just as we were ready to begin our migration, we discovered a critical new requirement from Google.</p><p><strong>What is the 16KB Page Size Change?</strong></p><p>Android 15 introduces support for <strong>16KB memory page sizes</strong> (up from the traditional 4KB). This change enables:</p><ul><li>Significant performance improvements for apps</li><li>Better optimization for devices with larger amounts of RAM</li></ul><p>However, apps compiled with the previous 4KB page size assumption could become <strong>incompatible on future devices</strong>.</p><p>As device manufacturers build devices with increasingly larger amounts of physical memory (RAM), many will adopt 16KB — and eventually even larger — page sizes to optimize device performance. Adding support for 16KB page sizes:</p><p>✅ Ensures your app runs on these newer devices<br> ✅ Helps your app benefit from associated performance improvements<br> ❌ <strong>Without recompiling for 16KB support, apps won’t work on 16KB devices in future Android releases</strong></p><p>Google set a hard deadline: <strong>By November 1st, 2025</strong>, all apps must support 16KB page sizes, or app updates would be <strong>rejected from the Play Store</strong>.</p><p>This added another layer of complexity to our already challenging migration. We now had to ensure our upgrade path supported not just the new architecture, but also 16KB page size compatibility — all before the deadline.</p><h4><strong>Back to the Drawing Board</strong></h4><p>The 16KB page size requirement forced us to revisit our migration plan. This YouTube video by Gautam Vijay was incredibly helpful in understanding the migration: <a href="https://www.youtube.com/watch?v=Qp24I6q33pE">https://www.youtube.com/watch?v=Qp24I6q33pE</a></p><p>Here’s where things got complicated. Hyperfuel was currently on React Native 0.72.4. The new architecture was enabled by default in 0.76.9, which we had planned to target. However, React Native only started supporting 16KB page sizes from version <strong>0.77.0 onwards</strong>. This meant <strong>we couldn’t stay on 0.76.9</strong> — we needed to migrate to at least 0.77 to meet Google’s deadline.</p><p>React Native 0.77 also introduced a significant iOS template change, replacing the existing Objective-C templates (AppDelegate.h and AppDelegate.mm) with a Swift template (AppDelegate.swift). This meant we&#39;d need to migrate our iOS native code from Objective-C to Swift as well.</p><p>When we looked for Expo support for React Native 0.77, we hit another snag. Expo had not released a stable SDK compatible with 0.77 — only a canary release (experimental version) existed. We wanted to rely on stable, production-ready SDKs rather than risk using experimental releases.</p><p>So we decided to target <strong>React Native 0.79</strong> instead. Expo already supported 0.79 through its stable <strong>SDK 53</strong>, which gave us new architecture support, 16KB page size compatibility, a stable Expo SDK with tested modules, and all the latest React Native improvements and bug fixes.</p><h4><strong>Why We Didn’t Go for the Latest (0.81 and Expo SDK 54)</strong></h4><p>We wanted something more reliable and stable. If we picked the absolute latest version in the market, there’s a high probability it might introduce issues with libraries or other unexpected problems down the line. We didn’t want to get stuck debugging bleeding-edge issues that the community was still working on fixing.</p><p>For React Native 0.79, we checked all our libraries and found that most had already released compatible versions. Plus, 0.79 had released <strong>6 patch versions</strong> (up to 0.79.6), with each one progressively fixing issues and improving stability. This made 0.79.6 a solid, battle-tested choice for us.</p><p>Now that we had compatible versions for both the new architecture and 16KB page size support, we thought we were good to go. But then we hit another roadblock: <strong>Not only React Native, but every library used in our app needs to support 16KB page sizes.</strong></p><p><strong>How We Verified 16KB Compatibility</strong></p><p>Here’s the step-by-step process we followed to ensure every library supported 16KB page sizes:</p><p><strong>Step 1: Update Development Tools</strong></p><p>We updated our development environment to the latest versions:</p><ul><li><strong>Android Studio</strong> to Narwhal Feature Drop | 2025.1.2</li><li><strong>Xcode</strong> to version 16.4</li></ul><p>We also removed any existing global React Native CLI versions to avoid conflicts.</p><p><strong>Step 2: Create a Clean POC Project</strong></p><p>We created a fresh sample React Native project with version 0.79.6 and built a release APK using the standard build guide.</p><p><strong>Step 3: Verify Base Compatibility</strong></p><p>We followed <a href="https://developer.android.com/guide/practices/page-sizes#identify-native-code">Android 16 KB Verification Steps</a> using Android Studio’s <strong>Analyze APK</strong> tool. This tool lets you upload your APK and check whether your app uses any native libraries that aren’t 16KB compatible. If some libraries don’t support 16KB, your app will crash on higher-end devices — specifically on screens where you’re using that library’s code.</p><p>In our sample POC, we only had React Native itself (which already supported 16KB), so the base app passed the verification.</p><p><strong>Step 4: Add All Production Libraries</strong></p><p>Now came the real test. We added all 50+ libraries that we use in Hyperfuel. Since we wanted to migrate everything to the latest versions, we added the most recent stable version of each library, following the latest setup instructions from their documentation.</p><p><strong>Step 5: Debug, Debug, Debug</strong></p><p>After adding all the libraries, we tried to run the app and immediately hit <strong>7–8 native issues</strong>. Honestly, we were stuck on these for some time, and it was frustrating.</p><p>But here’s our advice: <strong>Do not be afraid of native issues when they arise.</strong> These are bound to come during major migrations. Give them time, debug methodically, and search online to see if others have faced the same issues. Use AI tools to research the web. Dive into the library’s native code and use ChatGPT or Claude to help debug. Try upgrading or downgrading library versions to find compatible combinations.</p><p>At Hyperfuel, we adopt this mindset: <strong>“Every problem arises with a definite solution. There is no problem that can’t be solved. You just need either more time or more resources to solve it.”</strong></p><p><strong>Step 6: Patch When Necessary</strong></p><p>We noticed some issues were due to actual incompatibilities between libraries and the new architecture. In these cases, we had to patch the library code using patch-package to make it work.</p><p><strong>Step 7: Test Popular Libraries</strong></p><p>Online, we noticed people weren’t confident about using React Navigation V7, claiming it caused poor app performance. But we tried it in our sample app anyway, and <strong>it worked perfectly</strong>. Don’t let unverified claims stop you from testing yourself.</p><p><strong>Step 8: Final Verification</strong></p><p>After resolving all issues, we created another release APK and analyzed it again using the Analyze APK tool to confirm everything was 16KB compatible.</p><p><strong>A Note on Expo Libraries</strong></p><p>We didn’t add Expo SDK and Expo libraries to our POC yet because we were confident they would support 16KB page sizes. And we were right — Expo libraries were already 16KB compatible.</p><p><strong>The Two Problematic Libraries</strong></p><p>We discovered that we were using <strong>2 npm libraries that didn’t support 16KB page sizes</strong>, even in their latest versions. These libraries used heavy native C/C++ code internally, which hadn’t been recompiled for 16KB support.</p><p>Using the Analyze APK tool, you should be able to identify which npm libraries don’t work with 16KB page sizes — the tool displays the library names that are causing compatibility issues.</p><p><strong>Debugging react-native-clusterer</strong></p><p>The first problematic library was <strong>react-native-clusterer</strong>, which showed up clearly in the Analyze APK tool. An issue had already been created in the <a href="https://github.com/JiriHoffmann/react-native-clusterer/issues/59">library’s GitHub repository</a>, and someone had even raised a <a href="https://github.com/JiriHoffmann/react-native-clusterer/pull/61">PR</a> with fixes. We patched the PR changes into our local copy of the library using patch-package, but unfortunately, those changes didn&#39;t work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*AyKoAqlwHtmdyX7uc4VYGA.png" /></figure><p>We joined the conversation on the same GitHub thread, and someone shared the correct patch file that actually worked. We applied it, and react-native-clusterer became 16KB compatible.</p><p><strong>The Remaining Incompatibilities</strong></p><p>After fixing react-native-clusterer, our alignment check revealed that <strong>2 native libraries were still incompatible</strong>. These turned out to be internal dependencies used by a single npm library: <strong>react-native-multiple-image-picker</strong>.</p><p>This highlights an important point: sometimes it’s hard to identify which npm library is causing the incompatibility just by looking at the native library names displayed in the Analyze APK tool. The displayed names are often low-level C/C++ libraries, not the npm package names you’re familiar with.</p><p><strong>Pro tip:</strong> When you can’t identify the culprit library, try Googling the native library name shown in the tool, or use trial and error — remove probable libraries one by one and check alignment again until you find the source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkHcuHG_1LWlC6vhgd3t5w.png" /></figure><h4><strong>Raising an Issue for 16KB Compatibility</strong></h4><p>We raised an issue on the library’s GitHub repository, tagged the author, and requested them to release a version supporting 16KB page sizes. Here’s how it looked:<br> 👉 <a href="https://github.com/NitrogenZLab/react-native-multiple-image-picker/issues/241">https://github.com/NitrogenZLab/react-native-multiple-image-picker/issues/241</a></p><p>When creating such issues, follow this format to increase your chances of getting a response:</p><ol><li><strong>Show appreciation</strong> — Mention what you like about the library and acknowledge the author’s efforts in maintaining it</li><li><strong>Explain the 16KB requirement</strong> — Clearly describe the compatibility issue and Google’s deadline</li><li><strong>Provide a head start</strong> — If possible, reverse-engineer the library code and point them to where changes might be needed</li></ol><p>After raising the issue, monitor it for responses. Sometimes someone from the community will create a PR with fixes — you can patch that PR locally using patch-package to test if it works. If no one replies, politely ask again. If you still get no response from the author, you have two options:</p><ol><li><strong>Switch libraries</strong> — Find an alternative that’s already 16KB compatible</li><li><strong>Fix it yourself</strong> — Fork the library, make the necessary changes, and maintain your own version</li></ol><p><strong>Our Solution</strong></p><p>We chose to switch libraries. We transitioned from <strong>react-native-multiple-image-picker</strong> to <strong>expo-image-picker</strong>, which was already 16KB compatible. After this change, all the libraries we were using finally supported 16KB page sizes.</p><p>Now that we had verified everything in our POC, it was time to migrate the actual Hyperfuel project.</p><p>We followed the <a href="https://react-native-community.github.io/upgrade-helper/?from=0.72.2&amp;to=0.79.5"><strong>React Native Upgrade Helper</strong></a> to upgrade our project’s native code to 0.79.5. The Upgrade Helper shows all the necessary changes file by file, which is incredibly useful for complex upgrades.</p><p><strong>Critical advice:</strong> Follow these changes <strong>very carefully</strong>. Even one missing change can waste hours of unnecessary debugging later. Verify all changes twice, especially in files like project.pbxproj on iOS, which are notoriously easy to mess up.</p><p><strong>Migrating from Objective-C to Swift</strong></p><p>As we mentioned earlier, AppDelegate.h and AppDelegate.mm have been replaced with AppDelegate.swift in React Native 0.77+. If you&#39;ve added any library-specific code to your old Objective-C AppDelegate files, you&#39;ll need to find the Swift-compatible equivalent.</p><p><strong>Example: react-native-maps</strong></p><p>The <a href="https://github.com/react-native-maps/react-native-maps/blob/master/docs/installation.md#enabling-google-maps">react-native-maps documentation</a> shows how to enable Google Maps on iOS through changes in AppDelegate.mm, but it doesn&#39;t provide the equivalent code for AppDelegate.swift. When you encounter this situation:</p><ol><li><strong>Search the library’s GitHub</strong> — Navigate through issues, discussions, and PRs to see if anyone has reported this or if the maintainers have documented it elsewhere</li><li><strong>Raise an issue</strong> — If you can’t find it, politely ask the library owner for the Swift-compatible code</li><li><strong>Use AI assistance</strong> — Try using ChatGPT or Claude to convert the Objective-C .mm code to Swift (though verify the output carefully)</li></ol><p>In the case of react-native-maps, we eventually found the Swift-compatible change somewhere in their repository:</p><pre>import GoogleMaps<br><br>override func application(<br>    _ application: UIApplication,<br>    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil<br>  ) -&gt; Bool {<br>    <br>    ....<br><br>    // Configure Google Maps<br>    if let apiKey = RNCConfig.env(for: &quot;IOS_GOOGLE_MAPS_API_KEY&quot;) {<br>      GMSServices.provideAPIKey(apiKey)<br>    }<br>    <br>    ...<br><br>    return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>  }<br></pre><p>We store our IOS_GOOGLE_MAPS_API_KEY in environment variables, and to access it in native iOS code, we use RNCConfig from react-native-config. Again, we didn&#39;t find the Swift version in the documentation—<a href="https://github.com/lugg/react-native-config?tab=readme-ov-file#ios--macos">the docs</a> still only show the Objective-C implementation. We eventually found the Swift equivalent in the library&#39;s issues section.</p><p>This pattern of finding Swift solutions in GitHub issues rather than documentation was common throughout our migration. Don’t hesitate to dig through the issues section — often the community has already solved what you’re trying to do.</p><h4>react-native-firebase:</h4><p>This library was a pleasant exception — it correctly documented both the <a href="https://github.com/lugg/react-native-config?tab=readme-ov-file#ios--macos">Swift</a> and <a href="https://rnfirebase.io/#configure-firebase-with-ios-credentials-react-native--077">Objective-C</a> versions in their official documentation, making the migration straightforward.</p><p><strong>Applying Changes and Updating Dependencies</strong></p><p>Once we applied all the changes from the Upgrade Helper, we updated all package versions to match our sample POC and followed each library’s installation setup steps. We also updated our Node.js version to <strong>v20.9.4</strong> for better compatibility.</p><p>Even after doing all this, we still faced some core React Native issues. You may or may not encounter these, but we’re documenting them just in case:</p><p><strong>Issue 1: metro.config.js Incompatibility</strong></p><p>Even after following the <a href="https://react-native-community.github.io/upgrade-helper/?from=0.72.2&amp;to=0.79.5#RnDiffApp-metro.config.js">metro config changes</a> from the Upgrade Helper, our build failed. The suggested changes somehow weren’t compatible with our setup. We had to rewrite our metro.config.js file to adhere to the <strong>react-native-community metro.config.js </strong><a href="https://github.com/react-native-community/template/blob/main/template/metro.config.js"><strong>template format</strong></a>.</p><p>Additionally, since we were using <strong>react-native-reanimated</strong>, we had to wrap our config with wrapWithReanimatedMetroConfig as per Reanimated&#39;s documentation:</p><p><strong>Issue 2: Codegen Resolution Error</strong></p><p>We encountered this exact issue: <a href="https://github.com/facebook/react-native/issues/49566">https://github.com/facebook/react-native/issues/49566</a></p><p>The build was failing because multiple versions of codegen were being used simultaneously. The solution was to ensure only <strong>one codegen version</strong> existed in our <a href="https://github.com/zingolabs/zingo-mobile/pull/806/files#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519">package.json</a>. We resolved version conflicts using resolutions (for Yarn) or overrides (for npm).</p><h4><strong>Expo Install/Upgrade</strong></h4><p>Hyperfuel is a bare React Native CLI project, but as mentioned earlier, we were using Expo SDK version 49 to benefit from expo-modules. We wanted to upgrade to Expo SDK 53 to align with React Native 0.79.Install required expo sdk version.</p><pre>//If you want to go for latest react native version 0.81 and Expo SDK 54:<br>npm install expo<br><br>//If you want to install react native version &lt; 0.81 and Expo SDK &lt; 54<br>npm install &quot;expo@^53.0.0&quot;</pre><p>In our case we installed 53.0.22 version.</p><p>2. Upgrade all dependencies to match the installed SDK version</p><pre>npx expo install --fix</pre><p>3. Check all compatibility problems.</p><pre>npx expo-doctor</pre><p>This command is most useful for someone with <strong>Expo-managed project.</strong></p><p><strong>Understanding Expo Managed Projects</strong></p><p>Before we dive into our upgrade process, let’s clarify what an Expo Managed project is and why it matters.</p><p>An <strong>Expo Managed project</strong> is a project created from Expo’s template. In these projects, you can use expo-modules out of the box, but you can also install third-party React Native libraries. The recommended approach for installing third-party libraries in Expo Managed projects is through the expo install command.</p><p>For example, @react-native-async-storage/async-storage is a third-party library (see <a href="https://docs.expo.dev/versions/latest/sdk/async-storage/">https://docs.expo.dev/versions/latest/sdk/async-storage/</a>). In an Expo Managed project, you&#39;d install it using:</p><pre>expo install @react-native-async-storage/async-storage</pre><p>The purpose of using this command is that <strong>Expo maintains compatibility mappings</strong> between various third-party packages and the core Expo SDK version. This ensures you don’t get version mismatches that could break your app.</p><p>The npx expo-doctor command is helpful in Expo Managed projects—it lists all incompatibility issues between your Expo SDK version and your package versions.</p><p><strong>Our Situation: Bare React Native CLI Project</strong></p><p>Since Hyperfuel is <strong>not an Expo Managed project</strong> but rather a bare React Native CLI project with Expo modules installed, we install third-party libraries using yarn add (or npm install). These libraries don&#39;t need to be compatible with the Expo SDK version—they only need to be compatible with our React Native version. So we <strong>skipped the </strong><strong>npx expo-doctor command</strong>.</p><h4><strong>Native Code Changes for Expo</strong></h4><p>Next, you need to add native code changes for Expo. The approach depends on whether you’ve enabled <a href="https://docs.expo.dev/workflow/continuous-native-generation/"><strong>CNG (Continuous Native Generation)</strong></a> or not.</p><p><strong>If You’re Using CNG (Expo Managed Projects)</strong></p><p>With CNG enabled:</p><ol><li>You don’t need to manage android and ios directories manually. Instead, you manage a single JSON configuration file (app.json/app.config.js) that drives the complete native directory structure. This simplifies development since 80-90% of the time, you don&#39;t need to modify native code directly.</li><li>After upgrading your Expo SDK, you don’t need to make any manual changes inside the android or ios directories. Simply delete them, and they&#39;ll be automatically regenerated when you create a new build.</li></ol><p><strong>If You Don’t Use CNG (Bare React Native Projects)</strong></p><p>If you manage your android and ios directories yourself (like we do):</p><ul><li><strong>For SDK 54+:</strong> Follow the Android native changes here:<br> <a href="https://docs.expo.dev/bare/installing-expo-modules/#configuration-for-android">https://docs.expo.dev/bare/installing-expo-modules/#configuration-for-android</a></li><li><strong>For SDK &lt; 54</strong> (like us upgrading to SDK 53): Follow this upgrade guide:<br> <a href="https://docs.expo.dev/bare/upgrade/?fromSdk=49&amp;toSdk=54">https://docs.expo.dev/bare/upgrade/?fromSdk=49&amp;toSdk=54</a></li></ul><p>This guide shows you the file-by-file native code changes needed to upgrade from your current SDK to the target SDK.</p><p>After this we ran following commands to make sure to clean everything:</p><pre>cd android<br>./gradlew clean<br><br>rm -rf node_modules<br>rm -rf android/.cxx<br>rm -rf android/app/.cxx<br>rm -rf android/build<br>rm -rf android/app/build<br><br>Install node_modules again</pre><p>Even after following all the native code changes, our Android app was still failing to build. We faced the following issues. You may or may not encounter these, but we’re documenting them just in case:</p><p><strong>Issue 1: Leftover Old Architecture Folders</strong></p><p>We noticed that old folders from the previous architecture — like newarch and jni folders—were still present inside android/app/src/main/java/com/hyperfuel. We removed them manually since they were no longer necessary in React Native 0.79.5. These folders can cause build conflicts if left behind.</p><p><strong>Issue 2: Codegen Directory Not Found</strong></p><p>Even after cleaning up old folders, we faced this error:</p><pre>add_subdirectory given source &quot;…/node_modules/&lt;package&gt;/android/build/generated/source/codegen/jni/&quot; which is not an existing directory</pre><p>When we consulted AI tools for help, they indicated that the build system couldn’t find the generated codegen files. The solution was to manually generate the codegen files by running the following commands:</p><pre>npx @react-native-community/cli codegen</pre><pre>npx @react-native-community/cli codegen --platform ios</pre><p>This reads package.json file and generate native code based on codegen config(if exists).</p><p><strong>Issue 3: AndroidX and Support Library Conflict</strong></p><p>Previously, we had android.enableJetifier=true in android/gradle.properties. This flag automatically converts old Android Support Library code to AndroidX. Based on guidance from the <a href="https://react-native-community.github.io/upgrade-helper/?from=0.72.2&amp;to=0.79.5#RnDiffApp-android-gradle.properties">React Native upgrade documentation</a>, we removed it, assuming it was no longer needed.</p><p>However, after removing it, we started receiving errors about conflicts between AndroidX and the old Android Support Library. ChatGPT explained that these two cannot coexist in the same project. The solution was to add back android.enableJetifier=true, which successfully converted all old Support Library code to AndroidX and resolved the conflict.</p><p>Now the Android build was working fine, we needed to run IOS build.</p><h4>Migrating to Project-level CocoaPods Management</h4><p>Previously, our React Native iOS builds used a <strong>globally installed CocoaPods</strong> version. While this worked initially, it often led to <strong>version mismatches</strong> across different developer environments and CI machines. These mismatches caused inconsistencies in dependency resolution, sometimes even leading to unexpected build or linking issues.</p><p>Earlier, CocoaPods was installed globally using:</p><pre>sudo gem install cocoapods</pre><p>To make our setup more reliable and reproducible, we <strong>moved CocoaPods management inside the project</strong> using Bundler (Ruby’s dependency manager). By defining CocoaPods as a gem in the project’s Gemfile, we could lock its version in Gemfile.lock. This ensures that every developer and CI environment uses the <strong>same CocoaPods version</strong>, regardless of their local system setup.</p><p>New react native version comes up with following cocoapods version changes as per <a href="https://react-native-community.github.io/upgrade-helper/?from=0.72.2&amp;to=0.79.5#RnDiffApp-Gemfile">upgrade helper</a>:</p><pre>gem &#39;cocoapods&#39;, &#39;&gt;= 1.13&#39;, &#39;!= 1.15.0&#39;, &#39;!= 1.15.1&#39;</pre><p><strong>How it works</strong></p><p><strong>Ruby</strong> → The programming language<br><strong>Gems</strong> → Ruby packages (e.g., CocoaPods).<br><strong>Gemfile</strong> → A file that lists all required gems and their versions.<br><strong>Bundler</strong> → The tool that installs and manages these gems for the project.</p><h4>Setup Steps</h4><ol><li>Uninstall global CocoaPods:</li></ol><pre>sudo gem uninstall cocoapods<br>brew uninstall cocoapods</pre><p>2. Install Bundler (if not already installed):</p><pre>gem install bundler</pre><p>3. Install gems defined in the project’s Gemfile:</p><pre>bundle install</pre><p>4. Remove any old Gemfile inside the iOS folder — we now use the <strong>root-level Gemfile</strong>.</p><p>5. Update .xcode.env.local:</p><pre>export NODE_BINARY=&quot;/Users/vkukade/.nvm/versions/node/v20.9.0/bin/node&quot;</pre><p>6. Check CocoaPods version:</p><pre>bundle exec pod --version   # → 1.15.2</pre><p>7. Install pods:</p><pre>cd ios<br>bundle exec pod install</pre><p><strong>Usage Going Forward</strong></p><p>From now on, <strong>do not use global CocoaPods</strong>.</p><p>Always use Bundler-managed commands to ensure the correct version is used:</p><pre>bundle exec pod --version<br>bundle exec pod deintegrate<br>bundle exec pod install</pre><p>Optional cleanup</p><pre>rm -rf ~/Library/Developer/Xcode/DerivedData/*</pre><p>This setup makes our iOS dependency management <strong>stable, version-locked, and CI-compatible</strong>.</p><p>After this while trying to run IOS build, we faced numerous issues related to various libraries compatibility and also with respect to the extra widget we added for IOS live activities. Hence to debug this clearly, we commented IOS live activities code and only focused on core libraries issues. Once they were solved, we focused on live activities issues.</p><p>After this, we were able to successfully build ios app also. Now we needed to replace some of the old/depreciated libraries for android and ios both.</p><h4>Libraries Replacement</h4><p><a href="https://reactnative.dev/docs/backhandler">Android BackHandler</a> logic needs to be changed now.</p><p>Prev you must be using:</p><pre>//register listener<br>BackHandler.addEventListener(&#39;hardwareBackPress&#39;, handleBackButtonClick);<br><br>//remove listener<br>BackHandler.removeEventListener(&#39;hardwareBackPress&#39;, handleBackButtonClick);</pre><p>Now it is changed as follows:</p><pre>//Register listener<br>const backHandler = BackHandler.addEventListener(&#39;hardwareBackPress&#39;, handleBackButtonClick);<br><br>//remove listener<br>backHandler.remove();</pre><p>We divided the work into 2 parts:</p><ol><li><strong>Remove any unused/not necessary libraries</strong></li></ol><p>As time went on, we had accumulated some unnecessary libraries in the project. Now was the time to clean them up. We need to differentiate between two types of unused libraries:</p><p><strong>Type 1: Completely Unused Libraries</strong><br>Libraries that exist in package.json without any reference in the project code. We removed these directly without a second thought.</p><p><strong>Type 2: Indirect Dependencies</strong><br>Libraries that appear unused in our code but are actually dependencies of other heavily-used libraries. We <strong>cannot remove these</strong> — they may seem unused, but they’re required by other packages. For example, @react-native-community/datetimepicker is a dependency for react-native-modal-datetime-picker, so even though we don&#39;t import it directly, it must stay.</p><p><strong>2. Replacing Deprecated Libraries with Modern Alternatives</strong></p><p>We replaced several deprecated or incompatible libraries with new, well-maintained alternatives:</p><p><strong>Image Handling:</strong></p><p><strong>Replaced:</strong> <a href="https://github.com/DylanVann/react-native-fast-image"><strong>react-native-fast-image</strong></a><strong> →</strong> <a href="https://docs.expo.dev/versions/v53.0.0/sdk/image/"><strong>expo-image</strong></a><br> <em>react-native-fast-image </em>was deprecated and didn&#39;t support the new architecture or 16KB page sizes. <em><br></em>Note: There&#39;s also a new fork by Dream11 called <a href="https://github.com/ds-horizon/react-native-fast-image">react-native-fast-image</a> that&#39;s compatible with the new architecture and 16KB page sizes if you prefer that.</p><p><strong>Location &amp; GPS:</strong></p><ul><li><strong>Replaced:</strong> <a href="https://github.com/rmrs/react-native-settings"><strong>react-native-settings</strong></a><strong> → </strong><a href="https://github.com/Richou/react-native-android-location-enabler"><strong>react-native-android-location-enabler</strong></a><br> We were using this to get GPS access from users. The new library shows a Google Maps-style GPS popup to users.</li><li><strong>Replaced:</strong> <a href="https://github.com/Agontuk/react-native-geolocation-service"><strong>react-native-geolocation-service</strong></a><strong> → </strong><a href="https://docs.expo.dev/versions/v53.0.0/sdk/location/"><strong>expo-location</strong></a><br> The old library was deprecated, unmaintained, and didn&#39;t support the new architecture or 16KB page sizes.</li></ul><p><strong>Image Picking:</strong></p><ul><li><strong>Replaced:</strong> <a href="https://github.com/react-native-image-picker/react-native-image-picker"><strong>react-native-image-picker</strong></a><strong> + </strong><a href="https://github.com/NitrogenZLab/react-native-multiple-image-picker"><strong>react-native-multiple-image-picker</strong></a><strong> → </strong><a href="https://docs.expo.dev/versions/v53.0.0/sdk/imagepicker/"><strong>expo-image-picker</strong></a><br>Consolidated two libraries into one that handles both single and multiple image selection.</li></ul><p><strong>Keyboard Handling:</strong></p><ul><li><strong>Replaced:</strong> <a href="https://github.com/APSL/react-native-keyboard-aware-scroll-view"><strong>react-native-keyboard-aware-scroll-view</strong></a><strong> (deprecated) → </strong><a href="https://kirillzyusko.github.io/react-native-keyboard-controller/"><strong>react-native-keyboard-controller</strong></a><br>The new library is actively maintained and currently the most popular keyboard handling solution in the market.</li></ul><p><strong>Camera &amp; Barcode Scanning:</strong></p><ul><li><strong>Replaced:</strong> <a href="https://github.com/react-native-camera/react-native-camera"><strong>react-native-camera</strong></a><strong> + </strong><a href="https://github.com/moaazsidat/react-native-qrcode-scanner"><strong>react-native-qrcode-scanner</strong></a><strong> → </strong><a href="https://docs.expo.dev/versions/v53.0.0/sdk/camera/"><strong>expo-camera</strong></a><br> Consolidated two libraries into one. We considered <a href="https://github.com/mrousavy/react-native-vision-camera">react-native-vision-camera</a>, but it&#39;s overkill for our use case—expo-camera handles our needs perfectly.</li></ul><p><strong>Animations:</strong></p><ul><li><strong>Migrated:</strong> Core React Native Animated API → <a href="https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/getting-started"><strong>react-native-reanimated</strong></a> (latest version)<br> Converted all animations to use Reanimated for better performance and smoother animations on the new architecture.</li></ul><p><strong>Edge-to-Edge Display:</strong></p><ul><li><strong>Installed:</strong> <a href="https://github.com/zoontek/react-native-edge-to-edge">react-native-edge-to-edge</a> to enable edge-to-edge display on Android 15+<br> Important: You&#39;ll need to fix broken UI layouts at the top and bottom edges after enabling this. Test your UI thoroughly once enabled.<br>Guide: <a href="https://developer.android.com/about/versions/15/behavior-changes-15#edge-to-edge">https://developer.android.com/about/versions/15/behavior-changes-15#edge-to-edge</a> <br><em>Note: If you&#39;re running React Native 0.81 or later, consider using the built-in </em><em>edgeToEdgeEnabled=true gradle property along with </em><em>@zoontek/react-native-navigation-bar instead of the </em><em>react-native-edge-to-edge library.</em></li></ul><p><strong>3. Updating Existing Libraries</strong></p><p>We also updated several libraries that were already compatible but had newer versions available:</p><ul><li><strong>React Navigation:</strong> Updated to V7</li><li><strong>React Native Firebase:</strong> Updated to V23</li><li><strong>React Native MMKV:</strong> Updated to V3</li></ul><h4>Native modules -&gt; Turbo modules</h4><p>Finally, we updated our Native Modules to <strong>Turbo Modules</strong>. We had a separate widget for Live Activities, and to start or stop these activities, we previously sent data to iOS using Native Modules.</p><p>If you want to understand the difference between Native and Turbo Modules — and how to convert between them — you can refer to <a href="https://medium.com/@varunkukade999/build-native-and-turbo-modules-in-react-native-with-swift-e5d942226855">one of my detailed articles</a> on this topic, or check out the <a href="https://reactnative.dev/docs/turbo-native-modules-introduction">official React Native documentation</a>.</p><p>With this, we’ve completed all the steps required to migrate our app to the <strong>New Architecture</strong>. I hope this walkthrough helps you in your own migration journey. If you have any questions or doubts, feel free to ask in the comments — I’ll do my best to answer them.</p><p>I’ve already created various tech blogs in my leisure time. You can find more of such articles on my profile.</p><p>To stay updated on future articles, don’t forget to follow me! After following, you’ll get future articles right in your email inbox. Also, give this post <strong>50 claps 👏</strong> if you enjoyed this post and learned something useful. Your enthusiasm and support fuel my passion for sharing knowledge in the tech community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f97518456b8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Download File Example (PDF, Docs, Any File) for iOS and Android]]></title>
            <link>https://medium.com/@varunkukade999/react-native-download-file-example-pdf-docs-any-file-for-ios-and-android-9bca741c68b4?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bca741c68b4</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 18:16:15 GMT</pubDate>
            <atom:updated>2025-09-13T18:16:15.409Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Learn how to download and save any remote file (PDF, DOCX, images, etc.) in React Native on both iOS and Android. This POC uses Expo and can be easily customized for your own app.</strong></p><p>You can use it as shown below: simply pass the files array along with the headers, and all files will be downloaded simultaneously in parallel.</p><pre><br>const getHeaders = () =&gt; {<br>    const headers: Record&lt;string, string&gt; = {};<br>    const token = getToken();<br>    if (token) {<br>      headers[&quot;Authorization&quot;] = `Bearer ${token}`;<br>    }<br>    return headers;<br>  };<br><br>const downloadAuthenticatedFile = async () =&gt; {<br>    handleNotificationPermission(() =&gt; {<br>      const files = [<br>        {<br>          url: &quot;https://s24.q4cdn.com/216390268/files/doc_downloads/test.pdf&quot;,<br>          filename: &quot;test.pdf&quot;,<br>          headers: getHeaders(),<br>        },<br>      ];<br>      downloadFiles(files);<br>    });<br>  };<br><br>     &lt;Button<br>        title=&quot;Download authenticated file&quot;<br>        onPress={downloadAuthenticatedFile}<br>      /&gt;</pre><p>Android:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzsTcy40K78H8MtigAJmXw.gif" /></figure><p>IOS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*hc4EeIbcw-V4M1uIDPB_vg.gif" /></figure><p>The goal of this POC is to save you <strong>70–80% of the time</strong> usually spent on building the basic file-download functionality from scratch.</p><p>👉 Before we dive in, here’s the complete code repository: <a href="https://github.com/varunkukade/expo-file-download-poc">GitHub — expo-file-download-poc</a></p><h3>✨ POC Features</h3><ol><li>Download multiple files from a remote server in parallel using file URIs.</li><li>Show live download progress (%) for each file. <strong>Android</strong>: progress shown via notification bar.</li><li>Group Android notifications together for cleaner UI.</li><li>Check device storage and notify the user if there isn’t enough space to download a file.</li><li><strong>Android</strong>: allow users to cancel any ongoing download with a “Cancel” button.</li><li>Notify the user when each file finishes downloading.</li><li>After download completion, save all files together to the device’s file explorer.</li></ol><h3>Libraries we will use:</h3><ol><li><strong>expo-file-system:</strong> For accessing the user’s device file system</li><li><strong>@notifee/react-native:</strong> For showing local notifications.</li><li><strong>react-native-permissions:</strong> For asking Notification permission</li><li><strong>react-native-share:</strong> For showing “Save to Files” option for IOS and fallback “Share with” option for android.</li><li><strong>react-native-mmkv:</strong> We will ask for notification permission only once. We will use mmkv storage to store whether we have already asked for notification permission or not. You can also use any other preferred library of your choice.</li></ol><h3>Installation and setup:</h3><blockquote>Note: If you are stuck/confused about any step in following, just checkout my repo.</blockquote><ol><li><strong>expo-file-system:</strong></li></ol><p>I developed this feature on top of an Expo-managed project. I used Expo SDK 53.</p><p><strong>Expo managed: </strong><br>If you are already on the completely Expo managed (expo manages android and ios directories) project, just follow <a href="https://docs.expo.dev/versions/v54.0.0/sdk/filesystem-legacy/">this</a> to set this library.</p><p><strong>Bare React Native</strong><br>If you are on a bare react native project, you would not be able to use expo-file-system unless you first install expo. So in order to use expo-file-system, make sure to first install expo in your project.</p><p><strong>Which Expo SDK version to install or upgrade to? <br></strong>It depends on which react native version you have already / want to upgrade to. Every expo SDK comes up with different react native version. Not all react native versions are supported in expo. Expo maintain and supports last 3 major react native versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou0ywuvRoR7KXcf0Zf5_-w.png" /></figure><p>You will still be able to install expo SDK for old react native versions. But expo doesn’t maintain them actively.</p><p>Follow <a href="https://docs.expo.dev/workflow/upgrading-expo-sdk-walkthrough/#how-to-upgrade-to-the-latest-sdk-version">this</a> to install expo in your project.</p><p>For <a href="https://docs.expo.dev/workflow/upgrading-expo-sdk-walkthrough/#update-native-projects">this</a> “updating native code” step, as you are on bare react native project, you have to do following:</p><ol><li>If you don’t have expo installed already and want to update to latest SDK version 54 — follow <a href="https://docs.expo.dev/bare/installing-expo-modules/#manual-installation">this</a> changes.</li><li>If you already have expo and want to upgrade to some old expo SDK version, follow <a href="https://docs.expo.dev/bare/upgrade/?fromSdk=53&amp;toSdk=54#upgrade-native-project-files">this</a> changes.</li></ol><p>For Expo SDK ≥ 54, a new set of APIs created for this library <a href="https://docs.expo.dev/versions/v54.0.0/sdk/filesystem/">https://docs.expo.dev/versions/v54.0.0/sdk/filesystem/</a>. Let me know in the comments if you want the same feature using new set of APIs. But legacy file system APIs I have used in POC will also work with Expo SDK 54.</p><p><strong>2. react-native-share:</strong></p><p>For expo managed: <a href="https://react-native-share.github.io/react-native-share/docs/install#expo-managed-workflow">https://react-native-share.github.io/react-native-share/docs/install#expo-managed-workflow</a></p><p>For bare react native: <a href="https://react-native-share.github.io/react-native-share/docs/install#bare-react-native">https://react-native-share.github.io/react-native-share/docs/install#bare-react-native</a></p><p><strong>3. @notifee/react-native </strong>:</p><p><a href="https://docs.page/invertase/notifee/react-native/installation">https://docs.page/invertase/notifee/react-native/installation</a>.</p><p>Note: For my expo-managed project, even after following doc for notifee and installing it, I faced issue. I had to apply following patch for it.</p><pre>npx expo install expo-build-properties</pre><p>Add following patch in app.json:</p><pre>&quot;plugins&quot;: [<br>      [<br>        &quot;expo-build-properties&quot;,<br>        {<br>          &quot;android&quot;: {<br>            &quot;targetSdkVersion&quot;: 35,<br>            &quot;extraMavenRepos&quot;: [<br>              &quot;../../node_modules/@notifee/react-native/android/libs&quot;<br>            ]<br>          }<br>        }<br>      ],<br>]</pre><p><strong>4. react-native-permissions:</strong></p><p>Set this up from <a href="https://github.com/zoontek/react-native-permissions#readme">https://github.com/zoontek/react-native-permissions#readme</a>. We have to add notification permission support for android and ios.</p><p><strong>5. react-native-mmkv:</strong></p><p>Set this up from here: <a href="https://github.com/mrousavy/react-native-mmkv">https://github.com/mrousavy/react-native-mmkv</a></p><p>Let’s begin with actual code. Code is mostly self-explainatory.</p><pre>const downloadAuthenticatedFile = async () =&gt; {<br>    handleNotificationPermission(() =&gt; {<br>      const files = [<br>        {<br>          url: &quot;https://s24.q4cdn.com/216390268/files/doc_downloads/test.pdf&quot;,<br>          filename: &quot;test.pdf&quot;,<br>          headers: getHeaders(),<br>        },<br>      ];<br>      downloadFiles(files);<br>    });<br>  };</pre><p>We first handle notification permission and then after it, start downlaoding of files.</p><pre>export const handleNotificationPermission = (callback: () =&gt; void) =&gt; {<br>  //First check if notification permission already shown<br>  const isNotificationPermissionShown = loadPermissionShown();<br>  if (isNotificationPermissionShown) {<br>    //if shown already, don&#39;t ask it again.<br>    callback();<br>  } else {<br>    //If not shown, check notification permission<br>    checkNotificationsPermission(<br>      () =&gt; {<br>        createChannels();<br>        //if already granted, save it and execute callback code<br>        savePermissionShown(true);<br>        callback();<br>      },<br>      () =&gt; {<br>        //if not granted yet, ask for the permission<br>        if (isIos() || (isAndroid() &amp;&amp; getPlatformVersion() &gt;= 33)) {<br>          //only try to ask for permission for ios and android 33 and above<br>          requestNotificationsPermission(<br>            () =&gt; {<br>              createChannels();<br>              //if granted, save it<br>              savePermissionShown(true);<br>              callback();<br>            },<br>            () =&gt; {<br>              //if not granted, save it and execute callback code<br>              savePermissionShown(false);<br>              callback();<br>            }<br>          );<br>        } else {<br>          //for android below 33, we don&#39;t have to ask for permission as its already granted for them<br>          savePermissionShown(true);<br>          callback();<br>        }<br>      }<br>    );<br>  }<br>};</pre><p>Through <strong>loadPermissionShown</strong>, we load from storage if we have already shown the notification or not. If its already shown, we don’t ask for it again. We just go with downloading the files. If its not shown before, through <strong>checkNotificationsPermission,</strong> we first check if user has already given permissions for our app. If not we ask for the permission <strong>requestNotificationsPermission.</strong> Note that, we only ask runtime permissions for android api ≥ 33. This is because for android versions &lt; 33, android automatically grants the permission from following <strong>AndroidManifest.xml</strong> entry.</p><pre>&lt;uses-permission android:name=&quot;android.permission.POST_NOTIFICATIONS&quot; /&gt;</pre><p>If user grants the permission, we create Notification channel for android through <strong>createChannels</strong>. Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel. You can assume using channel as grouping related notifications together. check <a href="https://developer.android.com/develop/ui/views/notifications#ManageChannels">this</a> out for more info.</p><pre>export const createChannel = (channelId: string, channelName: string) =&gt; {<br>  if (isIos()) {<br>    return;<br>  }<br>  notifee.isChannelCreated(channelId).then((isCreated) =&gt; {<br>    if (!isCreated) {<br>      notifee.createChannel({<br>        id: channelId,<br>        name: channelName,<br>        sound: &quot;default&quot;,<br>        importance: AndroidImportance.HIGH,<br>      });<br>    }<br>  });<br>};<br><br>export const fileDownloadChannelId = &quot;file-downloads&quot;;<br>export const fileDownloadChannelName = &quot;File Downloads&quot;;<br><br>const createChannels = () =&gt; {<br>  //create new channels with any new channelId and channelName.<br>  createChannel(fileDownloadChannelId, fileDownloadChannelName);<br>};</pre><p>I created one channel id and name and created the channel using <strong>createChannel</strong> method.</p><p>After that as we have shown the notification permission to user, I store it in storage using <strong>savePermissionShown.</strong></p><p>Even if user denied the permission, I start downloading the files.</p><p>Let’s understand <strong>downloadFiles</strong> method step by step.</p><p>For android, <strong>notifee</strong> offers us capability to group related notifications together. That means if we have 10 downloads and want to show 10 different notifications for it, we can group them together. Each group can have 1 summary notification which will display the summary of all notifications. Note that creating channels is different than grouping. Inside one channel, you can display multiple groups of notifications.</p><p>Hence first we will display summary notification:</p><pre>export const groupId = `download-group`;<br>export const groupAlertBehavior = AndroidGroupAlertBehavior.SUMMARY;<br>export const groupNotificationId = `download-summary`;<br><br>export const updateSummaryNotification = async (<br>  title: string,<br>  body?: string<br>) =&gt; {<br>  await notifee.displayNotification({<br>    id: groupNotificationId,<br>    title,<br>    body,<br>    android: {<br>      channelId: fileDownloadChannelId,<br>      groupId: groupId,<br>      groupSummary: true,<br>      groupAlertBehavior: groupAlertBehavior,<br>    },<br>  });<br>};</pre><pre>// Create summary notification (parent group holder)<br>updateSummaryNotification(&quot;Downloading files...&quot;);</pre><p>Notifee requires us to pass “<strong>id</strong>” for every notification which we can use afterwards to update that same notification. In addition to it, we will also pass channel id, group id as android specific properties. Also its necessary to pass <strong>groupSummary</strong> as true.</p><p>IOS doesn’t support grouping of notifications. Its treated just as any separate notification.</p><p>Then for each file, we show the separate notfication which notifies the starting of download for that file</p><pre><br>export const getNotificationId = (filename: string) =&gt; `download-${filename}`;<br><br>export const updateFileNotification = ({<br>  file,<br>  title,<br>  body,<br>  progress,<br>  actions,<br>  iosSound,<br>}: {<br>  file: DownloadFile;<br>  title: string;<br>  body?: string;<br>  progress?: { indeterminate: boolean; max: number; current: number };<br>  actions?: {<br>    title: string;<br>    pressAction: { id: string; launchActivity: string | undefined };<br>  }[];<br>  iosSound?: string;<br>}) =&gt; {<br>  const notificationId = getNotificationId(file.filename);<br><br>  const androidRequest: NotificationAndroid = {<br>    channelId: fileDownloadChannelId,<br>    onlyAlertOnce: true,<br>    groupId: groupId,<br>    groupAlertBehavior: groupAlertBehavior,<br>  };<br>  if (progress) {<br>    androidRequest.progress = progress;<br>  } else {<br>    androidRequest.progress = undefined;<br>  }<br>  if (actions) {<br>    androidRequest.actions = actions;<br>  } else {<br>    androidRequest.actions = [];<br>  }<br>  const request: Notification = {<br>    id: notificationId,<br>    title,<br>    android: androidRequest,<br>  };<br>  if (iosSound) {<br>    request.ios = {<br>      sound: iosSound,<br>    };<br>  }<br>  if (body) {<br>    request.body = body;<br>  } else {<br>    request.body = &quot;&quot;;<br>  }<br>  console.log(&quot;Updating notification&quot;, request);<br>  notifee.displayNotification(request);<br>};<br><br><br>     files.forEach((file) =&gt; {<br>       const truncatedFilename = truncate(file.filename);<br>       updateFileNotification({<br>        file,<br>        title: `Downloading: ${truncatedFilename}`,<br>        body: undefined,<br>        progress: undefined,<br>        actions: [],<br>        iosSound: undefined,<br>       });<br>    });</pre><p>Here we generate “<strong>id</strong>” for each notification through <strong>getNotificationId</strong>. We will use same <strong>id</strong> later to update that notification once download finish.</p><p>Also notice we need to truncate the file name to fit the file name in case its very long.</p><p>After starting download, functionality differs for android and IOS.</p><p><strong>For Android:</strong></p><p>We first download the files temporarily to File system document directory. Once its downloaded, we ask to user where it wants to save the file in “My Files” section and ask for permission to save it. Once user gives permission to save file in certain directory in “My files” section, we move the files in that location.</p><p><strong>For IOS:</strong></p><p>We first download the files temporarily to File System document directory. IOS directly supports <strong>“Save to Files”</strong> feature which we will implement through <strong>react-native-share</strong>. On IOS, once file is downloaded to document directory, through <strong>react-native-share </strong>you can open following popup through which user is able to save all the files to the file explorer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeUj0aHOmnvvFj0gBTepvg.png" /></figure><p>For android, first we will ensure directory where we want to temporarily download the files, exist. If not we create it.</p><pre>export const DOCUMENT_DIR = `${FileSystem.documentDirectory}`;<br><br>export const doesDirExist = async (dir: string) =&gt; {<br>  const dirInfo = await FileSystem.getInfoAsync(dir);<br>  return dirInfo.exists;<br>};<br><br>// Creates the directory<br>export const createDir = async (dir: string) =&gt; {<br>  await FileSystem.makeDirectoryAsync(dir, { intermediates: true });<br>};<br><br>// Checks if gif directory exists. If not, creates it<br>export const ensureDirExists = async (dir: string) =&gt; {<br>  const isExist = await doesDirExist(dir);<br>  if (!isExist) {<br>    console.log(&quot;File directory doesn&#39;t exist, creating…&quot;);<br>    await createDir(dir);<br>  }<br>};<br><br>await ensureDirExists(DOCUMENT_DIR);</pre><p>Then for each file before starting the download, we check if we have sufficient memory in our device to download that file. If not, then we display the same in notification like this:</p><pre>handleNotificationPermission(() =&gt; {<br>      const files = [<br>        {<br>          url: &quot;https://ash-speed.hetzner.com/10GB.bin&quot;,<br>          filename: &quot;10gb.bin&quot;,<br>          size: 10 * 1024 * 1024 * 1024,<br>        },<br>      ];<br>      downloadFiles(files);<br>    });</pre><pre><br>export const getRemoteFileSize = async (<br>  url: string<br>): Promise&lt;number | null&gt; =&gt; {<br>  try {<br>    const response = await fetch(url, { method: &quot;HEAD&quot; });<br>    const contentLength = response.headers.get(&quot;Content-Length&quot;);<br>    return contentLength ? parseInt(contentLength, 10) : null;<br>  } catch (e) {<br>    console.error(&quot;Error fetching file size:&quot;, e);<br>    return null;<br>  }<br>};<br><br>export const getFreeDiskStorage = async () =&gt; {<br>  const info = await FileSystem.getFreeDiskStorageAsync();<br>  return info;<br>};<br><br>let remoteFileSize = await getRemoteFileSize(file.url);<br>        let fileSize = file.size;<br>        if (!remoteFileSize &amp;&amp; !fileSize) {<br>          throw new Error(&quot;Failed to get remote file size&quot;);<br>        }<br>        const freeDiskStorage = await getFreeDiskStorage();<br>        if (freeDiskStorage &lt; (remoteFileSize || fileSize)) {<br>          throw new Error(&quot;Not enough disk space&quot;);<br>        }</pre><p>Either you can pass the size from outside or if size doesn’t exist from user, before downloading we find the file size and then we check if users device has available disk space to download that file. If not, we display the error notification like this</p><pre>updateFileNotification({<br>          file,<br>          title: `${truncate(file.filename)}`,<br>          body: &quot;Failed: &quot; + error.message,<br>          progress: undefined,<br>          actions: [],<br>          iosSound: &quot;default&quot;,<br>        });</pre><p>This is how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*g5z8Yeipomf3aIVJ10ntmg.gif" /></figure><p>Then we start actual download and track its progress and show it in the notification inside progress bar. Android supports progress bar. Ios doesn’t support it.</p><pre>export const download = async (<br>  file: DownloadFile,<br>  callback: (progress: FileSystem.DownloadProgressData) =&gt; void<br>): Promise&lt;FileSystem.FileSystemDownloadResult | undefined&gt; =&gt; {<br>  const downloadResumable = FileSystem.createDownloadResumable(<br>    file.url,<br>    getFileDownloadPath(DOCUMENT_DIR, file.filename),<br>    file.headers ? { headers: file.headers, md5: true } : { md5: true },<br>    callback<br>  );<br>  const notificationId = getNotificationId(file.filename);<br>  const result = await downloadResumable.downloadAsync();<br>  return result;<br>};</pre><p>Above method downloads any file. It accepts a callback which which we pass on to the <strong>createDownloadResumable </strong>method which gives us the realtime bytes download progress of the specific file.</p><pre>const lastProgressMap: Record&lt;string, number&gt; = {};<br><br>const result = await download(file, (progress) =&gt; {<br>          const prog =<br>            progress.totalBytesWritten / progress.totalBytesExpectedToWrite;<br>          const percent = Math.floor(prog * 100);<br>          console.log(&quot;Received progress for &quot; + file.filename + &quot;:&quot;, percent);<br><br>          if (percent &gt; 100 || percent &lt; 0) {<br>            return;<br>          }<br><br>          const lastReported = lastProgressMap[file.filename] ?? 0;<br><br>          if (percent === 100) {<br>            // Always update on complete<br>            updateFileNotification({<br>              file,<br>              title: `${truncate(file.filename)}`,<br>              body: &quot;Download complete.&quot;,<br>              progress: undefined,<br>              actions: [],<br>              iosSound: &quot;default&quot;,<br>            });<br>            lastProgressMap[file.filename] = 100;<br>          } else {<br>            // Calculate threshold bucket (0–9 → 0, 10–19 → 10, etc.)<br>            const currentBucket = Math.floor(percent / 10) * 10;<br>            const lastBucket = Math.floor(lastReported / 10) * 10;<br><br>            if (currentBucket &gt; lastBucket) {<br>              // Only update if we crossed a new bucket<br>              updateFileNotification({<br>                file,<br>                title: `Downloading: ${truncate(file.filename)} - ${percent}%`,<br>                body: undefined,<br>                progress: {<br>                  indeterminate: false,<br>                  max: 100,<br>                  current: percent,<br>                },<br>                actions: [<br>                  {<br>                    title: &quot;Cancel&quot;,<br>                    pressAction: {<br>                      id: &quot;cancel&quot;,<br>                      launchActivity: undefined,<br>                    },<br>                  },<br>                ],<br>                iosSound: undefined,<br>              });<br>              lastProgressMap[file.filename] = percent;<br>            }<br>          }<br>        });</pre><p>We call this method for each file and calculate percent of download completed till now. We make use of <strong>lastProgressMap </strong>to show the download progress in buckets.</p><p>That means instead of showing progress like</p><p>1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7-&gt; 8-&gt; 9 -&gt; 10 -&gt; 11-&gt; 12 … upto 100</p><p>We show it like this:</p><p>1 -&gt; 10 -&gt; 20 -&gt; 30 -&gt; 40 … upto 100</p><p>When download percentage reaches 100, we update notification to show <strong>“Download complete”</strong>.</p><p>While download is in progress, we show the <strong>“Cancel”</strong> button. User can cancel the ongoing file download. We will see its click implementation later.</p><p>After all files download promises are settled, we update the summary notification.</p><pre>updateSummaryNotification(<br>      &quot;Downloads Summary&quot;,<br>      failCount === 0<br>        ? `${successCount} file(s) downloaded successfully.`<br>        : `${<br>            successCount &gt; 0 ? successCount + &quot; succeeded, &quot; : &quot;&quot;<br>          }${failCount} failed.`<br>    );</pre><p>So as of now, we have downloaded all the files to the document directory temporarily. Now in case of android, we need to get permission from user about saving all files downloaded in “My Files” directory of device and in case of IOS, we need to show “Save to Files” popup.</p><pre>const directoryUri = await getStoragePermissions();<br>      const urisToShare: string[] = [];<br><br>      //Process stored files one by one<br>      for (let i = 0; i &lt; successFiles.length; i++) {<br>        const result = successFiles[i];<br>        const { filename } = files[i];<br><br>        if (result.status === &quot;fulfilled&quot;) {<br>          const { uri } = result.value;<br>          if (Platform.OS === &quot;android&quot;) {<br>            if (directoryUri) {<br>              try {<br>                const base64 = await readFileContentAsBase64(uri);<br>                const fileUri = await createNewFile(<br>                  directoryUri,<br>                  filename,<br>                  result.value.headers[&quot;content-type&quot;]<br>                );<br>                await writeFileContent(fileUri, base64);<br>              } catch (err) {<br>                console.log(`❌ Error saving ${filename} to Downloads`, err);<br>              }<br>            } else {<br>              // Android fallback: add to share list<br>              urisToShare.push(uri);<br>            }<br>          } else {<br>            // iOS: add to share list<br>            urisToShare.push(uri);<br>          }<br>        } else {<br>          console.log(`❌ Download failed for ${filename}`, result.reason);<br>        }<br>      }</pre><p>For android: We get the directory permission. If user grants, we read the file content as base64 and then create new file in that directory which user granted permission for. Then in that new file, we write all the base 64 contents.</p><p>If user deny permission for directory for android, we store all uris into <strong>urisToShare.</strong></p><p>For IOS: For ios also, we store all uris into <strong>urisToShare</strong></p><pre>import Share from &quot;react-native-share&quot;;<br><br>export const shareFile = async (urisToShare: string[]) =&gt; {<br>  try {<br>    await Share.open({<br>      urls: urisToShare,<br>      failOnCancel: false,<br>      saveToFiles: true,<br>    });<br>  } catch (err) {<br>    throw err;<br>  }<br>};<br><br>if (urisToShare.length &gt; 0) {<br>        try {<br>          await shareFile(urisToShare);<br>        } catch (err) {<br>          console.log(&quot;❌ Error sharing files:&quot;, err);<br>        }<br>      }</pre><p>Now at the end we use <strong>shareFile</strong> method from react-native-share which opens the “Save to Files” popup for ios and stores all the uris into location user selects. For android in case user deny permission for directory/ doesnt save anything, it opens the popup like this where user is given an option to share it with any other app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*C07l_vSbDKCbHcEg3IncKw.png" /></figure><p>At the end once everything is done, we delete the directory where all the temp files were saved.</p><pre>export const deleteAllFiles = async () =&gt; {<br>  console.log(&quot;Deleting all files…&quot;);<br>  await FileSystem.deleteAsync(DOCUMENT_DIR);<br>};<br>   <br> deleteAllFiles();</pre><p>Now let’s see how we can handle “Cancel” button click for any ongoing file download. Expectation is once user clicks on cancel for any file download, ongoing download should be stopped and notification should be removed.</p><p>For that we first maintain and store all the download resumable objects which is returned from <strong>FileSystem.createDownloadResumable</strong> method.</p><pre>import * as FileSystem from &quot;expo-file-system&quot;;<br><br>export const activeDownloads: Record&lt;string, FileSystem.DownloadResumable&gt; = {};<br><br>export const fetchDownload = (id: string) =&gt; {<br>  return activeDownloads[id];<br>};<br><br>export const storeDownload = (<br>  id: string,<br>  downloadResumable: FileSystem.DownloadResumable<br>) =&gt; {<br>  activeDownloads[id] = downloadResumable;<br>};<br><br>export const removeDownload = (id: string) =&gt; {<br>  delete activeDownloads[id];<br>};<br><br>export const eraseDownloads = () =&gt; {<br>  Object.keys(activeDownloads).forEach((key) =&gt; {<br>    removeDownload(key);<br>  });<br>};</pre><p>Then while starting each download, we store the download resumable object.</p><pre>export const download = async (<br>  file: DownloadFile,<br>  callback: (progress: FileSystem.DownloadProgressData) =&gt; void<br>): Promise&lt;FileSystem.FileSystemDownloadResult | undefined&gt; =&gt; {<br>  const downloadResumable = FileSystem.createDownloadResumable(<br>    file.url,<br>    getFileDownloadPath(DOCUMENT_DIR, file.filename),<br>    file.headers ? { headers: file.headers, md5: true } : { md5: true },<br>    callback<br>  );<br>  const notificationId = getNotificationId(file.filename);<br>  //store download resumable.<br>  storeDownload(notificationId, downloadResumable);<br>  const result = await downloadResumable.downloadAsync();<br>  return result;<br>};</pre><p>This gives us capability to pause, resume, stop the ongoing download.</p><pre>downloadResumable.cancelAsync()</pre><p>Above method cancels the ongoing download for certain download resumable object.</p><p>Now whenever user clicks on notification while app is in foreground, notifee sends us those click events in <strong>onForegroundEvent.</strong></p><p>Whenever user clicks on notification while app is in background, notifee sends us those click events in <strong>onBackgroundEvent.</strong></p><p>Also if you remember while showing cancel button, we had attached an id to it.</p><pre>               actions: [<br>                  {<br>                    title: &quot;Cancel&quot;,<br>                    pressAction: {<br>                      id: &quot;cancel&quot;,<br>                      launchActivity: undefined,<br>                    },<br>                  },<br>                ],</pre><pre>notifee.onBackgroundEvent(async ({ type, detail }) =&gt; {<br>  if (type === EventType.ACTION_PRESS &amp;&amp; detail.pressAction?.id === &quot;cancel&quot;) {<br>    const notificationId = detail.notification?.id;<br>    if (!notificationId) return;<br><br>    console.log(&quot;Cancel pressed for&quot;, notificationId);<br><br>    await cancelNotification(notificationId);<br>  }<br>});<br><br>notifee.onForegroundEvent(async ({ type, detail }) =&gt; {<br>  if (type === EventType.ACTION_PRESS &amp;&amp; detail.pressAction?.id === &quot;cancel&quot;) {<br>    const notificationId = detail.notification?.id;<br>    if (!notificationId) return;<br><br>    console.log(&quot;Cancel pressed for&quot;, notificationId);<br><br>    await cancelNotification(notificationId);<br>  }<br>});</pre><p>Here’s how we will match the action button id and also notification id inside these 2 event handlers and then call <strong>cancelNotification.</strong></p><pre><br>const cancelNotification = async (notificationId: string) =&gt; {<br>  // 1. Cancel notification<br>  await notifee.cancelNotification(notificationId);<br><br>  // 2. Cancel actual download<br>  const resumable = fetchDownload(notificationId);<br>  if (resumable) {<br>    try {<br>      await resumable.cancelAsync();<br>      console.log(`✅ Download cancelled: ${notificationId}`);<br>    } catch (err) {<br>      console.log(`❌ Error cancelling: ${notificationId}`, err);<br>    } finally {<br>      removeDownload(notificationId); // cleanup<br>    }<br>  }<br>};</pre><p><strong>cancelNotification</strong> will actually first remove the notification from notification bar. Then it will fetch resumable object for that notification and stop the ongoing download. Finally it will cleanup resumable object which was stored inside <strong>activeDownloads.</strong></p><p>Also if file download and save was successful, at the end we remove all the resumable objects.</p><pre>eraseDownloads();</pre><p>That’s it. I hope this POC was helpful to you. Once you understand this you can add many features on top of this as per your requirement.</p><p>I’ve already created various tech blogs in my leisure time. You can find more of such articles on my profile.</p><p>To stay updated on future articles, don’t forget to follow me! After following, you’ll get future articles right in your email inbox. Also, give this post <strong>50 claps 👏</strong> if you enjoyed this post and learned something useful. Your enthusiasm and support fuel my passion for sharing knowledge in the tech community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bca741c68b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning a Coding Assistant into a cost-effective Autonomous AI Agent]]></title>
            <link>https://medium.com/@varunkukade999/turning-a-coding-assistant-into-a-cost-effective-autonomous-ai-agent-768aafcd358b?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/768aafcd358b</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 13:58:56 GMT</pubDate>
            <atom:updated>2025-08-23T04:02:53.111Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2: Turning an AI Coding Assistant into a cost-effective Autonomous AI Agent</h3><p>Converting guided flow → Autonomous AI Agent.</p><p>I started with a coding assistant that followed every instruction I gave — a guided flow. Then I transformed it into an autonomous AI agent that plans, executes, learns from mistakes, and revises its strategy.</p><p>🔗 <strong>Guided flow code</strong>: <a href="https://github.com/altirllc/altir-ai-codegen/tree/develop">GitHub Repository<br></a>📄 <strong>Guided flow article</strong>: <a href="https://medium.com/@varunkukade999/i-built-my-own-ai-coding-assistant-in-python-8e9079e8b9fc">I Built My Own AI Coding Assistant in Python</a></p><p>I recommend exploring the guided flow first — it’s the foundation for everything we’ll cover in this article.</p><p>If you’re completely new to AI, I’ve created a <strong>beginner-friendly 3-part series</strong> to help you build your first AI chatbot from scratch:</p><p><strong>Part 1</strong> → <a href="https://medium.com/@varunkukade999/part-1-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-3b370bb6e7c1">Build Your First AI Agent Chatbot with LangChain and LangGraph in Python</a><br><strong>Part 2</strong> → <a href="https://medium.com/@varunkukade999/part-2-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-dc9b4cffce06">Build Your First AI Agent Chatbot — Continued</a><br><strong>Part 3</strong> → <a href="https://medium.com/@varunkukade999/part-3-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-5d1716098b7d">Final Steps to Your AI Chatbot</a></p><p>Going through this series will give you the perfect foundation before diving into autonomous AI agents.</p><p>In the guided flow, I created <strong>separate nodes</strong> for each task. The flow then moved between these nodes either through <strong>predefined edges</strong> or via <strong>LLM-based routing</strong>.</p><pre>self.graph.add_node(&quot;prepare_llm&quot;, code_assistant_nodes.prepare_llm)<br>self.graph.add_node(&quot;decode_files&quot;, code_assistant_nodes.decode_files)<br>self.graph.add_node(&quot;human_feedback&quot;, code_assistant_nodes.human_feedback)<br>self.graph.add_node(&quot;analyse_feedback&quot;, code_assistant_nodes.analyse_feedback)<br>self.graph.add_node(&quot;fetch_files&quot;, code_assistant_nodes.fetch_files)<br>self.graph.add_node(&quot;llm_call&quot;, code_assistant_nodes.llm_call)<br>self.graph.add_node(&quot;update_file&quot;, code_assistant_nodes.update_file)<br>self.graph.add_node(&quot;human_approval&quot;, code_assistant_nodes.human_approval)<br>self.graph.add_node(&quot;approved_path&quot;, code_assistant_nodes.approved_path)<br>self.graph.add_node(&quot;rejected_path&quot;, code_assistant_nodes.rejected_path)</pre><h3>Three Approaches to AI Agent Architectures: From Guided to Autonomous</h3><p>When building AI agents, you face a fundamental trade-off between <strong>cost efficiency</strong> and <strong>autonomous behavior</strong>. Here are three distinct approaches that I found, each with clear advantages and limitations:</p><h3>1. Deterministic Workflow: The Guided Approach</h3><p><strong>Architecture:</strong></p><ul><li>Predefined nodes with fixed routing through edges</li><li>LLM makes routing decisions based on structured outputs</li><li>Separate specialized nodes for each tool/operation</li></ul><p><strong>Characteristics:</strong></p><ul><li>✅ <strong>Ultra-low token usage</strong> — Minimal LLM calls</li><li>✅ <strong>Highly cost-efficient</strong> — Predictable execution costs</li><li>✅ <strong>Reliable and debuggable</strong> — Clear execution paths</li><li>❌ <strong>Zero autonomy</strong> — Cannot adapt to unexpected situations</li><li>❌ <strong>No learning capability</strong> — Cannot recover from mistakes on its own.</li><li>❌ <strong>Requires complete pre-planning</strong> — Every scenario must be anticipated</li></ul><p><strong>Best for:</strong> Well-defined, repetitive tasks with predictable workflows</p><h3>2. Non-Deterministic Workflow: The Fully Autonomous Agent (Tool Calling)</h3><p><strong>Architecture:</strong></p><ul><li>Two-node system: Agent (decision maker) + Tool Executor</li><li>The agent analyzes the situation and selects the next tool <strong>after every step</strong></li><li>Continuous feedback loop until goal completion.</li></ul><p><strong>Characteristics:</strong></p><ul><li>✅ <strong>True autonomy</strong> — Thinks, plans, and adapts independently</li><li>✅ <strong>Self-correcting</strong> — Learns from mistakes and adjusts strategy</li><li>✅ <strong>Handles novel scenarios</strong> — No predefined workflows needed</li><li>❌ <strong>Extremely expensive</strong> — High-frequency LLM calls</li><li>❌ <strong>Unpredictable costs</strong> — Token usage scales with complexity</li><li>❌ <strong>Potential inefficiency</strong> — May take suboptimal paths</li></ul><p><strong>Best for:</strong> Complex, unpredictable tasks requiring genuine problem-solving</p><h3>3. Hybrid Approach: The Smart Balance</h3><p><strong>Architecture:</strong></p><ul><li>Three-node system: Strategic Planner + Task Executor + Flow Controller</li><li>Planner creates execution steps, Executor runs them sequentially</li><li><strong>Selective replanning</strong> — Only when step results indicate the need for course correction</li></ul><p>This is similar to “plan and execute” architecture: <br><a href="https://langchain-ai.github.io/langgraph/tutorials/plan-and-execute/plan-and-execute/#plan-and-execute">https://langchain-ai.github.io/langgraph/tutorials/plan-and-execute/plan-and-execute/#plan-and-execute</a>. The only improvement we do here is that we don’t replan after each step. We first check if we need to actually replan, and only then replan. This reduces the cost of LLM calls utilized for unnecessary replanning in case of a lengthy task.</p><p><strong>Key Innovation:</strong></p><pre>Plan → Execute → Evaluate → Continue OR Replan</pre><p><strong>Characteristics:</strong></p><ul><li>✅ <strong>Cost-optimized autonomy</strong> — 70–90% token reduction vs full autonomy</li><li>✅ <strong>Adaptive planning</strong> — Adjusts strategy when circumstances change</li><li>✅ <strong>Intelligent resource usage</strong> — LLM calls only when genuinely needed</li><li>✅ <strong>Scalable complexity</strong> — Handles both simple and complex tasks efficiently</li><li>⚖️ <strong>Balanced trade-offs</strong> — Some autonomy constraints for significant cost savings</li></ul><p><strong>Decision Logic:</strong></p><ul><li><strong>Continue execution:</strong> Standard success cases, predictable outcomes</li><li><strong>Trigger replanning:</strong> Failures, ambiguous results, new information discovered</li></ul><h3>The Bottom Line</h3><p>The <strong>hybrid approach</strong> represents the sweet spot for most real-world applications — delivering meaningful autonomy while maintaining cost efficiency.</p><blockquote><strong>Note:</strong> The use case in this article is a simplified example of an autonomous agent architecture. However, the core concept remains the same for any autonomous agent: it should <strong>plan</strong>, <strong>execute</strong>, and <strong>replan</strong> based on mistakes, learnings, and the results of executed steps.</blockquote><p>Before we start coding, here’s the complete code we’ll be building.</p><p>🔗 <strong>Agentic flow code</strong>: <a href="https://github.com/altirllc/altir-ai-codegen/tree/agent">GitHub Repository</a></p><p>In my earlier approach, I created a new graph for every query. Now, I build the graph only once and reuse it for all queries.</p><pre>graph_builder = GraphBuilder()<br>graph = graph_builder.compile_graph()</pre><pre>for chunk in graph.stream(<br>        request,<br>        config=config,<br>        stream_mode=&quot;updates&quot;,<br>        context={<br>            &quot;model_provider&quot;: model_provider,<br>            &quot;model_name&quot;: model_name,<br>        },<br>    ):</pre><p>When asking a query, I first request the <strong>model provider</strong> and <strong>model name</strong>, then pass them as context while invoking the query.</p><p>I now have the following nodes:</p><pre>self.graph.add_node(&quot;prepare_llm&quot;, code_assistant_nodes.prepare_llm)<br>self.graph.add_node(&quot;strategic_planner&quot;, code_assistant_nodes.strategic_planner)<br>self.graph.add_node(&quot;task_executor&quot;, code_assistant_nodes.task_executor)<br>self.graph.add_node(&quot;workflow_completed&quot;, code_assistant_nodes.workflow_completed)<br>self.graph.add_node(&quot;workflow_terminated&quot;, code_assistant_nodes.workflow_terminated)<br><br># Add edges to the graph<br>self.graph.add_edge(START, &quot;prepare_llm&quot;)<br>self.graph.add_edge(&quot;prepare_llm&quot;, &quot;strategic_planner&quot;)<br>self.graph.add_edge(&quot;strategic_planner&quot;, &quot;task_executor&quot;)<br>self.graph.add_edge(&quot;workflow_completed&quot;, END)<br>self.graph.add_edge(&quot;workflow_terminated&quot;, END)</pre><p><strong>prepare_llm</strong> → Prepares the LLM model for query invocation.</p><p><strong>strategic_planner</strong> → Plans the steps initially, and replans later based on the results of previous steps.</p><p><strong>task_executor</strong> → Executes the steps from the <strong>strategic_planner</strong>’s plan one by one, then decides the next node:</p><ul><li>If replanning is needed → go back to <strong>strategic_planner</strong></li><li>If the flow should end early → go to <strong>workflow_terminated</strong></li><li>If all steps are done → go to <strong>workflow_completed</strong></li></ul><p><strong>workflow_completed</strong> → Runs the final code after the flow is completed.</p><p><strong>workflow_terminated</strong> → Runs the final code after the flow is terminated.</p><p>I’ve also defined the respective <strong>edges</strong> between the nodes. The only exception is the edge from <strong>task_executor</strong>, as it’s decided <strong>on the fly</strong> based on the result of each task’s execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UD0r886ZgimMjDZ56AtokQ.png" /></figure><pre>def prepare_llm(self, state: CodeAssistantState, runtime: Runtime[CodeAssistantContextSchema]):<br>        requested_llm = getattr(runtime, &quot;context&quot;, {}).get(&quot;model_provider&quot;, &quot;&quot;)<br>        requested_model = getattr(runtime, &quot;context&quot;, {}).get(&quot;model_name&quot;, &quot;&quot;)<br>        if requested_llm == &quot;openai&quot;:<br>            self.llm = OpenAIProvider(model_name=requested_model).get_llm()<br>        elif requested_llm == &quot;groq&quot;:<br>            self.llm = GroqProvider(model_name=requested_model).get_llm()</pre><p>For every node, we have access to the <a href="https://langchain-ai.github.io/langgraph/concepts/low_level/?h=runtime#runtime-context"><strong>runtime context</strong></a> passed during invocation. From this context, we retrieve the values of <strong>model_provider</strong> and <strong>model_name</strong>. Based on the selected model provider, we obtain the LLM instance from its corresponding provider class.</p><p>Here’s an example — the <strong>OpenAIProvider</strong> class:</p><p><strong>main.py</strong></p><pre># Load environment variables<br>load_dotenv()</pre><p><strong>openai.py</strong></p><pre>from langchain_openai import ChatOpenAI<br>import os<br>import getpass<br><br><br>def get_api_key(env_var: str, prompt: str) -&gt; None:<br>    if not os.environ.get(env_var):<br>        os.environ[env_var] = getpass.getpass(prompt)<br><br><br>class OpenAIProvider:<br>    def __init__(self, model_name: str):<br>        self.model_name = model_name<br><br>    def get_llm(self):<br>        try:<br>            get_api_key(&quot;OPENAI_API_KEY&quot;, &quot;Enter API key for OpenAI: &quot;)<br><br>            if not self.model_name:<br>                raise ValueError(&quot;Model name is not provided&quot;)<br><br>            llm = ChatOpenAI(<br>                model=self.model_name,<br>                temperature=0,<br>                max_tokens=None,<br>                timeout=None,<br>                max_retries=2,<br>            )<br>            return llm<br>        except Exception as e:<br>            raise ValueError(f&quot;Error occurred while initializing OpenAI : {e}&quot;)</pre><p>Before returning the LLM instance, it checks if the API key exists; if not, it asks for it using <strong>getpass</strong>.</p><p>Once we have the respective LLM, let’s get started with the <strong>strategic_planner</strong> node.</p><h3>Strategic Planner Node</h3><p>The planner node has two tasks:</p><ol><li><strong>Plan</strong> → If there is no plan yet, create a new plan from scratch</li><li><strong>Replan</strong> → If there is an existing plan, discard all steps after the last executed step and create new steps for further execution.</li></ol><h4><strong>Inputs to the planner node:</strong></h4><p><strong>is_replanning_needed</strong> → Indicates whether the LLM should plan or replan.</p><p><strong>step_number_to_replan_from</strong> → In case of replanning, specifies the step number in the existing plan from which to replan.</p><p><strong>execution_plan</strong> → In case of replanning, provides the existing execution plan.</p><pre>def strategic_planner(self, state: CodeAssistantState):<br>        print(&quot;Inside Strategic Planner&quot;)<br>        strategic_planner_chain = (<br>            self.code_assistant_chains.create_strategic_planner_chain(self.llm)<br>        )<br>        is_replanning_needed = bool(state.ambiguous_files) or bool(state.decision) or bool(state.additional_query)<br>        is_ambiguous = True if state.ambiguous_files else False<br>        decision = &quot;Changed Accepted&quot; if state.decision == &quot;accept&quot; else &quot;Changed Rejected&quot; if state.decision == &quot;reject&quot; else &quot;No Decision yet&quot;<br>        strategic_planner_output: StrategicPlannerOutput = strategic_planner_chain.invoke(<br>            {<br>                &quot;messages&quot;: state.messages,<br>                &quot;is_replanning_needed&quot;: is_replanning_needed,<br>                &quot;step_number_to_replan_from&quot;: state.current_step_index + 1,<br>                &quot;execution_plan&quot;: state.execution_plan or &quot;No Execution Plan created yet.&quot;,<br>                &quot;is_ambiguous&quot;: is_ambiguous,<br>                &quot;decision&quot;: decision,<br>            }<br>        )<br>        print(&quot;Strategic Planner Plan: &quot;, strategic_planner_output.plan)<br>        return {<br>            &quot;execution_plan&quot;: strategic_planner_output.plan,<br>        }</pre><h4><strong>After each step, how do we decide whether we need to replan or not?</strong></h4><p>We won’t necessarily need to replan after each step. In autonomous agent use cases, the flow usually consists of deterministic tasks and non-deterministic tasks.</p><p>Let’s take the example of Trip Planning AI Agent:</p><p><strong>Deterministic tasks</strong> → Tasks where the outcome is known in advance and will not affect future steps. Here, the <em>expected</em> outcome is known and fixed, and failure is usually a <strong>technical exception</strong> (like a network error, timeout, or server down).</p><p><strong>1. Fetching country public holidays</strong> from a government API (data is fixed and won’t change the trip structure).<br><strong>2. Sorting attractions by distance</strong> once you already have the list.<br><strong>3. Booking a train ticket</strong> after you’ve already decided on the train (either it books successfully or you retry — the itinerary doesn’t change otherwise).<br><strong>4. Calculating total travel time</strong> between known locations using stored data.<br><strong>5. Fetching visa requirements</strong> from an official database.</p><p>Here, for every task, we can decide by ourselves which task we need to execute next. Example: In case of a failed api call, we need to execute the same api call task again.</p><p><strong>Non-deterministic tasks</strong> → Tasks where the outcome is uncertain and completely unknown, and it might affect future steps. Here, the <em>expected</em> outcome is <strong>inherently uncertain</strong> — even if everything works technically, the result could vary and change the plan. There is a high probability that we would need to change the plan after executing these steps.</p><p><strong>1. Checking live train/bus availability</strong> → If tickets are sold out, the agent needs to pick a different route or time.<br><strong>2. Getting weather forecast</strong> for the travel dates → Bad weather might force the agent to change outdoor sightseeing plans.<br><strong>3. Asking the user for budget preference</strong> → Their answer could completely change the trip plan (luxury vs budget travel).<br><strong>4. Searching for hotel options</strong> → Prices and availability vary, so the chosen hotel could affect location, transport, and activity choices.<br><strong>5. Checking live traffic updates</strong> → Unexpected jams could cause rescheduling of activities.</p><p>In case of <strong>deterministic</strong> tasks, we don’t need to ask the agent to replan. We can direct the flow ourselves. In case of <strong>Non-deterministic</strong> tasks, we will certainly need to ask the agent to replan.</p><p>After executing <strong>Non-deterministic</strong> tasks, to decide whether to replan or not, we store the data inside the state after executing those tasks, and we make use of the stored data. In our example, we will store “<strong>ambiguous_files</strong>”, “<strong>decision</strong>”, and “<strong>additional_query</strong>” in the state. These are the results of the non-deterministic steps, after which replanning was needed.</p><h4>In case of replanning, how can the planner decide which steps to plan further?</h4><p>If the planner knows it needs to replan, it will require some information or results from previously executed steps to make that decision. Therefore, we send <strong>is_ambiguous</strong> and <strong>decision</strong> — these are the results from previous steps that help the planner determine which steps to add or remove during replanning.</p><p>We will review the meaning of these properties later.</p><p>This is how I am prompting it:</p><pre>from langchain_core.prompts import MessagesPlaceholder<br><br>strategic_planner_prompt = [<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;<br>        You are a decision-making AI agent responsible for intelligently planning and replanning the sequence of tools to call.<br>        Your job is to return the correct tool call sequence based on:<br>        - the user&#39;s request and prior conversation<br>        - available tools and their purposes<br>        - execution context (such as replanning flags and tool outputs)<br><br>        ---<br><br>        ## OBJECTIVE:<br><br>        Your goal is to:<br>        1. Understand the user&#39;s request from the conversation (`messages`) and their intent.<br>        2. Use the provided execution context to either:<br>        - Plan from scratch, OR<br>        - Replan from a given point in an existing plan based on updated results.<br>        3. Select tools autonomously and flexibly — not via fixed sequences.<br>        4. Only use tools when necessary, and always respect their input-output dependencies.<br>        5. Finally, return the list of tool names to be called in sequence.<br><br>        These are the tools available to you:<br>           &quot;decode_files&quot;, &quot;resolve_ambiguity&quot;, &quot;analyse_feedback&quot;, &quot;fetch_files&quot;, &quot;llm_call&quot;, &quot;update_file&quot;, &quot;human_approval&quot;, &quot;approved_path&quot;, &quot;rejected_path&quot; <br><br>        ---<br><br>        ## EXECUTION CONTEXT:<br><br>        Here is the structured input:<br><br>        - `messages`: All prior user and assistant messages.<br><br>        - `execution_plan`: A list of previously planned tool names, or an empty list.<br>        Value: {execution_plan}<br>        Consider step number 1 as the first step.<br><br>        - `is_replanning_needed`: A boolean flag that controls your behavior.<br>        Value: {is_replanning_needed}<br><br>        - If `is_replanning_needed` is False:<br>          ⛔ You MUST IGNORE `execution_plan` completely. Do not reference it. Generate a new plan from scratch.<br>        <br>        - `step_number_to_replan_from`: The step number in `execution_plan` from which replanning should begin (inclusive).<br>        Value: {step_number_to_replan_from}<br><br>        - If `is_replanning_needed` is True:<br>            - If `step_number_to_replan_from` is less than or equal to 1, then you MUST ignore `execution_plan` completely. Do not reference it. Generate a new plan from scratch.<br><br>            - If `step_number_to_replan_from` is greater than 1, then you MUST use the given `execution_plan`.<br>              ✅ You MUST retain all steps from step number 1 to (`step_number_to_replan_from` - 1) step number.<br>              ✅ You MUST discard all steps starting at `step_number_to_replan_from` step (if exists) and beyond.<br>              ✅ Then you MUST replan only from `step_number_to_replan_from` step onward, using the updated context.<br>              ✅ The final plan must look like: [KEPT_STEPS..., NEWLY_PLANNED_STEPS...]<br><br>        - You will also receive additional key-value pairs, which are outputs from earlier tools. Make use of this information only for replanning and not for planning from scratch.<br>          Here&#39;s the additional key value pairs you will receive:<br>          - `is_ambiguous`: {is_ambiguous}<br>          - `decision`: {decision}<br><br>        ---<br><br>        ## Here is a purpose of each tool:<br><br>        - Extract the actual task from user query: whether the user wants to analyze, edit, refactor, create, or review files.<br>        - If you need file names to proceed, we first need to call `decode_files`. <br><br>        1. decode_files<br>        Purpose: <br>        - Extract file names from the user&#39;s query.<br>        - Checks if the same file name exists in multiple locations.<br>        - Returns: <br>          - `is_ambiguous`: true/false - If true, it means there are multiple files with the same name in the codebase.<br><br>        2. resolve_ambiguity<br>        - If ambiguity is found, this tool asks user to confirm correct file paths.<br>        - Returns: <br>          - user&#39;s feedback<br>        <br>        3. analyse_feedback<br>        Purpose: After user mentions the file paths we asked for in &quot;resolve_ambiguity&quot;, this tool analyse the user&#39;s feedback. <br>        It also asks user to mention any additional queries user have.<br>        If user also mentions some additional queries, this tool returns those additional queries inside &#39;messages&#39;. <br>        In case of any additional queries, we need to again execute `decode_files` and revise the plan further.<br><br>        4. fetch_files<br>        Purpose: Once we have all file names without any ambiguity, this tool fetches real content from disk for each file.<br><br>        5. llm_call<br>        Purpose: This is a main LLM tool. After all file content is available, this tool performs:<br>        - Analysis only OR<br>        - Edits only OR<br>        - New file creation OR<br>        - Any combination of above OR<br>        - All of the above based on user query.<br><br>        6. update_file<br>        Purpose: If any of the files are updated/created, this tool updates/creates the files back to disk.<br>        - We don&#39;t need this tool if no file is updated/created.<br><br>        7. human_approval<br>        Purpose: After final updates/edits are done, this tool asks user for approval.<br>        - We don&#39;t need this tool if no file is updated/created.<br>        - Returns: <br>          - `decision`: &#39;Changed Accepted&#39; or &#39;Changed Rejected&#39; or &quot;No Decision yet&quot;<br>        - If user accepts the changes, this tool returns &#39;Changed Accepted&#39; as decision.<br>        - If user rejects the changes, this tool returns &#39;Changed Rejected&#39; as decision.<br>        - If user doesn&#39;t make any decision yet, this tool returns &#39;No Decision yet&#39; as decision.<br><br>        8. approved_path<br>        Purpose: This tool executes code corresponding to acceptance of changes.<br><br>        9. rejected_path<br>        Purpose: This tool executes code corresponding to rejection of changes.<br><br>        ---<br><br>        ## EXAMPLES OF SIMPLE DECISION FLOWS:<br><br>        ### 1. &quot;Can you analyze the code in test.py?&quot;<br>        - Call `decode_files` → `fetch_files` → `llm_call`.<br><br>        ### 2. &quot;Add subtraction function to test.py&quot;<br>        - Call `decode_files` → `fetch_files` → `llm_call` → `update_file`→ `human_approval`<br><br>        Note:<br>        1. If query is unrelated to file-level analysis/editing, return `decode_files` as next step inside plan. <br>        Examples:<br>        - “What is the weather today?”  <br>        - “How does ChatGPT work?”  <br>        - Other internet or general queries  <br>        Saying “Hi”, “Hello” is okay.<br>        2. If you couldn&#39;t understand query/is out of scope/any other reason you couldn&#39;t create a plan for it, return `decode_files` as next step inside plan. <br><br>        ## FINAL NOTE:<br>        However the complex is query, think of very simple flow first and return that sequence. <br>        At first instance don&#39;t return the steps which are dependent on previous steps. e.g resolve_ambiguity depends on decode_files.<br>        Only when you have valid updates from prev tool, then you can plan and decide the next steps and change the plan.<br><br>        Your job is not to solve the task directly, but to plan and orchestrate the right tools to solve it.<br>        &quot;&quot;&quot;,<br>    ),<br>    MessagesPlaceholder(&quot;messages&quot;),<br>]</pre><p>I provided it with a list of available tools: <strong>decode_files</strong>, <strong>resolve_ambiguity</strong>, <strong>analyse_feedback</strong>, <strong>fetch_files</strong>, <strong>llm_call</strong>, <strong>update_file</strong>, <strong>human_approval</strong>, <strong>approved_path</strong>, and <strong>rejected_path</strong>.</p><p>If you’ve followed the previous article, you already know what each tool does. The main change is that <strong>decode_files</strong> now also decodes the file names from the query <strong>and</strong> checks if those files have multiple paths. If multiple paths exist, the next tool to execute is <strong>resolve_ambiguity</strong>, which asks the user to confirm the file path. If there is no ambiguity, it should not go to <strong>resolve_ambiguity</strong>.</p><p>I also explained the inputs it has access to — what each input means and its purpose. I instructed it to keep the previous steps as they are and plan further steps in the format:</p><p><strong>[KEPT_STEPS…, NEWLY_PLANNED_STEPS…]</strong></p><p>Then I explained the purpose of each tool. Finally, I asked it to return a simple flow of steps first — steps that don’t depend on any previous ones.</p><p>For a query like <strong>“Explain to me the graph code inside graph_builder.py”</strong>, it returns a straightforward plan:<br><strong> [“decode_files”, “fetch_files”, “llm_call”]</strong></p><p>For a slightly more involved query like <strong>“Please refactor the graph code inside graph_builder.py”</strong>, the returned plan is:<br><strong>[“decode_files”, “fetch_files”, “llm_call”, “update_file”, “human_approval”]</strong></p><p>Once the plan is returned, I store the plan inside a state.</p><pre>return {<br>            &quot;execution_plan&quot;: strategic_planner_output.plan,<br>        }</pre><p>This is how state struture looks:</p><pre>class CodeAssistantState(BaseModel):<br>    messages: Annotated[List[BaseMessage], add_messages]<br>    files: Optional[List[File]] = None<br>    summary: Optional[str] = None<br>    human_feedback: Optional[str] = None<br>    file_path_confirmation_prompt: Optional[str] = None<br><br>    # Needed to decide whether to replan or not<br>    ambiguous_files: List[Tuple[str, List[Path], Optional[str]]] = []<br>    decision: Optional[Literal[&quot;accept&quot;, &quot;reject&quot;]] = None<br>    additional_query: Optional[str] = None<br><br>    # Planning &amp; Execution<br>    execution_plan: List[str] = []           # Current list of planned steps<br>    current_step_index: int = 0              # Which step to execute next<br>    step_executed: Optional[str] = None      # Step that was executed</pre><p>I will explain the state variables and their usage step by step later.</p><h3>Task executor node</h3><pre>if not state.execution_plan:<br>            return Command(<br>                        goto=&quot;workflow_terminated&quot;,<br>                        update={<br>                            &quot;summary&quot;: &#39;Workflow Terminated due to some unexpected error&#39;,<br>                            &quot;files&quot;: None,<br>                            &quot;current_step_index&quot;: 0,<br>                            &quot;execution_plan&quot;: [],<br>                            &quot;completed_tasks&quot;: [],<br>                            &quot;step_executed&quot;: None,<br>                            &quot;file_path_confirmation_prompt&quot;: None,<br>                            &quot;human_feedback&quot;: None,<br>                            &quot;decision&quot;: None,<br>                            &quot;ambiguous_files&quot;: [],<br>                        },<br>                    )       </pre><p>When the flow reaches the <strong>task executor</strong>, the first step is to check if an execution plan exists. If no plan is found, the flow is terminated.</p><p>In most cases, a plan will exist based on the user’s query. For unrelated or random queries like <em>“How’s the weather?”</em> — which have nothing to do with the codebase — I’ve already instructed the <strong>strategic_planner</strong> node’s LLM to return a default plan:</p><p>[“decode_files”]</p><pre>       Note:<br>        1. If query is unrelated to file-level analysis/editing, return `decode_files` as next step inside plan. <br>        Examples:<br>        - “What is the weather today?”  <br>        - “How does ChatGPT work?”  <br>        - Other internet or general queries  <br>        Saying “Hi”, “Hello” is okay.<br>        2. If you couldn&#39;t understand query/is out of scope/any other reason you couldn&#39;t create a plan for it, return `decode_files` as next step inside plan. </pre><p>So, when the user asks a random query as “explain graph”, this is what the planner node returns</p><pre>Strategic Planner Plan:  [&#39;decode_files&#39;]</pre><p>For any query, the first step in the plan will always be <strong>decode_files</strong>.</p><p>So, we fetch that step and execute it within the <strong>task executor</strong>.</p><pre>        task = state.execution_plan[state.current_step_index]<br>        print(&quot;Current Task: &quot;, task)<br>        print(&#39;\n&#39;)<br>        is_replanning_needed = False<br>        should_terminate = False<br>        summary = &#39;&#39;<br>        files = None<br>        new_step_index = state.current_step_index<br>        step_executed = state.step_executed<br>        are_steps_completed = False<br>        file_path_confirmation_prompt = None<br>        human_feedback = None<br>        ambiguous_files = []<br>        messages = []<br>        decision = None<br>        additional_query = None<br>        if task == &quot;decode_files&quot;:<br>            result = self.decode_files(state)</pre><p>First, I reset all the previous values, and then I call <strong>decode_files</strong>.</p><pre>def decode_files(self, state: CodeAssistantState):<br>        if state.files:<br>            formatted_files = format_files_for_prompt(state.files)<br>        else:<br>            formatted_files = []        <br>        decode_file_name_chain = (<br>            self.code_assistant_chains.create_decode_file_name_chain(self.llm)<br>        )<br>        decoded_files: DecodeFileNameOutput = decode_file_name_chain.invoke(<br>            {<br>                &quot;messages&quot;: state.messages,<br>                &quot;formatted_files&quot;: formatted_files or &quot;No Existing Files Found.&quot;,<br>            }<br>        )<br>        # Initialize list to store ambiguous files<br>        ambiguous_files = []<br><br>        # Check for ambiguous files<br>        for file in decoded_files.files:<br>            if not file.file_name:<br>                continue<br>            result = check_file_ambiguity(file)<br>            if result.get(&quot;is_ambiguous&quot;, True) or result.get(&quot;is_ambigious_and_invalid_file_path&quot;, True):<br>                user_provided_path = (<br>                    file.file_path if result.get(&quot;is_ambigious_and_invalid_file_path&quot;, False) else None<br>                )<br>                ambiguous_files.append((file.file_name, result.get(&quot;valid_paths&quot;, []), user_provided_path))<br><br>        if decoded_files.should_end:<br>            return {<br>                &quot;should_terminate&quot;: True,<br>                &quot;is_replanning_needed&quot;: False,<br>                &quot;summary&quot;: decoded_files.summary,<br>            }<br>        if ambiguous_files:<br>            return {<br>                &quot;should_terminate&quot;: False,<br>                &quot;is_replanning_needed&quot;: True,<br>                &quot;ambiguous_files&quot;: ambiguous_files,<br>                &quot;files&quot;: decoded_files.files,<br>            }<br>        return {<br>            &quot;should_terminate&quot;: False,<br>            &quot;is_replanning_needed&quot;: False,<br>            &quot;summary&quot;: decoded_files.summary,<br>            &quot;files&quot;: decoded_files.files,<br>        }</pre><p>For <strong>decode_files</strong>, we call the LLM to extract the file names mentioned in the user’s query.</p><p>After decoding, I check if there are any ambiguous files. If ambiguity exists, I set <strong>is_replanning_needed</strong> to true and pass along both the ambiguous files and the decoded file list.</p><p>I’ve also instructed the decode LLM to return <strong>should_end</strong> as true for random or invalid queries. In such cases, I set <strong>should_terminate</strong> to true.</p><p>Finally, if there’s no ambiguity and no termination needed, I simply return the <strong>summary</strong> and <strong>files</strong> with their file names.</p><p>After executing the task, I fetch the returned result.</p><pre>if task == &quot;decode_files&quot;:<br>            result = self.decode_files(state)<br>            is_replanning_needed = result.get(&quot;is_replanning_needed&quot;, False)<br>            should_terminate = result.get(&quot;should_terminate&quot;, False)<br>            summary = result.get(&quot;summary&quot;, &#39;&#39;)<br>            files = result.get(&quot;files&quot;, None)<br>            ambiguous_files = result.get(&quot;ambiguous_files&quot;, [])<br>            new_step_index = new_step_index + 1<br>            are_steps_completed = new_step_index == len(state.execution_plan)</pre><p>After executing a task, I always increment the <strong>current step index</strong> and check whether all steps in the execution plan have been completed.</p><p>If replanning is required — for example, in the case of ambiguous files — I route the flow back to the <strong>strategic_planner</strong> node. While navigating, I store all the necessary data obtained from the task execution.</p><pre>step_executed = task    <br><br>if is_replanning_needed:<br>            return Command(<br>                goto=&quot;strategic_planner&quot;,<br>                update={<br>                    &quot;summary&quot;: summary,<br>                    &quot;ambiguous_files&quot;: ambiguous_files,<br>                    &quot;current_step_index&quot;: new_step_index,<br>                    &quot;messages&quot;: messages,<br>                    &quot;decision&quot;: decision,<br>                    &quot;step_executed&quot;: step_executed,<br>                    &quot;files&quot;: files,<br>                    &quot;additional_query&quot;: additional_query,<br>                },<br>            )</pre><p>After executing each task, we store it in <strong>step_executed</strong>.</p><p>I’ll explain later why we store <strong>decision</strong>, <strong>step_executed</strong>, and <strong>additional_query</strong>.</p><p>When returning to the <strong>strategic planner</strong>, as mentioned earlier, I decide whether to replan based on whether ambiguous files are present in the state. I also pass <strong>is_ambiguous</strong> as either true or false.</p><pre>is_replanning_needed = bool(state.ambiguous_files) or bool(state.decision) or bool(state.additional_query)<br>        is_ambiguous = True if state.ambiguous_files else False<br>        decision = &quot;Changed Accepted&quot; if state.decision == &quot;accept&quot; else &quot;Changed Rejected&quot; if state.decision == &quot;reject&quot; else &quot;No Decision yet&quot;<br>        strategic_planner_output: StrategicPlannerOutput = strategic_planner_chain.invoke(<br>            {<br>                &quot;messages&quot;: state.messages,<br>                &quot;is_replanning_needed&quot;: is_replanning_needed,<br>                &quot;step_number_to_replan_from&quot;: state.current_step_index + 1,<br>                &quot;execution_plan&quot;: state.execution_plan or &quot;No Execution Plan created yet.&quot;,<br>                &quot;is_ambiguous&quot;: is_ambiguous,<br>                &quot;decision&quot;: decision,<br>            }<br>        )</pre><p>According to the system prompt, the <strong>strategic planner</strong> reasons as follows:</p><p><strong>Is replanning required?</strong> → Yes.</p><p><strong>What steps should I add next?</strong> → Check <strong>is_ambiguous</strong>. It’s true, meaning we found ambiguous files. Therefore, add the <strong>resolve_ambiguity</strong> and <strong>analyse_feedback</strong> steps so the user can help resolve the ambiguity.</p><p><strong>Where should I add these steps?</strong> → Discard all steps after <strong>step_number_to_replan_from</strong> and keep the steps before it. Then, insert the two new steps and rebuild the rest of the plan.</p><p>In this case, <strong>current_step_index</strong> is 1 because only one task (<strong>decode_files</strong>) has been executed.</p><p>The LLM discards all steps from step 2 onward.</p><p>So, if the original plan for the query <em>“Please refactor graph code inside graph_builder.py”</em> was:</p><p>[“decode_files”, “fetch_files”, “llm_call”, “update_file”, “human_approval”]</p><p>The updated plan becomes:</p><p>[“decode_files”, <strong>“resolve_ambiguity”, “analyse_feedback”,</strong> “fetch_files”, “llm_call”, “update_file”, “human_approval”]</p><p>Inside the <strong>task executor</strong>, if <strong>no replanning</strong> is needed, we check for <strong>flow completion</strong>:</p><pre>else:<br>            if are_steps_completed:<br>                return Command(<br>                    goto=&quot;workflow_completed&quot;,<br>                    update={<br>                        &quot;summary&quot;: summary,<br>                        &quot;files&quot;: [],<br>                        &quot;current_step_index&quot;: 0,<br>                        &quot;execution_plan&quot;: [],<br>                        &quot;completed_tasks&quot;: [],<br>                        &quot;step_executed&quot;: step_executed,<br>                    },<br>                )</pre><p>If all steps in the existing plan are completed, we simply mark the flow as <strong>complete</strong>.</p><p>If steps are still remaining, we then check whether the flow should be <strong>terminated mid-way</strong> before proceeding further.</p><pre>else:<br>                if should_terminate:<br>                    return Command(<br>                        goto=&quot;workflow_terminated&quot;,<br>                        update={<br>                            &quot;summary&quot;: summary,<br>                            &quot;files&quot;: None,<br>                            &quot;current_step_index&quot;: 0,<br>                            &quot;execution_plan&quot;: [],<br>                            &quot;completed_tasks&quot;: [],<br>                            &quot;step_executed&quot;: step_executed,<br>                        },<br>                    )</pre><p>If the decode LLM returns <strong>should_end</strong> as true for invalid queries, the flow is terminated with a clear summary explaining why the termination occurred.</p><p>Finally, if there’s no replanning needed, the steps aren’t completed, and no flow termination is required, we simply proceed to execute the next step and navigate the flow back to the <strong>task executor</strong>.</p><pre>else:<br>                    return Command(<br>                        goto=&quot;task_executor&quot;,<br>                        update={<br>                            &quot;current_step_index&quot;: new_step_index,<br>                            &quot;summary&quot;: summary,<br>                            &quot;files&quot;: files,<br>                            &quot;file_path_confirmation_prompt&quot;: file_path_confirmation_prompt,<br>                            &quot;human_feedback&quot;: human_feedback,<br>                            &quot;step_executed&quot;: step_executed,<br>                        },<br>                    )</pre><p>While doing this, we update all the necessary information inside the state. I will explain later why we store <strong>file_path_confirmation_prompt</strong> and <strong>human_feedback</strong> in the state.</p><p>Now, assuming there is ambiguity, when we return to the <strong>task executor</strong>, we reset all previous values and execute the next task in the sequence.</p><pre>if task == &quot;resolve_ambiguity&quot;:<br>            result = self.resolve_ambiguity(state)</pre><pre>def resolve_ambiguity(self, state: CodeAssistantState):<br>        # If there are ambiguous files, prompt the user<br>        file_path_confirmation_prompt = contruct_file_path_confirmation_prompt(<br>            state.ambiguous_files<br>        )<br>        feedback = interrupt(<br>            {<br>                &quot;question&quot;: file_path_confirmation_prompt,<br>                &quot;from&quot;: &quot;human_feedback&quot;,<br>            }<br>        )<br>        return {<br>            &quot;should_terminate&quot;: False,<br>            &quot;is_replanning_needed&quot;: False,<br>            &quot;summary&quot;: &quot;\nPlease wait a moment, I am analysing your feedback...\n&quot;,<br>            &quot;file_path_confirmation_prompt&quot;: file_path_confirmation_prompt,<br>            &quot;human_feedback&quot;: feedback,<br>        }</pre><p><strong>resolve_ambiguity</strong> asks the user to confirm the file path. Once the user responds, we capture the <strong>feedback</strong> along with the original prompt used.</p><p>Next, the <strong>task executor</strong> navigates the flow back to itself to execute the next node in the sequence: <strong>analyse_feedback</strong>.</p><p>Here, we provide both the original stored prompt and the user’s feedback to the <strong>analyse_feedback</strong> LLM so it can analyze the complete scenario.</p><pre>def analyse_feedback(self, state: CodeAssistantState):<br>        formatted_files = format_files_for_prompt(state.files)<br>        analyse_feedback_chain = (<br>            self.code_assistant_chains.create_analyse_feedback_chain(self.llm)<br>        )<br>        analyse_human_feedback_output: AnalyseHumanFeedbackOutput = (<br>            analyse_feedback_chain.invoke(<br>                {<br>                    &quot;formatted_files&quot;: formatted_files,<br>                    &quot;human_feedback&quot;: state.human_feedback,<br>                    &quot;file_path_confirmation_prompt&quot;: state.file_path_confirmation_prompt,<br>                }<br>            )<br>        )<br>        if analyse_human_feedback_output.should_end:<br>            return {<br>                &quot;should_terminate&quot;: True,<br>                &quot;is_replanning_needed&quot;: False,<br>                &quot;summary&quot;: analyse_human_feedback_output.summary,<br>            }<br>        if analyse_human_feedback_output.additional_query:<br>            return {<br>                &quot;should_terminate&quot;: False,<br>                &quot;is_replanning_needed&quot;: True,<br>                &quot;files&quot;: analyse_human_feedback_output.files,<br>                &quot;messages&quot;: [<br>                    AIMessage(<br>                        content=&quot;Do you have any other queries in addition to the above? I can process all of them simultaneously.&quot;<br>                    ),<br>                    HumanMessage(<br>                        content=analyse_human_feedback_output.additional_query<br>                    ),<br>                ],<br>                &quot;summary&quot;: &quot;Thanks for confirming the file paths. Now let me analyse your additional queries.&quot;,<br>                &quot;additional_query&quot;: analyse_human_feedback_output.additional_query,<br>            }<br>        return {<br>            &quot;should_terminate&quot;: False,<br>            &quot;is_replanning_needed&quot;: False,<br>            &quot;files&quot;: analyse_human_feedback_output.files,<br>            &quot;summary&quot;: &quot;Thanks for confirming the file paths. Let me fetch those files...&quot;,<br>        }</pre><p>The <strong>analyse_feedback</strong> task processes the user’s feedback to determine if the file ambiguity has been resolved and takes one of the following actions:</p><ol><li>If the feedback did <strong>not</strong> resolve the ambiguity, it ends the flow by setting <strong>should_terminate</strong> to true.</li><li>If the feedback is valid but includes additional user queries, it extracts those queries, returns them, and requests replanning by setting <strong>is_replanning_needed</strong> to true.</li></ol><pre>is_replanning_needed = bool(state.ambiguous_files) or bool(state.decision) or bool(state.additional_query)<br>        is_ambiguous = True if state.ambiguous_files else False<br>        decision = &quot;Changed Accepted&quot; if state.decision == &quot;accept&quot; else &quot;Changed Rejected&quot; if state.decision == &quot;reject&quot; else &quot;No Decision yet&quot;<br>        strategic_planner_output: StrategicPlannerOutput = strategic_planner_chain.invoke(<br>            {<br>                &quot;messages&quot;: state.messages,<br>                &quot;is_replanning_needed&quot;: is_replanning_needed,<br>                &quot;step_number_to_replan_from&quot;: state.current_step_index + 1,<br>                &quot;execution_plan&quot;: state.execution_plan or &quot;No Execution Plan created yet.&quot;,<br>                &quot;is_ambiguous&quot;: is_ambiguous,<br>                &quot;decision&quot;: decision,<br>            }<br>        )</pre><p>Now strategic planner updates its existing plan from <br>[“decode_files”, “resolve_ambiguity”, “analyse_feedback”, “fetch_files”, “llm_call”, “update_file”, “human_approval”]<br>to:<br>[“decode_files”, “resolve_ambiguity”, “analyse_feedback”, “<strong>decode_files</strong>”, “fetch_files”, “llm_call”, “update_file”, “human_approval”]</p><p>After analyzing feedback, it adds a new <strong>decode_files</strong> task to process additional file names mentioned in the user’s additional query.</p><p>The <strong>task executor</strong> then runs this new <strong>decode_files</strong> task, identifies the file names in the additional query, and updates the existing <strong>files</strong> state with these new files.</p><p>Afterwards, the flow continues as usual, following the control after the <strong>decode_files</strong> output.</p><p>3. If the feedback resolves the file ambiguity and there are no additional queries, the flow neither terminates nor replans. Instead, it proceeds to the next step in the existing plan</p><p>[“decode_files”, “resolve_ambiguity”, “analyse_feedback”, “fetch_files”, “llm_call”, “update_file”, “human_approval”]</p><p>The next step is <strong>fetch_files</strong>, which fetches the original file content, followed by <strong>llm_call</strong>, which analyzes or refactors the file.</p><p>After executing either of these steps, the flow continues to the next step without replanning or termination.</p><p>For queries like <strong>“Explain to me the graph code inside graph_builder.py”</strong>, all steps are completed after <strong>llm_call</strong>, and the summary is presented to the user.</p><p>For bugfix, refactoring, or editing queries, the remaining steps are:[“update_file”, “human_approval”]</p><ul><li><strong>update_file</strong> updates the file content with changes from <strong>llm_call</strong>.</li><li><strong>human_approval</strong> presents the change summary to the user and asks whether to accept or reject the changes.</li></ul><pre>def human_approval(self, state: CodeAssistantState):<br>        interrupt_response: dict = interrupt(<br>            {<br>                &quot;question&quot;: f&quot;Here is the summary of changes \n {state.summary}\n Do you approve the output? Type &#39;accept&#39; or &#39;reject&#39;:- &quot;,<br>                &quot;from&quot;: &quot;human_approval&quot;,<br>            }<br>        )<br>        decision: str = interrupt_response.get(&quot;decision&quot;, &quot;&quot;)<br>        states_history: list[StateSnapshot] = interrupt_response.get(&quot;state_history&quot;, [])<br>        print(&#39;\n&#39;)<br>        print(&quot;States history: &quot;, states_history)  <br>        print(&#39;\n&#39;)<br>        # Get the state of graph before llm call and after update file<br>        state_before_llm_call: StateSnapshot | None = None<br>        state_after_llm_call: StateSnapshot | None = None<br>        if states_history:<br>            for each_state in states_history:<br>                if getattr(each_state, &quot;values&quot;, None).get(&quot;step_executed&quot;, &quot;&quot;) == &quot;fetch_files&quot;:<br>                    state_before_llm_call = each_state<br>                if getattr(each_state, &quot;values&quot;, None).get(&quot;step_executed&quot;, &quot;&quot;) == &quot;llm_call&quot;:<br>                    state_after_llm_call = each_state<br>        # Get the final list of files with their original content to reverse the changes in case of rejection<br>        files_to_reverse = get_files_to_reverse(<br>            getattr(state_before_llm_call, &quot;values&quot;, None).get(&quot;files&quot;, None), <br>            getattr(state_after_llm_call, &quot;values&quot;, None).get(&quot;files&quot;, None)<br>        )<br>        print(&quot;\n&quot;)<br>        print(&quot;Files to reverse: &quot;, files_to_reverse)<br>        print(&quot;\n&quot;)<br>        return {<br>                &quot;is_replanning_needed&quot;: True,<br>                &quot;should_terminate&quot;: False,<br>                &quot;files&quot;: state.files if decision == &quot;accept&quot; else files_to_reverse,<br>                &quot;decision&quot;: decision,<br>                &quot;summary&quot;: &quot;&quot;<br>            }</pre><p>Once the user confirms their decision, we need to replan based on their choice:</p><ul><li>If the user selects <strong>“accept”</strong>, a new step <strong>approved_path</strong> is added and executed next.</li><li>If the user selects <strong>“reject”</strong>, a new step <strong>rejected_path</strong> is added and executed next. In this case, we must reverse the changes applied during the <strong>update_file</strong> task.</li></ul><p>Using the checkpoint mechanism, LangGraph maintains copies of its state after each update. We retrieve the state history to identify the state <strong>before</strong> and <strong>after</strong> the LLM update. This helps us determine which files were updated and their original content.</p><p>Here, <strong>step_executed</strong> helps track which step was executed for each state copy. After identifying the original files and contents, we store them in the <strong>files</strong> state so the <strong>rejected_path</strong> can act on them.</p><p>Finally, I instruct the planner to replan by setting <strong>is_replanning_needed</strong> to true and storing the user’s <strong>decision</strong> in the state so the planner can access it and create the next plan accordingly.</p><p>Now Planner creates a new plan as</p><ul><li>If rejected:<br>[“decode_files”, “resolve_ambiguity”, “analyse_feedback”, “fetch_files”, “llm_call”, “update_file”, “human_approval”, “<strong>rejected_path”</strong>]</li><li>If accepted:<br>[“decode_files”, “resolve_ambiguity”, “analyse_feedback”, “fetch_files”, “llm_call”, “update_file”, “human_approval”, “<strong>approved_path”</strong>]</li></ul><p>The <strong>task executor</strong> executes the <strong>approved_path</strong> or <strong>rejected_path</strong> task accordingly. For the rejected path, it reverses changes by restoring files to their original content.</p><p>After completing all steps, the flow navigates to the <strong>workflow_completed</strong> node.</p><p>That’s it! We successfully transformed our directed flow into a cost-effective autonomous agent that thinks, replans, and adapts as needed. I hope you now understand the core concepts behind building helpful and intelligent AI agents for your own use cases.</p><p>If you have any doubts or feedback, please feel free to share them in the comments.</p><h4>Limitations of this basic coding assistant:</h4><ul><li>At this stage, the AI assistant <strong>requires explicit file names</strong> to analyze, edit, or refactor.</li><li>If file names are not provided, it will fail — it cannot infer which files to modify solely from the user query.</li><li>It also cannot track dependent files through imports or other relationships.</li></ul><p>This is because I haven’t yet integrated AST (Abstract Syntax Tree) analysis and semantic search — two features that significantly enhance the assistant’s contextual understanding of the codebase.</p><p><strong>Without AST:</strong></p><p>The assistant cannot build a dependency graph mapping function usage, property access, or file-level interdependencies.</p><p><strong>Without semantic search:</strong></p><p>It cannot search for specific properties, methods, classes, components, states, and so on. This limits its ability to handle complex global refactoring tasks such as:</p><ul><li>Searching and renaming all instances of a function like add_numbers across the entire codebase</li><li>Refactoring an entire flow, like the authentication process, end-to-end</li></ul><p>Once AST-based analysis and dependency graph generation are added, the assistant will have full visibility into the codebase’s structure and relationships. This will enable it to track symbol references accurately, understand cross-file dependencies, and perform advanced code transformations with confidence.</p><p>I plan to cover these enhancements in the next articles.</p><p><strong>Edit - 23rd Aug 2025: </strong>I made some more improvements to the code in <a href="https://github.com/altirllc/altir-ai-codegen/tree/agent_with_dependency_resolution">this</a> branch.<br>1. I added a good amount of user logs in this branch. Created a separate utility class called <strong>SimpleLogger.</strong></p><p>2. Now I create a dependency map which holds all the file dependencies for each file, like this: I created code for <strong>dependency_map</strong> using “Claude Sonnet 4”. I don’t think it provided production-ready code. But it works in 70–80% of cases. I think we should use some third-party dependencies for this.</p><pre>dependency_map = {<br>    &quot;main_file.py&quot;: [<br>        {&quot;name&quot;: &quot;auth.py&quot;, &quot;path&quot;: &quot;src/core/auth.py&quot;},<br>        {&quot;name&quot;: &quot;main_graph.py&quot;, &quot;path&quot;: &quot;src/utils/main_graph.py&quot;},<br>    ],<br>    &quot;src/core/auth.py&quot;: [],<br>    &quot;src/utils/main_graph.py&quot;: [{&quot;name&quot;: &quot;config.py&quot;, &quot;path&quot;: &quot;src/config.py&quot;}],<br>    &quot;src/config.py&quot;: [],<br>}</pre><p>I pass dependencies for the main file to “<strong>llm_call</strong>” and then llm returns us “<strong>required_files</strong>”. Think of it like this. You start looking into a bug, and you make some changes to the main file. But now you see that this file imports a method from another file, and that method may also need some changes. So you hop over to that method in another file, analyse, and make the changes in that method. In the same way, I instructed LLM to make the changes in the main file given and then tell us which more “<strong>required_files</strong>” it needs to analyse/update.</p><p>After LLM gives us “<strong>required_files</strong>”, we fetch those files and give them back to LLM by calling the “<strong>llm_call</strong>” node. In case LLM made some changes to the main file, we first update that file through the “<strong>update_files</strong>” node and show them to the end user, and then go to fetch “<strong>required_files</strong>”.</p><p>2. Also, I realized, I don’t need to turn “<strong>Replanner</strong>” into an agent. I was complicating that unnecessarily.</p><p>I divided the planner and replanner node as follows:</p><p><strong>Planner node:</strong> I made the planner prompt very simple. It will just create a new plan from scratch.</p><pre>def strategic_planner(self, state: CodeAssistantState):<br>        logger.log_step_start(&quot;strategic_planner&quot;, &quot;Creating execution plan based on user request&quot;)<br><br>        try:<br>            user_message = state.messages[-1].content if state.messages else &quot;No message&quot;<br>            display_message = user_message[:60] + &quot;...&quot; if len(user_message) &gt; 60 else user_message<br>            logger.log_step_info(f&quot;Analyzing request: &#39;{display_message}&#39;&quot;)<br>        <br>            # Create and invoke the strategic planner chain<br>            logger.log_step_info(&quot;Generating strategic plan...&quot;)<br>            strategic_planner_chain = (<br>                self.code_assistant_chains.create_strategic_planner_chain(self.llm)<br>            )<br>        <br>            output: StrategicPlannerOutput = strategic_planner_chain.invoke(<br>                {<br>                    &quot;messages&quot;: state.messages,<br>                }<br>            )<br>        <br>            logger.log_step_success(&quot;Plan generated successfully!&quot;)<br>            logger.log_execution_plan(output.plan)<br>        <br>            # Complete the step<br>            logger.log_step_complete(&quot;strategic_planner&quot;)<br>        <br>            return {<br>                &quot;execution_plan&quot;: output.plan,<br>            }<br>        <br>        except Exception as e:<br>            print(f&quot;│  ❌ Error creating plan: {str(e)}&quot;)<br>            logger.log_step_complete(&quot;strategic_planner&quot;)<br>            raise</pre><p>Planner prompt:</p><pre>You are a decision-making AI agent responsible for intelligently planning the sequence of tools to call.<br>        Your job is to return the correct tool call sequence based on:<br>        - the user&#39;s request and prior conversation<br>        - available tools and their purposes<br><br>        ---<br><br>        ## OBJECTIVE:<br><br>        Your goal is to:<br>        1. Understand the user&#39;s request from the conversation and their intent.<br>        2. Plan from scratch.<br>        3. Return the list of tool names to be called in sequence.<br><br>        These are the tools available to you:<br>           &quot;decode_files&quot;, <br>           &quot;fetch_files&quot;, <br>           &quot;llm_call&quot;, <br>           &quot;update_file&quot;, <br>           &quot;human_approval&quot;<br><br>        ---<br><br>        Steps to plan:<br>        1. Understand clearly what user wants to do.<br>        2. If user wants to do update/edit/change/refactor/bugfix/create files, then return following sequence:<br>           [&#39;decode_files&#39;, &#39;fetch_files&#39;, &#39;llm_call&#39;, &#39;update_file&#39;, &#39;human_approval&#39;]<br>        3. If user wants to analyse/explain/understand files, then return following sequence:<br>           [&#39;decode_files&#39;, &#39;fetch_files&#39;, &#39;llm_call&#39;]<br>        4. If user wants to (1) and (2) both. then return following sequence:<br>           [&#39;decode_files&#39;, &#39;fetch_files&#39;, &#39;llm_call&#39;, &#39;update_file&#39;, &#39;human_approval&#39;]<br><br>        ## Special Cases:<br>        Non-file queries: Return [&#39;decode_files&#39;] as safety fallback<br>        Unclear intent: Return [&#39;decode_files&#39;] to begin discovery<br>        Greeting/casual: Return [&#39;decode_files&#39;] (will handle gracefully downstream)<br><br>        ## Error Recovery Patterns:<br>        Invalid context: Reset to [&quot;decode_files&quot;]<br>        Unknown user intent: Default to analysis-only workflow<br><br>        CRITICAL: Return ONLY valid tool names. Any invalid name will cause system failure.</pre><p>Now, for replanner, I just handled everything through if-else:</p><pre>def strategic_replanner(self, state: CodeAssistantState):<br>        is_ambiguous = bool(state.ambiguous_files)<br>        is_decision_taken = bool(state.decision)<br>        is_additional_query_given = bool(state.additional_query)<br>        does_llm_need_more_files = bool(state.required_files)<br>        updated_plan = []<br>        if is_ambiguous:<br>            updated_plan = insert_steps(<br>                state.execution_plan,<br>                state.current_step_index,<br>                [&quot;resolve_ambiguity&quot;, &quot;analyse_feedback&quot;],<br>            )<br>        if is_decision_taken:<br>            updated_plan = insert_steps(<br>                state.execution_plan,<br>                state.current_step_index,<br>                (<br>                        [&quot;approved_path&quot;]<br>                        if state.decision == &quot;accept&quot;<br>                        else [&quot;rejected_path&quot;]<br>                    ),<br>            )<br>        if is_additional_query_given:<br>            updated_plan = insert_steps(<br>                state.execution_plan, state.current_step_index, [&quot;decode_files&quot;]<br>            )<br>        if does_llm_need_more_files:<br>            if state.has_llm_updated_files:<br>                updated_plan = insert_steps(<br>                    state.execution_plan,<br>                    state.current_step_index,<br>                    [&quot;update_file&quot;, &quot;fetch_files&quot;, &quot;llm_call&quot;],<br>                )<br>            else:<br>                updated_plan = insert_steps(<br>                    state.execution_plan,<br>                    state.current_step_index,<br>                    [&quot;fetch_files&quot;, &quot;llm_call&quot;],<br>                )<br>        return {<br>            &quot;execution_plan&quot;: updated_plan,<br>        }</pre><p>I used the <strong>insert_steps </strong>method to add some intermediate steps in between the plan. Previously, I was discarding whole steps and asking the agent to recreate those steps, which resulted in hallucinating a lot.</p><blockquote>Hence, I understood that you don’t need to unnecessarily use LLM/agent where you don’t need it.</blockquote><p>Here, based on future use cases, I can turn replanner into an agent only when required.</p><p>3. Also, for testing purposes over other projects, I asked the end user their preferred root directory and then ran the complete code inside that root directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqO1pkkGvTEGeF0jUwTHbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5j9oIMb-eEhqy72uESwAg.png" /></figure><p>Finally, I will end this POC to focus my attention on other topics. I started this poc to</p><ul><li>Get used to Python</li><li>Learn which AI workflows are most useful internally</li><li>Understand LangGraph-based orchestration</li><li>Explore internal vs external AI tooling needs</li><li>Learn how to create an agent that plans, replans, and executes.</li></ul><p>I hope you were also able to learn a lot of new things through this article.</p><p>To stay updated on future articles, don’t forget to follow me! After following, you’ll get future articles right in your email inbox. Also, give this post <strong>50 claps 👏</strong> if you enjoyed this post and learned something useful. Your enthusiasm and support fuel my passion for sharing knowledge in the tech community.</p><p>I’ve already created various tech blogs in my leisure time. You can find more of such articles on my profile → <a href="https://medium.com/@varunkukade999">https://medium.com/@varunkukade999</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=768aafcd358b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Building My Own AI Coding Assistant in Python]]></title>
            <link>https://medium.com/@varunkukade999/i-built-my-own-ai-coding-assistant-in-python-8e9079e8b9fc?source=rss-3443b8abb2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e9079e8b9fc</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Varun Kukade]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 17:26:02 GMT</pubDate>
            <atom:updated>2025-08-19T15:00:02.892Z</atom:updated>
            <content:encoded><![CDATA[<p>The best way to learn a new language or framework? Build lots of projects and POCs! 🛠️</p><p>I’ve recently started learning Python, LangChain, and LangGraph. I’ve been going through documentation, taking courses, and building POCs and projects to learn more in-depth about these technologies.</p><p>This article demonstrates the AI code assistant project I built as part of my learning journey! 🚀</p><p>Check out my initial articles on how LangChain and LangGraph can help you build a simple, basic chatbot with agent capabilities! 🤖</p><p><strong>Part 1:</strong> <a href="https://medium.com/@varunkukade999/part-1-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-3b370bb6e7c1">https://medium.com/@varunkukade999/part-1-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-3b370bb6e7c1</a></p><p><strong>Part 2:</strong> <a href="https://medium.com/@varunkukade999/part-2-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-dc9b4cffce06">https://medium.com/@varunkukade999/part-2-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-dc9b4cffce06</a></p><p><strong>Part 3:</strong> <a href="https://medium.com/@varunkukade999/part-3-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-5d1716098b7d">https://medium.com/@varunkukade999/part-3-build-your-first-ai-agent-chatbot-with-langchain-and-langgraph-in-python-5d1716098b7d</a></p><p><strong>I’ve already covered the following basic concepts in the above 3 articles and won’t be covering those basics in this article:</strong></p><ol><li><strong>Setting up a clean Python project</strong> — What is uv, how it’s different from pip, what is a virtual environment, why we need it, and understanding <strong>pyproject.toml</strong></li><li><strong>Managing and loading API keys</strong> — How to store them securely, and an intro to Langsmith — a powerful tool to inspect and debug LLM traces</li><li><strong>Using LangChain</strong> — What are tokens, how do chatbots predict the next token, why input and output tokens matter, what are prompt templates, what is LCEL, what are runnables, and how does <strong>RunnableLambda</strong> work</li><li><strong>Using LangGraph to build smart flows</strong> — Create state, define nodes, and connect them with edges to model dynamic, multi-step reasoning</li><li><strong>Adding short-term and long-term memory</strong> by summarizing all messages</li><li><strong>Parallelism &amp; tool calling</strong></li></ol><p>Note that this will be a very comprehensive and lengthy article! I believe in providing thorough, in-depth explanations to ensure better clarity and minimal to zero doubts by the end. 📚</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sBYXtudEzI5tuicj1bTyg.webp" /></figure><h3><strong>What I built: (Everything happens in terminal, right from entering the user query)</strong></h3><p><strong>Simple Scenario 1:</strong></p><pre>messages = [HumanMessage(content=&quot;Can you analyse the code in refactor.py?&quot;)]</pre><p><strong>refactor.py</strong> is a file that exists somewhere in my complete codebase. <a href="http://github.com/altirllc/altir-ai-codegen/blob/develop/src/chains/refactor.py">Here’s</a> what it looks like.</p><p>I want the assistant to analyze that file for me and give me an analysis. Here’s what the output looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WO9FDTxyuwj5pI4j4raK4w.png" /></figure><p><strong>Scenario 2:</strong></p><pre>messages = [HumanMessage(content=&quot;Can you refactor the code in refactor.py and add tests for it?&quot;)]</pre><p>Now I want the assistant to refactor the code in <strong>refactor.py</strong> and also create tests for it.</p><p>Here’s what the output looked like:</p><p>So it refactored the <strong>refactor.py</strong> file. It also created a new file called <strong>test_refactor.py</strong> in the same directory and added tests to it.</p><p><strong>refactor.py</strong></p><pre>import os<br><br><br>def check_file_status(file_path):<br>    &quot;&quot;&quot;Check the status of a single file.&quot;&quot;&quot;<br>    with open(file_path, &#39;r&#39;) as file:<br>        content = file.read()<br>        return &#39;error&#39; if &#39;error&#39; in content else &#39;ok&#39;<br><br><br>def process_files(file_paths):<br>    &quot;&quot;&quot;Process a list of file paths and return their status.&quot;&quot;&quot;<br>    results = []<br>    for path in file_paths:<br>        if os.path.exists(path):<br>            if os.path.isdir(path):<br>                results.extend(process_directory(path))<br>            else:<br>                results.append({&#39;file&#39;: path, &#39;status&#39;: check_file_status(path)})<br>        else:<br>            results.append({&#39;file&#39;: path, &#39;status&#39;: &#39;missing&#39;})<br>    return results<br><br><br>def process_directory(directory_path):<br>    &quot;&quot;&quot;Process all files in a directory and return their status.&quot;&quot;&quot;<br>    results = []<br>    for f in os.listdir(directory_path):<br>        full_path = os.path.join(directory_path, f)<br>        if os.path.isfile(full_path):<br>            results.append({&#39;file&#39;: full_path, &#39;status&#39;: check_file_status(full_path)})<br>    return results<br><br><br>def print_summary(results):<br>    &quot;&quot;&quot;Print a summary of the file processing results.&quot;&quot;&quot;<br>    error_count = sum(1 for r in results if r[&#39;status&#39;] == &#39;error&#39;)<br>    ok_count = sum(1 for r in results if r[&#39;status&#39;] == &#39;ok&#39;)<br>    missing_count = sum(1 for r in results if r[&#39;status&#39;] == &#39;missing&#39;)<br><br>    print(&quot;Summary:&quot;)<br>    print(&quot;OK files:&quot;, ok_count)<br>    print(&quot;Files with errors:&quot;, error_count)<br>    print(&quot;Missing files:&quot;, missing_count)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    file_list = [&#39;logs/app.log&#39;, &#39;logs/debug.log&#39;, &#39;data/input.txt&#39;, &#39;missing.txt&#39;]<br>    output = process_files(file_list)<br>    print_summary(output)</pre><p>test_refactor.py</p><pre>import unittest<br>from unittest.mock import patch, mock_open<br>import refactor<br><br><br>class TestRefactor(unittest.TestCase):<br>    @patch(&#39;os.path.exists&#39;)<br>    @patch(&#39;os.path.isdir&#39;)<br>    @patch(&#39;os.listdir&#39;)<br>    @patch(&#39;builtins.open&#39;, new_callable=mock_open, read_data=&#39;This is a test file with no error.&#39;)<br>    def test_process_files_ok(self, mock_open, mock_listdir, mock_isdir, mock_exists):<br>        mock_exists.side_effect = lambda x: True<br>        mock_isdir.side_effect = lambda x: False<br>        file_paths = [&#39;file1.txt&#39;, &#39;file2.txt&#39;]<br>        expected = [<br>            {&#39;file&#39;: &#39;file1.txt&#39;, &#39;status&#39;: &#39;ok&#39;},<br>            {&#39;file&#39;: &#39;file2.txt&#39;, &#39;status&#39;: &#39;ok&#39;}<br>        ]<br>        result = refactor.process_files(file_paths)<br>        self.assertEqual(result, expected)<br><br>    @patch(&#39;os.path.exists&#39;)<br>    @patch(&#39;os.path.isdir&#39;)<br>    @patch(&#39;os.listdir&#39;)<br>    @patch(&#39;builtins.open&#39;, new_callable=mock_open, read_data=&#39;This is a test file with error.&#39;)<br>    def test_process_files_error(self, mock_open, mock_listdir, mock_isdir, mock_exists):<br>        mock_exists.side_effect = lambda x: True<br>        mock_isdir.side_effect = lambda x: False<br>        file_paths = [&#39;file1.txt&#39;, &#39;file2.txt&#39;]<br>        expected = [<br>            {&#39;file&#39;: &#39;file1.txt&#39;, &#39;status&#39;: &#39;error&#39;},<br>            {&#39;file&#39;: &#39;file2.txt&#39;, &#39;status&#39;: &#39;error&#39;}<br>        ]<br>        result = refactor.process_files(file_paths)<br>        self.assertEqual(result, expected)<br><br>    @patch(&#39;os.path.exists&#39;)<br>    def test_process_files_missing(self, mock_exists):<br>        mock_exists.side_effect = lambda x: False<br>        file_paths = [&#39;file1.txt&#39;, &#39;file2.txt&#39;]<br>        expected = [<br>            {&#39;file&#39;: &#39;file1.txt&#39;, &#39;status&#39;: &#39;missing&#39;},<br>            {&#39;file&#39;: &#39;file2.txt&#39;, &#39;status&#39;: &#39;missing&#39;}<br>        ]<br>        result = refactor.process_files(file_paths)<br>        self.assertEqual(result, expected)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    unittest.main()</pre><p>Finally, it prompted the user to either accept or reject those changes by interrupting the flow. Note that it doesn’t end the flow — it waits for user input.</p><pre>Here is the summary of changes <br> The code in `refactor.py` was refactored to improve readability and structure by extracting repeated logic into separate functions, using meaningful function names, and following Python best practices. The main behavior of the code remains unchanged.<br><br>Additionally, a new test file `test_refactor.py` was created to add unit tests for the refactored code. These tests cover various scenarios such as processing files with and without errors, handling missing files, and processing directories. The tests use the `unittest` framework and mock file operations to ensure the code behaves as expected.<br> Do you approve the output? Type &#39;accept&#39; or &#39;reject&#39;:- </pre><p>If the user types “accept”, it approves the output and does nothing. If the user types “reject”, it reverses all the changes made to existing files and also deletes the files that were created newly.</p><p><strong>Scenario 3:</strong></p><pre>messages = [HumanMessage(content=&quot;Can you add addition code inside index.py?&quot;)]</pre><p>Here, there are multiple files inside the codebase called index.py.</p><p>As soon as the assistant detects multiple paths for the same file, it prompts this and interrupts the flow.</p><pre>The following files have multiple matching paths:<br>🔸 **index.py** has multiple matches:<br>   - /Users/vkukade/Documents/AgenticAI/AICodeAssistant/models/index.py<br>   - /Users/vkukade/Documents/AgenticAI/AICodeAssistant/prompt_template/index.py<br><br>👉 Please specify the correct paths for each above file and also let me know if you have any additional queries.</pre><p>If the user replies with valid file paths, it accepts the file path and does the required changes on that confirmed file.</p><p>If the user replies with invalid file paths, it will end the flow with reason like this:</p><pre>The user&#39;s response did not provide a valid path confirmation for the file &#39;index.py&#39; as expected. Instead, the response was incomplete or unclear, making it impossible to proceed with the file analysis or editing. Therefore, the flow is being terminated.</pre><p>If user replies with valid paths and also some additional queries. Example of such reply by user:</p><pre>here is correct path: /Users/vkukade/Documents/AgenticAI/AICodeAssistant/prompt_template/index.py and can you also add subtraction function in same file?</pre><p>Here assistant accepts additional queries and also make those additional changes on top of the initial query.</p><p>At the end, it presents the summary of changes and asks for human approval:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIxOU8-j5xrMVvZKoZKNjg.png" /></figure><h4>Objective of the AI Code Assistant</h4><p><strong>Comprehensive Codebase Analysis</strong>: It should be equipped to parse and analyze an arbitrary number of files within a project.</p><p><strong>Intelligent Code Manipulation</strong>: It must support refactoring, editing, creation, and bug fixing in files. Additionally, it should support full rollback of modifications if the user chooses to reject the proposed changes.</p><p><strong>Interactive Feedback Loop: </strong>The assistant should be designed to handle human-in-the-loop feedback. In cases of ambiguity (e.g., multiple files with similar names or uncertain references) or additional queries by user, it should proactively seek clarification from the user and adapt its actions accordingly.</p><h4>Current Limitations</h4><p>At this stage AI Assistant must require the file names to analyse/edit/refactor. If file names are not provided, it will fail. It can’t figure out files to do the changes on its own just based on user query.</p><p>This is because I haven’t yet added <strong>AST (Abstract Syntax Tree)</strong> integration, which significantly impacts its contextual understanding of the codebase. Without AST:</p><ul><li>The assistant cannot construct a <strong>semantic dependency graph</strong> that maps function usage, property access, or file-level interdependencies.</li><li>As a result, it is currently unable to process complex global refactoring tasks such as: “search/rename all instances of add_numbers function across the codebase”, “Refactor the authentication flow end-to-end”</li></ul><p>Once AST-based analysis and dependency graph generation are integrated, the assistant will gain full visibility into the codebase’s structural and functional relationships. This will allow it to precisely track symbol references, understand cross-file dependencies, and perform advanced transformations with confidence and accuracy.</p><p>Here’s what the graph flowchart looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbMNurki3k6y0_ZAd28edg.png" /></figure><p>(This beautiful flowchart is created by <a href="https://www.eraser.io/ai/flowchart-generator">https://www.eraser.io/ai/flowchart-generator</a>. I just added detail description of how the flow works using natural language as input.)</p><p>To model an AI-driven code assistant, I constructed a directed graph where each node represents a task, and edges represent the flow of control based on conditions or outcomes. Explaination of all nodes and edges:</p><ol><li>Start: User provides a query</li><li>DECODE_FILES: Parses the user query and extracts file names that the user mentions to change/analyze. <br>If query is invalid -&gt; END<br>If query is valid -&gt; move to HUMAN_FEEDBACK</li><li>HUMAN_FEEDBACK: Checks if there are multiple files with the same file name.<br>If yes -&gt; ask user to resolve ambiguity via ANALYSE_FEEDBACK<br>If no -&gt; that means there is only one file with one name-&gt; directly fetch files via FETCH_FILES</li><li>ANALYSE_FEEDBACK: Ask the user to resolve ambiguity via interrupting and prompting the user, and process the human feedback.<br>If feedback is invalid -&gt; END<br>If valid feedback -&gt; proceed to fetch files via FETCH_FILES<br>If any new query was embedded in feedback along with valid files-&gt; go back to DECODE_FILES to detect the files from the query again. After DECODE_FILES flow will be same as mentioned above</li><li>FETCH_FILES: For all the detected files, fetch the original file contents from disk and pass all file data and user queries to LLM via LLM_CALL.</li><li>LLM_CALL: Call LLM with file content + query and ask to solve the user query. <br>If updates are made by LLM, go to UPDATE_FILE<br>If no changes are needed (analysis-only), end the flow</li><li>UPDATE_FILE: Write updated content of files written by LLM to disk, then move to HUMAN_APPROVAL.</li><li>HUMAN_APPROVAL: Ask user to accept or reject changes. <br>If user approves, go to APPROVED_PATH.<br>If user approves, go to REJECTED_PATH.</li><li>APPROVED_PATH: Do some actions after approving the changes and then end the flow.</li><li>REJECTED_PATH: Reverse all the changes written on disk and also delete any files if created.</li></ol><p>Now let me explain to you step by step. Before we start, here is the final <a href="https://github.com/altirllc/altir-ai-codegen/tree/develop">GitHub repo</a>.</p><p>This is how my state looks:</p><pre>from typing import Optional<br>from typing import Annotated, Optional, List<br>from langchain_core.messages.base import BaseMessage<br><br>from langgraph.graph import add_messages<br>from src.models.file import File<br>from pydantic import BaseModel<br><br><br>class CodeAssistantState(BaseModel):<br>    messages: Annotated[List[BaseMessage], add_messages]<br>    files: Optional[List[File]] = None<br>    summary: Optional[str] = None<br>    decision: Optional[str] = None<br>    is_update: Optional[bool] = None<br>    human_feedback: Optional[str] = None<br>    file_path_confirmation_prompt: Optional[str] = None</pre><p><strong>messages</strong>: stores messages exchanged between the user and the assistant.</p><p><strong>files</strong>: stores file data that we need across the flow. We store the file name, its content, whether it exists on disk or not, and its path on the disk.</p><p><strong>summary</strong>: For the LLM calls we make, summary will store the summary of those LLM calls and will be presented to the end user.</p><p><strong>decision</strong>: Whether the user accepted or rejected the changes.</p><p><strong>is_update</strong>: Whether any file update was needed for the user query.</p><p><strong>human_feedback</strong>: After we ask the user to confirm the file path for ambiguous files, we store human feedback here.</p><p><strong>file_path_confirmation_prompt</strong>: After the user confirms the file path for ambiguous files, we ask the LLM to analyze that feedback. For that, we store the prompt in this.</p><p>We start from the main.py.</p><pre>    messages = [HumanMessage(content=&quot;Can you add addition code inside index.py?&quot;)]<br>    request = {<br>        &quot;messages&quot;: messages,<br>    }<br>    config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;1&quot;, &quot;user_id&quot;: &quot;1&quot;}}<br>    sections = [<br>        &quot;decode_files&quot;,<br>        &quot;human_feedback&quot;,<br>        &quot;analyse_feedback&quot;,<br>        &quot;fetch_files&quot;,<br>        &quot;llm_call&quot;,<br>        &quot;approved_path&quot;,<br>        &quot;rejected_path&quot;,<br>    ]<br>    llm = OpenAIProvider(model_name=&quot;gpt-4o&quot;).get_llm()<br>    graph_builder = GraphBuilder(llm)<br>    graph = graph_builder.compile_graph()<br>    for chunk in graph.stream(request, config=config, stream_mode=&quot;updates&quot;):<br>        log_data(chunk, sections)</pre><p>We ask for user input, then load the LLM and graph, and finally invoke the graph with <strong>graph.stream</strong>. The <strong>graph.stream</strong> returns the chunk after execution of each node as we mentioned stream_mode=&quot;updates&quot;.</p><p>Coming from a JavaScript frontend background, I wasn’t exposed to class-based modular structure of codebases that much. But this project taught me how to systematically construct projects using OOP methodology. I’m still in the learning phase though. If you have any feedback, let me know! 🚀</p><p>This is how we load the LLM using the <strong>OpenAIProvider</strong>:</p><pre>from langchain_openai import ChatOpenAI<br>from dotenv import load_dotenv<br>from src.utils.api_key import get_api_key<br><br># Function to get API keys from the user<br>def get_api_key(env_var: str, prompt: str) -&gt; None:<br>    if not os.environ.get(env_var):<br>        os.environ[env_var] = getpass.getpass(prompt)<br><br>class OpenAIProvider:<br>     def __init__(self, model_name: str):<br>        # Load environment variables<br>        load_dotenv()<br>        self.model_name = model_name<br><br>    def get_llm(self):<br>        try:<br>            get_api_key(&quot;OPENAI_API_KEY&quot;, &quot;Enter API key for OpenAI: &quot;)<br><br>            if not self.model_name:<br>                raise ValueError(&quot;Model name is not provided&quot;)<br><br>            llm = ChatOpenAI(<br>                model=self.model_name,<br>                temperature=0,<br>                max_tokens=None,<br>                timeout=None,<br>                max_retries=2,<br>            )<br>            return llm<br>        except Exception as e:<br>            raise ValueError(f&quot;Error occurred with exception : {e}&quot;)</pre><p>The purpose of creating a separate class for every LLM provider is that users should be able to give input for the LLM provider and model of their choice, and we should be able to construct the graph based on that. We load the environment variables, and if not found, ask the user for input using <strong>getpass</strong>.</p><p>Once we have the LLM, we pass the LLM to <strong>GraphBuilder</strong> and create and compile the graph.</p><pre>from langgraph.graph import END, START, StateGraph<br>from src.states.code_assistant_state import CodeAssistantState<br>from langgraph.checkpoint.memory import InMemorySaver<br>from src.nodes.code_assistant_nodes import CodeAssistantNodes<br><br>class GraphBuilder:<br>    def __init__(self, llm):<br>        self.graph = StateGraph(CodeAssistantState)<br>        self.llm = llm<br><br>    # Function to determine next node<br>    def __should_continue(self, state: CodeAssistantState) -&gt; str:<br>        if state.is_update:<br>            return &quot;update_file&quot;<br>        return END<br><br>    def __go_to(self, state: CodeAssistantState) -&gt; str:<br>        if state.human_feedback:<br>            return &quot;analyse_feedback&quot;<br>        return &quot;fetch_files&quot;<br><br>    def build_code_assistant_graph(self):<br>        code_assistant_nodes = CodeAssistantNodes(self.llm)<br>        self.graph.add_node(&quot;decode_files&quot;, code_assistant_nodes.decode_files)<br>        self.graph.add_node(&quot;human_feedback&quot;, code_assistant_nodes.human_feedback)<br>        self.graph.add_node(&quot;analyse_feedback&quot;, code_assistant_nodes.analyse_feedback)<br>        self.graph.add_node(&quot;fetch_files&quot;, code_assistant_nodes.fetch_files)<br>        self.graph.add_node(&quot;llm_call&quot;, code_assistant_nodes.llm_call)<br>        self.graph.add_node(&quot;update_file&quot;, code_assistant_nodes.update_file)<br>        self.graph.add_node(&quot;human_approval&quot;, code_assistant_nodes.human_approval)<br>        self.graph.add_node(&quot;approved_path&quot;, code_assistant_nodes.approved_path)<br>        self.graph.add_node(&quot;rejected_path&quot;, code_assistant_nodes.rejected_path)<br><br>        # Add edges to the graph<br>        self.graph.add_edge(START, &quot;decode_files&quot;)<br><br>        self.graph.add_conditional_edges(&quot;human_feedback&quot;, self.__go_to)<br><br>        self.graph.add_edge(&quot;fetch_files&quot;, &quot;llm_call&quot;)<br>        self.graph.add_conditional_edges(<br>            &quot;llm_call&quot;,<br>            self.__should_continue,<br>        )<br>        self.graph.add_edge(&quot;update_file&quot;, &quot;human_approval&quot;)<br>        self.graph.add_edge(&quot;approved_path&quot;, END)<br>        self.graph.add_edge(&quot;rejected_path&quot;, END)<br><br>        return self.graph<br><br>    def compile_graph(self):<br>        self.build_code_assistant_graph()<br>        memory = InMemorySaver()<br>        graph = self.graph.compile(checkpointer=memory)<br>        return graph</pre><p>We added all nodes and edges for our flow.</p><p>So, to implement conditional routing, I came across the following 2 working methods:</p><ol><li>As I mentioned earlier, from the <strong>“decode_files”</strong> node, we either end the flow or go to <strong>“human_feedback”</strong>. But I haven’t predefined that edge yet while building the graph. This works fine.</li><li>Using <strong>add_conditional_edges</strong>, I create a conditional edge from <strong>“human_feedback”</strong> and <strong>“llm_call”</strong>. I do the routing based on what the current state holds. This approach also works.</li></ol><p>Inside <strong>compile_graph</strong>, I add short-term memory to the graph and compile it. Now I will systematically explain what <strong>CodeAssistantNodes</strong> does.</p><p>Let’s first start with prompts. We create a prompt using the system prompt and messages exchanged between the user and AI. When I say system prompt, it means the prompt that we give to the LLM on how it should behave for a certain query. We instruct the LLM what task it should perform for any query we send it. To make any LLM production-ready, it’s important to write clear system prompts.</p><pre>from src.prompts.decode_prompt import decode_prompt<br>from src.prompts.analyse_feedback_prompt import analyse_feedback_prompt<br>from src.prompts.analyse_update_prompt import analyse_update_prompt<br><br>class CodeAssistantPrompts:<br>    def fetch_decode_prompt(self):<br>        return decode_prompt<br><br>    def fetch_analyse_feedback_prompt(self):<br>        return analyse_feedback_prompt<br><br>    def fetch_analyse_update_prompt(self):<br>        return analyse_update_prompt</pre><p><strong>CodeAssistantPrompts </strong>implements the methods that fetch the prompts.</p><pre>from langchain_core.prompts import MessagesPlaceholder<br><br>decode_prompt = [<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;<br>            <br>        &quot;&quot;&quot;,<br>    ),<br>    MessagesPlaceholder(&quot;messages&quot;),<br>]<br><br>analyse_feedback_prompt = [<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;<br>            &quot;&quot;&quot;,<br>    ),<br>]<br><br>analyse_update_prompt = [<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;<br>            &quot;&quot;&quot;,<br>    ),<br>    MessagesPlaceholder(&quot;messages&quot;),<br>]</pre><p>Here we can also call APIs to get those system prompts through the API. For now, I’ll hardcode them locally.</p><p>Prompts are a list of tuples. <strong>MessagesPlaceholder</strong> also converts the passed messages list into the following format and makes it a tuple:</p><pre>(&quot;user&quot;, &quot;What is the capital of France?&quot;)<br>(&quot;ai&quot;, &quot;The capital of France is Paris.&quot;)</pre><p>We need 3 prompts: One for decoding the initial user input, the next one for analyzing the user feedback when we prompt them for resolving ambiguous file paths, and the last one to let the LLM update/analyze the files based on user input and provide a final summary.</p><p>We’ll fill them in later. Also, I’ve passed the message list for constructing the prompt in addition to the system prompt.</p><p>Now we’ll create the prompt template based on these prompts.</p><pre>from typing import List<br>from langchain_core.prompts import ChatPromptTemplate<br>from src.prompts.code_assistant_prompts import CodeAssistantPrompts<br><br><br>class CodeAssistantTemplates:<br>    def __init__(self):<br>        self.code_assistant_prompts = CodeAssistantPrompts()<br><br>    def __fetch_decode_prompt(self):<br>        return self.code_assistant_prompts.fetch_decode_prompt()<br><br>    def __fetch_analyse_feedback_prompt(self):<br>        return self.code_assistant_prompts.fetch_analyse_feedback_prompt()<br><br>    def __fetch_analyse_update_prompt(self):<br>        return self.code_assistant_prompts.fetch_analyse_update_prompt()<br><br>    def __create_prompt_template(self, messages: List[tuple]) -&gt; ChatPromptTemplate:<br>        return ChatPromptTemplate.from_messages(messages)<br><br>    def get_decode_prompt_template(self):<br>        decode_prompt = self.__fetch_decode_prompt()<br>        return self.__create_prompt_template(decode_prompt)<br><br>    def get_analyse_feedback_prompt_template(self):<br>        analyse_feedback_prompt = self.__fetch_analyse_feedback_prompt()<br>        return self.__create_prompt_template(analyse_feedback_prompt)<br><br>    def get_analyse_update_prompt_template(self):<br>        analyse_update_prompt = self.__fetch_analyse_update_prompt()<br>        return self.__create_prompt_template(analyse_update_prompt)</pre><p>Here, for every prompt template, first, I fetch the prompts. As mentioned, prompts are a list of tuples. Then we pass that list of tuples to <strong>ChatPromptTemplate</strong>. <strong>ChatPromptTemplate</strong> converts the list of tuples into a template of messages in a format that LLM providers accept.</p><p>Now, based on the prompt template, we create 3 chains.</p><pre>from src.models.decode_file_name import DecodeFileNameOutput<br>from src.models.analyse_human_feedback import AnalyseHumanFeedbackOutput<br>from src.models.llm_analyse_edit_output import LLMAnalyseEditOutput<br>from src.prompt_templates.code_assistant_templates import CodeAssistantTemplates<br><br><br>class CodeAssistantChains:<br>    def __init__(self, llm):<br>        self.llm = llm<br>        self.code_assistant_templates = CodeAssistantTemplates()<br><br>    def create_decode_file_name_chain(self):<br>        decode_prompt_template = (<br>            self.code_assistant_templates.get_decode_prompt_template()<br>        )<br>        return decode_prompt_template | self.llm.with_structured_output(<br>            DecodeFileNameOutput<br>        )<br><br>    def create_analyse_feedback_chain(self):<br>        analyse_feedback_prompt_template = (<br>            self.code_assistant_templates.get_analyse_feedback_prompt_template()<br>        )<br>        return analyse_feedback_prompt_template | self.llm.with_structured_output(<br>            AnalyseHumanFeedbackOutput<br>        )<br><br>    def create_analyse_update_chain(self):<br>        analyse_update_prompt_template = (<br>            self.code_assistant_templates.get_analyse_update_prompt_template()<br>        )<br>        return analyse_update_prompt_template | self.llm.with_structured_output(<br>            LLMAnalyseEditOutput<br>        )</pre><p>For every chain, we get the prompt template and chain it with the LLM. If you see, we use <strong>with_structured_output</strong> with the LLM. I’ll explain later why we used it here.</p><p>Once chains are created, we implement all the nodes inside the <strong>CodeAssistantNodes</strong> class.</p><pre>from src.states.code_assistant_state import CodeAssistantState<br>from src.chains.code_assistant_chains import CodeAssistantChains<br><br>class CodeAssistantNodes:<br>    def __init__(self, llm):<br>        self.llm = llm<br>        self.code_assistant_chains = CodeAssistantChains(llm)<br><br>    def decode_files(self, state: CodeAssistantState):<br>        print(&quot;decode_files&quot;)<br><br>    def human_feedback(self, state: CodeAssistantState):<br>        print(&quot;human_feedback&quot;)<br><br>    def analyse_feedback(self, state: CodeAssistantState):<br>        print(&quot;analyse_feedback&quot;)<br><br>    def fetch_files(self, state: CodeAssistantState):<br>        print(&quot;fetch_files&quot;)<br><br>    def llm_call(self, state: CodeAssistantState):<br>        print(&quot;llm_call&quot;)<br><br>    def update_file(self, state: CodeAssistantState):<br>        print(&quot;update_file&quot;)<br><br>    def human_approval(self, state: CodeAssistantState):<br>        print(&quot;human_approval&quot;)<br><br>    def approved_path(self, state: CodeAssistantState):<br>        print(&quot;approved_path&quot;)<br><br>    def rejected_path(self, state: CodeAssistantState):<br>        print(&quot;rejected_path&quot;)<br><br>    def update_file(self, state: CodeAssistantState):<br>        print(&quot;update_file&quot;)<br><br>    def human_approval(self, state: CodeAssistantState):<br>        print(&quot;human_approval&quot;)<br><br>    def approved_path(self, state: CodeAssistantState):<br>        print(&quot;approved_path&quot;)<br><br>    def rejected_path(self, state: CodeAssistantState):<br>        print(&quot;rejected_path&quot;)<br><br>    def rejected_path(self, state: CodeAssistantState):<br>        print(&quot;rejected_path&quot;)<br></pre><p>So if you see the initializer of the <strong>CodeAssistantNodes</strong> class, as soon as an instance of <strong>CodeAssistantNodes</strong> is created, all the chains will be set up by chaining prompt template + structured output LLM. But they aren’t invoked yet. Also, all the nodes are defined using def.</p><p>When we compile the graph from <strong>main.py</strong>, it starts creating the state graph and while creating it, it creates an instance of the <strong>CodeAssistantNodes</strong> class and attaches all the node methods to the graph.</p><p>Now, consider that everything is ready — chains, nodes, edges, etc. Now we just need to invoke them. Let’s take one example and examine the complete invocation process, including all node definitions.</p><p>Example user query:</p><pre>messages = [HumanMessage(content=&quot;Can you analyse the code inside refactor.py?&quot;)]<br>request = {<br>  &quot;messages&quot;: messages,<br>}</pre><pre>for chunk in graph.stream(request, config=config, stream_mode=&quot;updates&quot;):<br>        log_data(chunk, sections)</pre><p><strong>graph.stream</strong> streams the state data after every node execution. As soon as we call the <strong>graph.stream</strong>, it updates the state with the passed request (i.e., messages) and creates a checkpoint/backup of this state.</p><p>Now, the first node, <strong>“decode_files”</strong>, is called, and the latest updated state is passed to that first node.</p><h3>decode_files</h3><p>The goal of this node is to detect the file names the user has mentioned in the query and store them so that we can use them later in another node.</p><pre>def format_files_for_prompt(files: List[File]) -&gt; str:<br>    return &quot;\n&quot;.join(<br>        f&quot;Filename: {file.file_name}\nDoes file exist: {file.exists}\nFile Path: {file.file_path}\nFile Content:\n```python\n{file.content}\n```&quot;<br>        for file in files<br>    )<br><br>def decode_files(self, state: CodeAssistantState):<br>        if state.files:<br>            formatted_files = format_files_for_prompt(state.files)<br>        else:<br>            formatted_files = []<br>        decode_file_name_chain = (<br>            self.code_assistant_chains.create_decode_file_name_chain()<br>        )<br>        decoded_files: DecodeFileNameOutput = decode_file_name_chain.invoke(<br>            {<br>                &quot;messages&quot;: state.messages,<br>                &quot;formatted_files&quot;: formatted_files or &quot;No Existing Files Found.&quot;,<br>            }<br>        )<br>        if decoded_files.should_end:<br>            return Command(<br>                goto=&quot;__end__&quot;,<br>                update={<br>                    &quot;summary&quot;: decoded_files.summary,<br>                },<br>            )<br>        return Command(<br>            goto=&quot;human_feedback&quot;,<br>            update={<br>                &quot;files&quot;: decoded_files.files,<br>                &quot;summary&quot;: decoded_files.summary,<br>            },<br>        )</pre><ul><li>It checks if files data exists or not, and if it exists, we create formatted data for the file. Because if it exists, we’ll pass that file data to the LLM. I’ll explain why we do this later.</li><li>Then we create a <strong>decode_file_name_chain</strong> and invoke it using a list of messages exchanged between the user and the assistant and formatted files. When we invoke the chain, first, this request is passed to the prompt, and the prompt is created. Here’s how I’ve written the prompt to accept this data and also instructions to the LLM on what it should do here:</li></ul><pre>decode_prompt = [<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;<br>            User can ask to:<br>            1. Analyse/search files<br>            2. Edit/refactor/update files<br>            3. Analyse and edit both<br><br>            You will receive:<br>            1. A list of messages exchanged between the user and the assistant. <br>              These messages include the user&#39;s requests, clarifications, doubts about the code changes, edits, refactoring, or analysis.<br>            2. A list of existing files we have.<br>             <br>            Here is existing file list data:<br>            {formatted_files}<br><br>            ---<br><br>            ### Your Role<br><br>            You are a **file name extractor**.  <br>            Your task is to identify which files the user intends to **analyse**, **modify**, or **both**, based on their message requests.<br>            Based on your identification construct files list and return multiple properties.<br>            ---<br><br>            ### Dead-End Scenarios (Trigger `should_end: true`)<br><br>            1. **No file mentioned**: <br>            The user did not mention any file name they want to analyse/edit/update/etc.  <br>            ➤ Prompt the user again clearly telling them what was missing. Also mention like we only support file-level tasks and cannot perform project-level/global changes yet.  <br><br>            2. **File mentioned but no actionable intent**:<br>            Example: `&quot;Can u filename.py&quot;` - this is **unclear and insufficient**.  <br>            ➤ Clearly understand the all user queries and check if intent is missing or vague, prompt the user asking for the missing information.<br><br>            3. **Query is unrelated to file-level analysis/editing**:  <br>            Examples:  <br>            - “What is the weather today?”  <br>            - “How does ChatGPT work?”  <br>            - Other internet or general queries  <br>            Saying “Hi”, “Hello” is okay.<br>            ➤ Prompt user that their query is unrelated to file-level analysis/editing and do ask them to rephrase.<br><br>            ---<br><br>            ### Dead-End Flow:<br><br>            If any of the dead-end scenarios occur, return your output as follows:<br>                {{<br>                    &quot;files&quot;: [],<br>                    &quot;should_end&quot;: true,<br>                    &quot;summary&quot;: &quot;Reason of dead-end&quot;<br>                }}<br>            Also don&#39;t forget to return valid reason of dead-end to user in case of dead-end in `summary`.<br>            ---<br><br>            ### Non-dead-end Flow:<br><br>            If none of the dead-end scenarios happen return your output as follows:<br><br>            - Non-dead-end flow files schema:<br>                {{<br>                    &quot;files&quot;: [<br>                        {{<br>                            &quot;file_name&quot;: &quot;filename.py&quot;,<br>                            &quot;content&quot;: &quot;&quot;,<br>                            &quot;file_path&quot;: &quot;&quot;,<br>                            &quot;exists&quot;: true<br>                        }}<br>                    ],<br>                    &quot;should_end&quot;: false,<br>                    &quot;summary&quot;: &quot;&quot;<br>                }}<br>                Each object must follow this schema:<br>                - &quot;file_name&quot;: the name of the file.<br>                - &quot;content&quot;: always set this to an empty string (&quot;&quot;) — no need to generate actual file content.<br>                - &quot;exists&quot;: for now assume each file already exist and return true for all files<br>                - &quot;file_path&quot;: If user has already mentioned the file path, return it. Otherwise, return an empty string (&quot;&quot;).<br>            <br>            Notes:<br>            Existing files list data can be empty or non empty.<br>            1. If existing files list is not empty and if it contains valid files with file_name, file_path, content, exists already filled,<br>                - retain those files in the output and don&#39;t remove/change existing file name, content, path, exists and return them as it is.<br>                - don&#39;t apply &quot;Non-dead-end flow files schema&quot; to any of the existing files.<br>                - If you detect new file to add, append those to the list at the end while applying &quot;Non-dead-end flow files schema&quot;. But don&#39;t override existing list.<br>            2. If existing files list is empty, construct new files and append them to empty list while applying &quot;Non-dead-end flow files schema&quot;.<br><br>            Some rules to follow:<br>            - Include a file only if the user is asking to read, understand, analyse or modify, create, add, update, write something inside it.<br>            - If the file is being used for both reading and writing, include it.<br>            - Keep the list minimal and only with relevant file names.<br>            - If user doesn&#39;t specify file extension, assume it is a python (.py) file.<br><br>            Note: <br>            You may see valid (non-dead-end) and invalid (dead-end) queries together.<br>            In this scenario, if at least one valid query is found, you must proceed with the Non-Dead-End Flow and return `summary` for dead-end invalid queries. <br>        &quot;&quot;&quot;,<br>    ),<br>    MessagesPlaceholder(&quot;messages&quot;),<br>]</pre><p>First, I mentioned what it will receive. Then I mentioned what its role is. Then I mentioned what dead-end scenarios are, where the flow should end. Then I mentioned non-dead-end flows. Also, to cover edge cases where the user can already give file paths in the query itself, I asked the LLM to retain/use that file path.</p><h4><strong>Edge case I almost missed</strong> 🚨</h4><p>The user will come back to this node again and again due to the loop we introduced in the <strong>“analyse_feedback”</strong> node. So I created this prompt keeping in mind this loop. This was created through various trials and errors. If you can’t understand why certain instructions are written, come back to this prompt after I explain the <strong>“analyse_feedback”</strong> node. While writing system prompts, we should always refine them again and again when we introduce new conditional routes to certain nodes.</p><p>Also, I had created a chain with LLM with structured output.</p><pre>class DecodeFileNameOutput(BaseModel):<br>    files: List[File]<br>    should_end: bool<br>    summary: str<br><br>self.llm.with_structured_output(<br>            DecodeFileNameOutput<br>)</pre><p>So this instructs the LLM to return data in a fixed format. Inside the system prompt, I’ve instructed the LLM on when to send which format. For example, I ask the LLM to send “should_end” as true when it finds that the query is going to land in one of the dead-end scenarios.</p><p>Now, based on what the LLM returns, I direct my graph as follows:</p><pre>if decoded_files.should_end:<br>            return Command(<br>                goto=&quot;__end__&quot;,<br>                update={<br>                    &quot;summary&quot;: decoded_files.summary,<br>                },<br>            )<br>        return Command(<br>            goto=&quot;human_feedback&quot;,<br>            update={<br>                &quot;files&quot;: decoded_files.files,<br>                &quot;summary&quot;: decoded_files.summary,<br>            },<br>        )</pre><p>If you only want to update the state from any node, you can just return the new state dict from that node. But if you want to update both state and route together, <strong>Command</strong> helps us here.</p><p>“summary” is specifically returned by the LLM in the scenario of ending the flow. It explains to the user why the flow was terminated. Check the “Dead-End Scenarios” section in the system prompt.</p><p>That means now if the query is valid, we’ll go to the <strong>“human_feedback”</strong> node. Let’s understand it now.</p><h3>human_feedback</h3><p>The goal of this node is to detect if there are multiple files with the same name. If yes, we should ask the user to confirm which file to go with. Let’s say the user asked to update <strong>index.py</strong> and we have 2 paths with that file:</p><p>/Users/vkukade/Documents/AgenticAI/AICodeAssistant/models/<strong>index.py</strong> /Users/vkukade/Documents/AgenticAI/AICodeAssistant/prompt_template/<strong>index.py</strong></p><pre>from pathlib import Path<br>import pathspec<br>import os<br><br>project_root = Path(os.getcwd())<br><br>def get_gitignore_spec():<br>    # Generate gitignore path<br>    gitignore_path = project_root / &quot;.gitignore&quot;<br><br>    # Load gitignore rules<br>    if gitignore_path.exists():<br>        with open(gitignore_path, &quot;r&quot;) as f:<br>            lines = f.readlines()<br>            spec = pathspec.PathSpec.from_lines(&quot;gitwildmatch&quot;, lines)<br>    else:<br>        spec = pathspec.PathSpec.from_lines(&quot;gitwildmatch&quot;, [])<br>    return spec<br><br><br>def get_valid_file_paths(paths_found: List[Path]) -&gt; List[Path]:<br>    valid_paths = []<br>    spec = get_gitignore_spec()<br>    for p in paths_found:<br>        # Convert to relative path<br>        relative_path = p.relative_to(project_root).as_posix()<br>        # If the path is NOT in gitignore, keep it<br>        if not spec.match_file(relative_path):<br>            valid_paths.append(p)<br>    return valid_paths<br><br>def check_file_ambiguity(file: File) -&gt; dict:<br>    # Get all matching paths in the project<br>    paths_found = list(project_root.rglob(file.file_name))<br>    # Now filter out the paths that are in gitignore<br>    valid_paths = get_valid_file_paths(paths_found)<br><br>    # There are two scenarios here:<br>    # 1. file.file_path is None and there are multiple valid paths for certain file name. <br>    # 2. file.file_path is present, there are multiple valid paths for certain file name and file.file_path is not one of them - this means user provided file path doesn&#39;t exist/is invalid for that file.<br>    # example: Valid paths: [PosixPath(&#39;/Users/vkukade/Documents/AgenticAI/AICodeAssistant/models/index.py&#39;), PosixPath(&#39;/Users/vkukade/Documents/AgenticAI/AICodeAssistant/prompt_template/index.py&#39;)]<br>    # Wrong File path : /Users/vkukade/Documents/AgenticAI/AICodeAssistant/index.py<br>    # In this case we should inform user that your provided file path is invalid.<br>    is_ambiguous = bool(valid_paths) and len(valid_paths) &gt; 1 and file.file_path == &quot;&quot;<br>    is_ambigious_and_invalid_file_path = bool(valid_paths) and len(valid_paths) &gt; 1 and file.file_path and Path(file.file_path) not in valid_paths<br>    return {<br>        &quot;is_ambiguous&quot;: is_ambiguous,<br>        &quot;is_ambigious_and_invalid_file_path&quot;: is_ambigious_and_invalid_file_path,<br>        &quot;valid_paths&quot;: valid_paths,<br>    }</pre><p><strong>check_file_ambiguity</strong> function checks whether a file has multiple paths across the codebase. Let me explain this function in-depth.</p><p>First, it finds all matching paths using <strong>rglob</strong>.</p><p><strong>Edge case I almost missed</strong> 🚨<br> Now all matching paths will also include the file paths for the files/directories mentioned in <strong>.gitignore</strong>. Hence we should first read the user’s <strong>.gitignore</strong> file and not consider the paths which are in <strong>.gitignore</strong>.</p><p><strong>get_valid_file_paths</strong> function creates valid paths by ignoring <strong>.gitignore</strong> files. <strong>pathspec</strong> is a library which helps us with that.</p><p><strong>Git reads the .gitignore file</strong> and creates a set of <strong>rules</strong> based on its content. For every file in the project, Git checks whether the file should be tracked or ignored by comparing its path against those <strong>rules</strong>.</p><p>Similarly, the <strong>pathspec</strong> library in Python allows us to replicate this behavior. It reads the contents of a <strong>.gitignore</strong> file and builds the same kind of <strong>ignore rules</strong> as Git would. These rules are stored in a <strong>spec</strong>.</p><p>The <strong>spec</strong> provides a <strong>.match_file()</strong> function, which checks whether a given file path matches any of the ignore rules.</p><p>The “<strong>gitwildmatch</strong>” pattern is the matching style used to interpret the <strong>.gitignore</strong> rules in the same way Git does.</p><p><strong>pathspec</strong> isn’t limited to git. It creates rules for ignoring any kind of files. So in use cases like file backups, file uploads, we can filter certain files based on the rules it creates.</p><p>Then we check if the file is ambiguous if valid paths found are more than 1.</p><p><strong>Edge case I almost missed</strong> 🚨<br> What if the user provided the path for ambiguous files inside the input query itself?</p><p>We have multiple files with file name as <strong>index.py</strong> but the user provided the correct path for that file in the query itself.</p><pre>messages = [HumanMessage(content=&quot;Can you add addition code inside /Users/vkukade/Documents/AgenticAI/AICodeAssistant/prompt_templates/index.py?&quot;)]</pre><p>Now this can happen through the following scenarios:</p><ol><li><strong>“decode_files”</strong> → <strong>“human_feedback”</strong></li><li><strong>“decode_files”</strong> → <strong>“human_feedback”</strong> → <strong>“analyse_feedback”</strong> → <strong>“decode_files”</strong> → <strong>“human_feedback”</strong></li></ol><p>For this case, <strong>“decode_files”</strong> LLM will create a file object with the user-provided path as instructed in the system prompt:</p><pre>- &quot;file_path&quot;: If user has already mentioned the file path, return it. Otherwise, return an empty string (&quot;&quot;).</pre><p>But we don’t know yet if the path is valid or invalid.</p><p>So, in addition to checking ambiguity, we should also check if the user-provided path for that ambiguous file was invalid.</p><pre>def human_feedback(self, state: CodeAssistantState):<br>        # Initialize list to store ambiguous files<br>        ambiguous_files = []<br><br>        # Check for ambiguous files<br>        for file in state.files:<br>            if not file.file_name:<br>                continue<br>            result = check_file_ambiguity(file)<br>            if result.get(&quot;is_ambiguous&quot;, True) or result.get(&quot;is_ambigious_and_invalid_file_path&quot;, True):<br>                user_provided_path = (<br>                    file.file_path if result.get(&quot;is_ambigious_and_invalid_file_path&quot;, False) else None<br>                )<br>                ambiguous_files.append((file.file_name, result.get(&quot;valid_paths&quot;, []), user_provided_path))<br><br>        # If there are ambiguous files, prompt the user<br>        if ambiguous_files:<br>            file_path_confirmation_prompt = contruct_file_path_confirmation_prompt(<br>                ambiguous_files<br>            )<br>            feedback = interrupt(<br>                {&quot;question&quot;: file_path_confirmation_prompt, &quot;from&quot;: &quot;human_feedback&quot;}<br>            )<br>            return Command(<br>                update={<br>                    &quot;file_path_confirmation_prompt&quot;: file_path_confirmation_prompt,<br>                    &quot;human_feedback&quot;: feedback,<br>                    &quot;summary&quot;: &quot;\nPlease wait a moment, I am analysing your feedback...\n&quot;,<br>                }<br>            )<br>        else:<br>            return Command(<br>                update={<br>                    &quot;file_path_confirmation_prompt&quot;: None,<br>                    &quot;human_feedback&quot;: None,<br>                }<br>            )</pre><p>If we have any ambiguous files OR any ambiguous files + invalid provided path, we just create the prompt we want to show to the user using <strong>construct_file_path_confirmation_prompt</strong>:</p><pre>def contruct_file_path_confirmation_prompt(<br>    ambiguous_files: List[tuple[str, List[Path], Optional[str]]]<br>) -&gt; str:<br>    file_path_confirmation_prompt = &quot;&quot;<br><br>    for file_name, paths, user_provided_path in ambiguous_files:<br>        if user_provided_path:  # case when user provided an invalid path<br>            file_path_confirmation_prompt += (<br>                f&quot;⚠️ Your provided file path `{user_provided_path}` for file &quot;<br>                f&quot;**{file_name}** was invalid. I found possible correct paths:\n&quot;<br>            )<br>        else:<br>            file_path_confirmation_prompt += f&quot;🔸 **{file_name}** has multiple matches:\n&quot;<br><br>        for path in paths:<br>            file_path_confirmation_prompt += f&quot;   - {path}\n&quot;<br><br>        file_path_confirmation_prompt += &quot;\n&quot;<br><br>    file_path_confirmation_prompt += (<br>        &quot;👉 Please specify the correct paths for each above file and also let me know if you have any additional queries.\n&quot;<br>    )<br><br>    return file_path_confirmation_prompt</pre><p>Here’s what sample output looks like for ambiguous files:</p><pre>The following files have multiple matching paths:<br>🔸 **index.py** has multiple matches:<br>   - /Users/vkukade/Documents/AgenticAI/AICodeAssistant/models/index.py<br>   - /Users/vkukade/Documents/AgenticAI/AICodeAssistant/prompt_template/index.py<br><br>👉 Please specify the correct paths for each above file and also let me know if you have any additional queries.</pre><p>Here’s what sample output looks like for ambiguous files and the user also provided an invalid path for it:</p><pre>⚠️ Your provided file path `/Users/vkukade/Documents/AgenticAI/AICodeAssistant/prompt_templatess/` for file **index.py** was invalid. I found possible correct paths:<br>   - /Users/vkukade/Documents/AgenticAI/AICodeAssistant/index.py<br>   - /Users/vkukade/Documents/AgenticAI/AICodeAssistant/src/models/index.py<br><br>👉 Please specify the correct paths for each above file and also let me know if you have any additional queries.</pre><p>We interrupt the complete flow using the <strong>interrupt</strong> method. The concept of interrupting the flow is called <strong>Human in the Loop</strong>. We want human feedback in between without stopping the flow such that after feedback, we can resume the flow. You can check this for more info: <a href="https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/add-human-in-the-loop/">https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/add-human-in-the-loop/</a></p><p>In order to display this to the user, we have to handle it in the stream of chunks we get.</p><p><strong>main.py</strong></p><pre>from langgraph.graph.state import CompiledStateGraph<br>from src.states.code_assistant_state import CodeAssistantState<br>from langgraph.types import Command<br><br>for chunk in graph.stream(request, config=config, stream_mode=&quot;updates&quot;):<br>        log_data(chunk, sections)<br>        resume = handle_interrupt(graph, config, chunk)<br>        if resume:<br>            for chunk in graph.stream(<br>                Command(resume=resume),<br>                config=config,<br>                stream_mode=&quot;updates&quot;,<br>            ):<br>                log_data(chunk, sections)</pre><p>In stream of chunks, we get one of the chunk as follows:</p><pre>Interrupt(<br>    value={&#39;question&#39;: &#39;the question we asked&#39;, &#39;from&#39;: &#39;human_feedback&#39;}, <br>    id=&#39;a0d9dd40440ac7be2720dc5c20858627&#39;<br>)</pre><pre>def handle_interrupt(<br>    graph: CompiledStateGraph[CodeAssistantState], config: dict, chunk<br>):<br>    interrupt_response = chunk.get(&quot;__interrupt__&quot;, [])<br>    resume = None<br>    if (<br>        interrupt_response<br>        and len(interrupt_response) &gt; 0<br>        and interrupt_response[0].value<br>        and interrupt_response[0].value.get(&quot;question&quot;)<br>        and interrupt_response[0].value.get(&quot;from&quot;)<br>    ):<br>        question = interrupt_response[0].value[&quot;question&quot;]<br>        from_ = interrupt_response[0].value[&quot;from&quot;]<br>        user_input = input(question)<br>        state_history = list(graph.get_state_history(config))<br>        if from_ == &quot;human_feedback&quot;:<br>            resume = user_input.strip()<br>    return resume</pre><p>Now inside <strong>handle_interrupt</strong>, we find that chunk and if it’s present, we fetch the question and display it using “input”. This will display the question in the terminal and wait for user input. Then we create a “<strong>resume</strong>” variable which includes the user response.</p><p>Now we again invoke the graph by passing <strong>resume</strong> using <strong>Command</strong>. As soon as we do that, <strong>LangGraph</strong> invokes the <strong>“human_feedback”</strong> node again and executes it from start. But now it instantly resolves the <strong>“interrupt”</strong> with the <strong>resume</strong> value we passed.</p><pre>            feedback = interrupt(<br>                {&quot;question&quot;: file_path_confirmation_prompt, &quot;from&quot;: &quot;human_feedback&quot;}<br>            )<br>            return Command(<br>                update={<br>                    &quot;file_path_confirmation_prompt&quot;: file_path_confirmation_prompt,<br>                    &quot;human_feedback&quot;: feedback,<br>                    &quot;summary&quot;: &quot;\nPlease wait a moment, I am analysing your feedback...\n&quot;,<br>                }<br>            )</pre><p>After that, we update the state with <strong>human_feedback</strong>, <strong>file_path_confirmation_prompt</strong> and also stream summary for the user.</p><p>Note that as I said — <strong>.stream</strong> will return the latest state after each node execution and after we return something from the node. We log that summary using <strong>log_data</strong> function inside <strong>main.py</strong>.</p><pre>def log_data(chunk: dict, sections: list[str]):<br>    for section in sections:<br>        summary = chunk.get(section, {}).get(&quot;summary&quot;)<br>        if summary:<br>            print(summary)<br>            print(&quot;\n&quot;)<br><br>  sections = [<br>        &quot;decode_files&quot;,<br>        &quot;human_feedback&quot;,<br>        &quot;analyse_feedback&quot;,<br>        &quot;fetch_files&quot;,<br>        &quot;llm_call&quot;,<br>        &quot;approved_path&quot;,<br>        &quot;rejected_path&quot;,<br>    ]<br> for chunk in graph.stream(request, config=config, stream_mode=&quot;updates&quot;):<br>        log_data(chunk, sections)</pre><p>If we don’t have ambigious files, we reset the state:</p><pre>return Command(<br>                update={<br>                    &quot;file_path_confirmation_prompt&quot;: None,<br>                    &quot;human_feedback&quot;: None,<br>                }<br>            )</pre><p>Now as per this, if human_feedback is present in state, flow will go to “analyse_feedback” section or flow will go to “fetch_files”</p><pre>def __go_to(self, state: CodeAssistantState) -&gt; str:<br>        if state.human_feedback:<br>            return &quot;analyse_feedback&quot;<br>        return &quot;fetch_files&quot;<br><br>self.graph.add_conditional_edges(&quot;human_feedback&quot;, self.__go_to)</pre><p>Let’s see “analyse_feedback”.</p><h3>analyse_feedback</h3><p>The goal of this node is to ask the LLM to analyze the <strong>human_feedback</strong> the user gave in the last node and decide whether <strong>human_feedback</strong> was valid or invalid and then direct the flow accordingly.</p><pre>def analyse_feedback(self, state: CodeAssistantState):<br>        formatted_files = format_files_for_prompt(state.files)<br>        analyse_feedback_chain = (<br>            self.code_assistant_chains.create_analyse_feedback_chain()<br>        )<br>        analyse_human_feedback_output: AnalyseHumanFeedbackOutput = (<br>            analyse_feedback_chain.invoke(<br>                {<br>                    &quot;formatted_files&quot;: formatted_files,<br>                    &quot;human_feedback&quot;: state.human_feedback,<br>                    &quot;file_path_confirmation_prompt&quot;: state.file_path_confirmation_prompt,<br>                }<br>            )<br>        )<br>        if analyse_human_feedback_output.should_end:<br>            return Command(<br>                goto=&quot;__end__&quot;,<br>                update={<br>                    &quot;summary&quot;: analyse_human_feedback_output.summary,<br>                },<br>            )<br>        if analyse_human_feedback_output.additional_query:<br>            return Command(<br>                goto=&quot;decode_files&quot;,<br>                update={<br>                    &quot;files&quot;: analyse_human_feedback_output.files,<br>                    &quot;messages&quot;: [<br>                        AIMessage(<br>                            content=&quot;Do you have any other queries in addition to the above? I can process all of them simultaneously.&quot;<br>                        ),<br>                        HumanMessage(<br>                            content=analyse_human_feedback_output.additional_query<br>                        ),<br>                    ],<br>                    &quot;summary&quot;: &quot;Thanks for confirming the file paths. Now let me analyse your additional queries.&quot;,<br>                },<br>            )<br>        return Command(<br>            goto=&quot;fetch_files&quot;,<br>            update={<br>                &quot;files&quot;: analyse_human_feedback_output.files,<br>                &quot;summary&quot;: &quot;Thanks for confirming the file paths. Let me fetch those files...&quot;,<br>            },<br>        )</pre><p>We invoke the LLM using <strong>analyse_feedback_chain</strong> and pass all required things for it to analyze.</p><p>Here’s how the system prompt for this LLM looks like:</p><pre>analyse_feedback_prompt = [<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;<br>            You will receive:<br>            1. A list of files, each with its filename, whether file exists or not - boolean value, and full content. <br><br>            File Data:<br>            {formatted_files}<br><br>            User has asked to:<br>            1. Analyse files<br>            2. Edit/refactor/update files<br>            3. Analyse and edit files<br><br>            Based on user query, we already identified the files to be analysed and edited.<br>            While doing this we found that one or more file was found at different paths.<br>            Hence asked user to confirm the file paths. Here is what we prompted user:<br><br>            ### `file_path_confirmation_prompt`:<br>            {file_path_confirmation_prompt}<br><br>            Then user responded with natural language text. Here is user&#39;s response:<br><br>            ### `human_feedback`:<br>            {human_feedback}<br>             <br>            Your Role:<br>            Your task is to analyse the human feedback and return updated files.<br><br><br>            Return your output as follows:<br>            {{<br>                &quot;files&quot;: [<br>                    {{<br>                        &quot;file_name&quot;: &quot;filename.py&quot;,<br>                        &quot;content&quot;: &quot;always return empty string for now&quot;,<br>                        &quot;file_path&quot;: &quot;file path here&quot;,<br>                        &quot;exists&quot;: always return true<br>                    }}<br>                ],<br>                &quot;additional_query&quot;: &quot;Decoded additional user intent here if any&quot;,<br>                &quot;should_end&quot;: &quot;Provide true if you are ending the flow, else false&quot;,<br>                &quot;summary&quot;: &quot;Provide only if you are ending the flow&quot;<br>            }}<br><br>            ---<br><br>            ### For constructing each file object, refer to this logic:<br>            &#39;human_feedback&#39; can either contain just the confirmation of file paths as per `file_path_confirmation_prompt` <br>            Or it can also contain additional queries by user.<br>            Please note: To decide if user is providing additional file queries or not, strictly use &#39;human_feedback&#39; and not &#39;file_path_confirmation_prompt&#39;.<br><br>            <br>            Now based on &#39;human_feedback&#39; one or more of the following scenarios can occur:<br><br>            1. **Valid Path Confirmation and No Additional queries:**  <br>            Human can respond with valid file paths for the given files in natural language and no additional queries.  <br>            → Your task is to match those paths correctly to each file name.  <br>            → For each file, return an object with:<br>            - `file_name`: confirmed file name  <br>            - `file_path`: path confirmed by the user  <br>            - `content`: always return empty string for now  <br>            - `exists`: always return `true` for now  <br>            Here don&#39;t return any additional_query.<br><br>            2. **Valid Paths + Additional File Queries:**  <br>            Human can respond with valid paths as above and also mention additional file(s) in their query asking for refactor/edit/analysis.  <br>            → In this case, follow scenario 1 for the confirmed and valid paths.<br>            → Also extract additional query as a single natural language string and pass it to `additional_query`. To extract this strictly use &#39;human_feedback&#39;.<br>            - If you don&#39;t find any additional query in &#39;human_feedback&#39;, consider this as 1st (**Valid Path Confirmation and No Additional queries:**) path and don&#39;t return additional_query.<br><br>            3. **Invalid Paths:** - End the flow <br>            Human can respond with paths that are not present in the original `file_path_confirmation_prompt` or it can only contain additional queries without any valid paths. <br>            → In this case, we assume the input is invalid and terminate the flow.  <br>            → Return an empty `files` list, empty `additional_query`, and set `should_end` to `true`.<br>            - Inside `summary` provide a clear and easy to understand descriptive summary on why the flow is ending.<br>            &quot;&quot;&quot;,<br>    ),<br>]</pre><p>I gave file data to it. Then told it the scenario and gave it the confirmation prompt we asked the user and also gave it the human feedback we received. Then gave it a role to analyze feedback. Then told it various scenarios it needs to handle and return the output accordingly.</p><p><strong>Here are the scenarios I asked it to handle:</strong></p><ol><li>If user feedback didn’t contain any valid path, then end the flow.</li><li>If user feedback contained a valid path, then construct the file by appending that path.</li><li>If user feedback contained some additional query in addition to a valid path, return the additional query in <strong>“additional_query”</strong>.</li></ol><p>Here’s the structured output it should return:</p><pre><br>class AnalyseHumanFeedbackOutput(BaseModel):<br>    files: List[File]<br>    additional_query: str<br>    should_end: bool<br>    summary: str</pre><h4><strong>LLM hallucination</strong> 🧠</h4><p>If you see in the system prompt, I didn’t pass it the existing messages. Initially I had passed them. But then the LLM was hallucinating. It was considering the “initial_query” I had passed in existing messages as additional query and returning that initial query again. So the flow was going to <strong>“decode_files”</strong> but again the same query was getting decoded.</p><p>If the LLM asked to end the flow, we end it by displaying the reason.</p><pre>if analyse_human_feedback_output.should_end:<br>            return Command(<br>                goto=&quot;__end__&quot;,<br>                update={<br>                    &quot;summary&quot;: analyse_human_feedback_output.summary,<br>                },<br>            )</pre><p>If llm returned some additional query, we go back to decode files to decode that query again.</p><pre>if analyse_human_feedback_output.additional_query:<br>            return Command(<br>                goto=&quot;decode_files&quot;,<br>                update={<br>                    &quot;files&quot;: analyse_human_feedback_output.files,<br>                    &quot;messages&quot;: [<br>                        AIMessage(<br>                            content=&quot;Do you have any other queries in addition to the above? I can process all of them simultaneously.&quot;<br>                        ),<br>                        HumanMessage(<br>                            content=analyse_human_feedback_output.additional_query<br>                        ),<br>                    ],<br>                    &quot;summary&quot;: &quot;Thanks for confirming the file paths. Now let me analyse your additional queries.&quot;,<br>                },<br>            )</pre><h4><strong>LLM hallucination</strong> 🧠</h4><p>If you see, I passed an additional AIMessage in addition to the additional_query. I did this because of the following failing scenario:</p><ol><li>User asks, “Can you add addition function in <strong>test.py</strong>”. We store this in messages and pass it to the LLM at various steps.</li><li>We find that multiple <strong>test.py</strong> files exist. We ask the user to confirm the exact file. User confirmed it with additional query as “Can you add subtraction function in <strong>test.py</strong>”.</li><li>Now the <strong>“decode_files”</strong> LLM node should recognize that the user wants to add addition + subtraction in <strong>test.py</strong>. But it was hallucinating and only considering the last query “Can you add subtraction function in <strong>test.py</strong>” as the final one and only executing that further.</li></ol><p>Hence passing an additional <strong>AIMessage</strong> like <strong>“Do you have any other queries in addition to the above? I can process all of them simultaneously”</strong> gives AI the feeling that this is what I had asked the user before this and I have to process all the previous requests also.</p><p>At last, if we don’t have additional queries and also if there’s no need to end the flow, we go to <strong>“fetch_files”</strong> by updating the state with what the LLM returned back to me.</p><pre>return Command(<br>            goto=&quot;fetch_files&quot;,<br>            update={<br>                &quot;files&quot;: analyse_human_feedback_output.files,<br>                &quot;summary&quot;: &quot;Thanks for confirming the file paths. Let me fetch those files...&quot;,<br>            },<br>        )</pre><h3>fetch_files</h3><p>The goal of this node is to fetch file content from the disk.</p><pre>from typing import List<br>from src.models.file import File<br>from pathlib import Path<br>import pathspec<br>import os<br><br>project_root = Path(os.getcwd())<br><br>def fetch_files(self, state: CodeAssistantState):<br>        for file in state.files:<br>            if not file.file_name:<br>                continue<br>            if file.file_path:<br>                print(f&quot;✅ File path confirmed by user: {file.file_path}&quot;)<br>                # file path already confirmed by user<br>                resolved_path = Path(file.file_path)<br>                relative_path = resolved_path.relative_to(project_root)<br>                file.file_path = str(relative_path)<br>                file.content = resolved_path.read_text(encoding=&quot;utf-8&quot;)<br>                file.exists = True<br>            else:<br>                # either file doesn&#39;t exist or each file has only one path<br>                # Get all matching paths in the project<br>                paths_found = list(project_root.rglob(file.file_name))<br><br>                # Now filter out the paths that are in gitignore<br>                valid_paths = get_valid_file_paths(paths_found)<br>                if valid_paths:<br>                    # if valid paths found, use first match as there is only one valid path<br>                    resolved_path = valid_paths[0]<br>                    relative_path = resolved_path.relative_to(project_root)<br>                    file.file_path = str(relative_path)<br>                    file.content = resolved_path.read_text(encoding=&quot;utf-8&quot;)<br>                    file.exists = True<br>                else:<br>                    # if no valid paths found, file doesn&#39;t exist<br>                    file.file_path = &quot;&quot;<br>                    file.content = &quot;&quot;<br>                    file.exists = False<br><br>        found_files = [file.file_name for file in state.files if file.exists]<br>        missing_files = [file.file_name for file in state.files if not file.exists]<br>        summary_parts = []<br><br>        if found_files:<br>            summary_parts.append(<br>                f&quot;I found these file{len(found_files) &gt; 1 and &#39;s&#39; or &#39;&#39;} - {&#39;, &#39;.join(found_files)}.&quot;<br>            )<br><br>        if missing_files:<br>            summary_parts.append(<br>                f&quot;I couldn&#39;t find these file{len(missing_files) &gt; 1 and &#39;s&#39; or &#39;&#39;} - {&#39;, &#39;.join(missing_files)}.&quot;<br>            )<br><br>        summary = &quot;\n&quot;.join(summary_parts)<br>        return {&quot;files&quot;: state.files, &quot;summary&quot;: summary}</pre><p>So once we enter into this node, we come from two possible routes:</p><ol><li><strong>“decode_files”</strong> → <strong>“human_feedback”</strong> → <strong>“fetch_files”</strong>: In this case we don’t know the path yet. But we’re sure that if that file exists on disk, then it doesn’t have multiple paths. Only one file with that name exists on the disk. Hence here if the file exists on disk, we fetch that file content from its single path and store it in the state.</li><li><strong>“decode_files”</strong> → <strong>“human_feedback”</strong> → <strong>“analyse_feedback”</strong> → <strong>“decode_files”</strong> → <strong>“fetch_files”</strong>: In this case we already know the path as the user confirmed that path for us and we asked the LLM to update it. Hence here we fetch that file content from its confirmed path and store it in the state.</li></ol><p>Additionally, we inform the user about file existence.</p><h3>llm_call</h3><p>Goal of this node to ask llm to give us analysis / updated version of file content based on user’s query.</p><pre>def llm_call(self, state: CodeAssistantState):<br>        formatted_files = format_files_for_prompt(state.files)<br>        analyse_update_chain = self.code_assistant_chains.create_analyse_update_chain()<br>        llm_output: LLMAnalyseEditOutput = analyse_update_chain.invoke(<br>            {<br>                &quot;messages&quot;: state.messages,<br>                &quot;formatted_files&quot;: formatted_files,<br>            }<br>        )<br>        return {<br>            &quot;files&quot;: llm_output.files,<br>            &quot;summary&quot;: llm_output.summary,<br>            &quot;is_update&quot;: llm_output.is_update,<br>        }</pre><p>Here is how system prompt for this llm looks like:</p><pre>analyse_update_prompt = [<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;<br>            You are an expert Python assistant.<br><br>            You will receive:<br>            1. A list of files, each with its filename, whether file exists or not - boolean value, and full content. <br>            Content will be the existing Python code written inside the file.<br>            If file doesn&#39;t exist or is empty already, existing content will be empty.<br>            2. A list of messages exchanged between the user and the assistant. These messages include the user&#39;s requests, clarifications, doubts about the code changes, edits, refactoring, or analysis.<br><br>            File Data:<br>            {formatted_files}<br><br>            User can ask to:<br>            1. Analyse files only<br>            2. Edit/refactor/update files only<br>            3. Analyse and edit both<br><br>            Based on your understanding of the user messages and intent, take one of the above actions appropriately.<br><br>            ---------------------------------------------------<br><br>            If the user asked for code explanation/analysis only:<br><br>            You are a coding assistant that helps users understand Python code thoroughly and clearly.<br><br>            Your task is to analyze the complete code line by line, understand what it does, and generate an explanation.<br><br>            Explanation Format:<br>            1. If the user has specified a preference (e.g., high-level summary only, or in-depth explanation only), follow that exactly.<br>            2. If no preference is mentioned, use the default format below:<br><br>            Default format:<br>            - High-Level Summary (2-3 lines):  <br>            Start with a short, simple explanation of what the code is doing overall. This should be easy to understand and helpful for users who want just the gist of it.<br><br>            - Detailed Explanation (Following the high-level summary):  <br>            After the high-level summary, provide an in-depth explanation of the code.<br><br>            Follow these principles:<br>            - Use simple, beginner-friendly language.<br>            - Break down complex logic into easy steps.<br>            - Structure your explanation clearly and neatly.<br>            - Use bullet points or numbering where helpful to explain sequences or logic flow.<br>            - Use inline code formatting (`like_this`) to refer to variables, functions, or important expressions.<br>            - Explain why certain decisions were made in the code, not just what they do.<br>            - Ensure your explanation is detailed enough that the user has no follow-up questions.<br><br>            Instructions:<br>            - Do not return any modified code — only your explanation.<br>            - Check &quot;Does file exist:&quot; section for each file to decide whether file exists or not.<br>            1. If file doesn&#39;t exist - mention it clearly without explaining why it doesn&#39;t exist.<br>            2. If a file exists but is empty or has no code, mention that clearly without explaining why it is empty.<br>            - Focus on understanding and explaining — do not add, rewrite, or improve the code.<br><br>            Return your output as a dictionary with these three keys:<br>            1. files: a flat list of file objects in this format:  <br>            [<br>                {{ &quot;file_name&quot;: &quot;filename.py&quot;, &quot;content&quot;: &quot;original file content here&quot;, &quot;file_path&quot;: &quot;original file path here&quot;, &quot;exists&quot;: &quot;return original exists value as it is&quot; }}<br>            ]  <br>            (Note: File content must not be changed. Also, return original exists and file_path value as it is. Don&#39;t make any change to &quot;exists&quot; and &quot;file_path&quot; value.)<br><br>            2. summary: a string containing the complete explanation.<br><br>            3. is_update: false<br><br>            ---------------------------------------------------<br><br>            If the user asked for code edits, refactors, or bug fixes:<br><br>            You are a coding assistant that helps edit, add to, or refactor code or solve bugs based on user instructions.<br>            Your task is to pick files one by one and modify the relevant code as needed to fulfill the user&#39;s request.<br>            After code is modified for each file, return the updated file content.<br><br>            Return your output as a dictionary with three keys:<br>            1. files: a flat list of modified file objects in this format:  <br>            [<br>                {{ &quot;file_name&quot;: &quot;filename.py&quot;, &quot;content&quot;: &quot;updated file content here&quot;, &quot;exists&quot;: &quot;return original exists value as it is&quot;, &quot;file_path&quot;: &quot;return original file_path value as it is&quot; }}<br>            ]<br>            (Note: Return original exists and file_path value as it is. Don&#39;t make any change to &quot;exists&quot; and &quot;file_path&quot; value.)<br>            2. summary: a brief explanation of the changes made, OR a message explaining why no changes were necessary.<br><br>            3. is_update: true if any file was updated; false if none were changed.<br><br>            Task: Refactor the code.<br>            - Improve readability and structure.<br>            - Remove redundancy and follow Python best practices (PEP8).<br>            - Extract repeated logic into functions.<br>            - Use meaningful variable and function names.<br>            - Do not change the main behavior of the code at all.<br>            - Don&#39;t over optimize or refactor at the cost of code readability.<br><br>            Task: Fix bugs in the code.<br>            - Identify and correct logical, runtime, or syntax errors.<br>            - Preserve existing functionality unless it&#39;s clearly broken.<br>            - Make minimal, precise changes to resolve issues.<br>            - Add comments if a fix needs explanation.<br><br>            Task: Add new functionality to the code.<br>            - Implement the requested feature with clean and modular code.<br>            - Reuse existing logic where possible.<br>            - Do not break existing behavior.<br>            - Follow the structure and naming patterns of the existing code.<br><br>            Task: Write tests for the given code.<br>            - Use `unittest` or `pytest` (based on context or as instructed).<br>            - Cover key functionalities and edge cases.<br>            - Write clean, modular test functions with meaningful names.<br>            - Mock external dependencies or I/O where needed.<br>            - Do not modify the original code unless explicitly instructed.<br>            <br>            Instructions:<br>            - Maintain valid Python syntax, proper indentation, and do not alter core functionality unless explicitly asked. Never ask follow-up questions. Focus on accuracy, clarity, and correctness.<br>            - If a file needs no changes as per your reasoning, do not change anything in its content. Return it as it is.<br>            - Always use proper comments for new code that you will add. Don&#39;t add comments for existing code unless asked by user.<br>            - Always ensure to make your new code error-free. If required make use of try except. Ensure code doesn&#39;t break.<br>            - Take into consideration the corner cases, scalability, optimizations while adding new code.<br>            - Do not add code that was not explicitly asked for in the user query.<br>            - Maintain proper syntax and indentation.<br>            - Always ensure the code remains valid Python.<br>            - For now, do not ask any follow-up questions.<br>            - Check &quot;Does file exist:&quot; section for each file to decide whether file exists or not.<br>            - If file doesn&#39;t exist and you made the changes in content of it<br>              - directory_name: {{ if file_path is like &quot;filename.py&quot;, then say &quot;root directory&quot; or if file_path is like nested &quot;node1/node2/filename.py&quot;, then say &quot;node1/node2/filename.py&quot;}}<br>              - mention that clearly like &quot;I created new file ... in {{ directory_name }} and added...&quot;.<br><br>            ---------------------------------------------------<br><br>            If the user asked to both analyse and edit:<br><br>            - First, follow all steps under “If the user asked to analyze or explain code” for those files which user asked to analyse<br>            - Then, follow all steps under “If the user asked for code edits, refactors, or bug fixes” for those files which user asked to edit<br>            - Your output must be a dictionary with the following keys:<br>                1. files: a flat list of file objects in this format: <br>                [<br>                    {{ <br>                        &quot;file_name&quot;: &quot;filename.py&quot;, <br>                        &quot;content&quot;: &quot;original/updated file content here depending on whether you updated or not.&quot;, <br>                        &quot;exists&quot;: &quot;return original exists value as it is&quot;, <br>                        &quot;file_path&quot;: &quot;return original file_path value as it is&quot;  <br>                    }}<br>                ] <br>                - Do not modify content of files if the user only asked to analyze. Only edit file content when the user explicitly asks for modifications.<br>                - Return original exists value as it is. Don&#39;t make any change to &quot;exists&quot; value.<br>                - Return original file_path value as it is. Don&#39;t make any change to &quot;file_path&quot; value.<br>                2. summary: a single string containing explanation.<br>                - If only editing, follow the explanation guidelines from the edit section.<br>                - If only analyzing, follow the explanation guidelines from the analyze section.<br>                - If both:<br>                - for those files which needed editing, follow the explanation guidelines from the edit section. <br>                - For those files which needed analyzing, follow the explanation guidelines from the analyze section.<br>                3. is_update:<br>                    - false if the task only involved analysis or explanation.<br>                    - true if any file was modified.<br>                    - true if both editing and analysis were involved.<br>            &quot;&quot;&quot;,<br>    ),<br>    MessagesPlaceholder(&quot;messages&quot;),<br>]</pre><p>This system prompt is big. But it handles all the main scenarios and also the corner cases. Let me know if there’s a better way to instruct the LLM, but this prompt worked in my case.</p><p>I gave it formatted file data recently fetched and also messages exchanged till now. Then gave it a good amount of instructions on how to behave when the user just asks for code explanation/analysis vs code edits, refactors, or bug fixes. Also instructed it on how to behave if asked for both at the same time.</p><pre>class LLMAnalyseEditOutput(BaseModel):<br>    files: List[File]<br>    summary: str<br>    is_update: bool</pre><p>It will return structured output like this. It will update the file data with modified code (if any) and also the <strong>is_update</strong> value which tells us whether it did any kind of update in any of the files. We store this into state.</p><p>Now based on the <strong>is_update</strong> value, we route the flow to either the <strong>update_file</strong> node or “end”.</p><pre>def __should_continue(self, state: CodeAssistantState) -&gt; str:<br>        if state.is_update:<br>            return &quot;update_file&quot;<br>        return END<br><br>self.graph.add_conditional_edges(<br>            &quot;llm_call&quot;,<br>            self.__should_continue,<br>        )</pre><p>If it goes to end, that means user simply asked for summary/explaination of the files. It will present the summary and flow will end.</p><h3>update_file</h3><p>The goal of this node is to update the latest file content to the disk. This is the simplest.</p><pre>def update_file(self, state: CodeAssistantState):<br>        for file in state.files:<br>            # Use file_path if available, otherwise fallback to root/file_name<br>            path = (<br>                Path(file.file_path) if file.file_path else Path(&quot;.&quot;) / file.file_name<br>            )<br>            # Ensure parent directories exist<br>            path.parent.mkdir(parents=True, exist_ok=True)<br>            # Write content<br>            path.write_text(file.content, encoding=&quot;utf-8&quot;)<br>        return {<br>            &quot;files&quot;: state.files,<br>        }</pre><p>Now there can be two cases:</p><ol><li><strong>File path is not available:</strong> LLM gave us some new file with its content which didn’t exist before on the disk. Here we create a new file in the current directory and write the content into that file on disk.</li><li><strong>File path is available:</strong> LLM gave us an existing file but with modified content. Here we write the modified content by the LLM to this existing file on disk.</li></ol><h3>human_approval</h3><p>The goal of this node is to ask user to either accept or reject those changes we did in previous step.</p><pre>def human_approval(self, state: CodeAssistantState):<br>        interrupt_response: dict = interrupt(<br>            {<br>                &quot;question&quot;: f&quot;Here is the summary of changes \n {state.summary}\n Do you approve the output? Type &#39;accept&#39; or &#39;reject&#39;:- &quot;,<br>                &quot;from&quot;: &quot;human_approval&quot;,<br>            }<br>        )</pre><p>Using <strong>interrupt</strong> we again ask the user to either accept or reject the changes by showing them the complete summary of changes.</p><p>Now we need to show this question to the user. For that I need to change the streaming code.</p><p>There are two flows here:</p><ol><li>We interrupt for <strong>“human_feedback”</strong>. Then at the end we also interrupt for <strong>human_approval</strong>.</li><li>We only interrupt for <strong>human_approval</strong>.</li></ol><h4>I spent lot of time on this:</h4><p>For the first case, initially I thought I would get both “<strong>interrupt</strong>” chunks inside one stream of updates like this and I could resume execution by conditionally creating <strong>resume</strong> values:</p><pre>for chunk in graph.stream(request, config=config, stream_mode=&quot;updates&quot;):<br>        log_data(chunk, sections)<br>        resume = handle_interrupt(graph, config, chunk)<br>        if resume:<br>            graph.invoke(<br>                Command(resume=resume),<br>                config=config,<br>            )</pre><p>But it didn’t work. It only gave the chunk for the first interrupt. But then after a good amount of debugging and checking documentation, I thought let’s check the logs of the second invoke. And I got it! I came to know that the first invoke of the graph gives the first interrupt chunk and the second invoke of the graph gives the second interrupt chunk, and we have to handle them sequentially.</p><p>So the correct code is this:</p><pre>for chunk in graph.stream(request, config=config, stream_mode=&quot;updates&quot;):<br>        log_data(chunk, sections)<br>        resume = handle_interrupt(graph, config, chunk)<br>        if resume:<br>            for chunk in graph.stream(<br>                Command(resume=resume),<br>                config=config,<br>                stream_mode=&quot;updates&quot;,<br>            ):<br>                log_data(chunk, sections)<br>                resume = handle_interrupt(graph, config, chunk)<br>                if resume:<br>                    graph.invoke(<br>                        Command(resume=resume),<br>                        config=config,<br>                    )</pre><p>Here we stream two times and call same <strong>handle_interrupt</strong> flow twice.</p><p>Now here we will also modify the code of<strong> handle_interrupt</strong> a bit to create the <strong>resume</strong> value dynamically.</p><pre>def handle_interrupt(<br>    graph: CompiledStateGraph[CodeAssistantState], config: dict, chunk<br>):<br>    interrupt_response = chunk.get(&quot;__interrupt__&quot;, [])<br>    resume = None<br>    if (<br>        interrupt_response<br>        and len(interrupt_response) &gt; 0<br>        and interrupt_response[0].value<br>        and interrupt_response[0].value.get(&quot;question&quot;)<br>        and interrupt_response[0].value.get(&quot;from&quot;)<br>    ):<br>        question = interrupt_response[0].value[&quot;question&quot;]<br>        from_ = interrupt_response[0].value[&quot;from&quot;]<br>        user_input = input(question)<br>        state_history = list(graph.get_state_history(config))<br>        if from_ == &quot;human_approval&quot;:<br>            resume = {<br>                &quot;decision&quot;: user_input.strip(),<br>                &quot;state_history&quot;: state_history,<br>            }<br>        elif from_ == &quot;human_feedback&quot;:<br>            resume = user_input.strip()<br>    return resume</pre><p>I added different <strong>resume</strong> values for <strong>“human_feedback”</strong> and <strong>human_approval</strong>. I additionally send <strong>state_history</strong> in case of <strong>human_approval</strong>.</p><h4><strong>Time Travel</strong> ⏰</h4><p>Now we’ll see how to do “Time Travel” to past state. So as I said, after each state update, LangGraph maintains the copy/backup of the state in <strong>state_history</strong>. That means we can always go back and check the previous states. For each state in <strong>state_history</strong>, <strong>state.next</strong> tells us the next node in the sequence.</p><p>In our case we want this copy of state:</p><p><strong>state_before_llm_call</strong>: State before the LLM updated the file contents. We find this copy when <strong>state.next</strong> is <strong>“llm_call”</strong>. Because in <strong>“llm_call”</strong> the LLM will update the file content.</p><p>We need this copy because in case the user has rejected the file changes, we want to reverse all the changes that the LLM did. So we’ll update our state with original file content from the <strong>state_before_llm_call</strong> copy of state.</p><h4><strong>Edge case I almost missed</strong> 🚨</h4><p>There’s one scenario where we asked the LLM to refactor some file. But in the process of refactoring, the LLM can create some new files of its own for breakdown of code/any new functionality. So if the user rejects the changes, we should also delete the <strong>“newly created file”</strong> in addition to reversing <strong>existing files</strong>. But for this we should first know which new files the LLM created. Hence we’ll calculate the diff between state after LLM update and state before LLM update and figure out new files the LLM created.</p><p><strong>state_after_llm_call</strong>: State after the LLM updated file contents. We find this copy when <strong>state.next</strong> is <strong>“update_file”</strong>. Because <strong>“update_file”</strong> comes after <strong>“llm_call”</strong> and in <strong>“llm_call”</strong> the LLM will update the file content.</p><pre><br>def get_files_to_reverse(<br>    files_before_llm_update: list[File], <br>    files_after_llm_update: list[File]<br>) -&gt; list[File]:<br>    final_files: list[File] = []<br><br>    # Add all old files to final list<br><br>    final_files.extend(files_before_llm_update)<br><br>    # Create a set of (file_name, file_path) for quick lookup<br>    old_file_keys = set((f.file_name, f.file_path) for f in files_before_llm_update)<br><br>    # Check for new files<br>    for file in files_after_llm_update:<br>        key = (file.file_name, file.file_path)<br>        if key not in old_file_keys:<br>            # It&#39;s a new file, add it with empty content<br>            final_files.append(<br>                File(<br>                    file_name=file.file_name,<br>                    file_path=file.file_path,<br>                    content=&quot;&quot;,<br>                    exists=False,<br>                )<br>            )<br>    return final_files</pre><p><strong>get_files_to_reverse</strong> method gives me the final complete list of files which I need to either reverse or delete.</p><pre>def human_approval(self, state: CodeAssistantState):<br>        interrupt_response: dict = interrupt(<br>            {<br>                &quot;question&quot;: f&quot;Here is the summary of changes \n {state.summary}\n Do you approve the output? Type &#39;accept&#39; or &#39;reject&#39;:- &quot;,<br>                &quot;from&quot;: &quot;human_approval&quot;,<br>            }<br>        )<br>        decision: str = interrupt_response.get(&quot;decision&quot;, &quot;&quot;)<br>        states_history: list[StateSnapshot] = interrupt_response.get(&quot;state_history&quot;, [])<br><br>        # Get the state of graph before llm call and after update file<br>        state_before_llm_call: StateSnapshot | None = None<br>        state_after_llm_call: StateSnapshot | None = None<br>        if states_history:<br>            for each_state in states_history:<br>                if each_state.next and each_state.next[0] == &quot;llm_call&quot;:<br>                    state_before_llm_call = each_state<br>                if each_state.next and each_state.next[0] == &quot;update_file&quot;:<br>                    state_after_llm_call = each_state<br>        # Get the final list of files with their original content to reverse the changes in case of rejection<br>        files_to_reverse = get_files_to_reverse(<br>            state_before_llm_call.values[&quot;files&quot;], state_after_llm_call.values[&quot;files&quot;]<br>        )<br>        if decision == &quot;accept&quot;:<br>            return Command(goto=&quot;approved_path&quot;, update={&quot;decision&quot;: &quot;accepted&quot;})<br>        else:<br>            return Command(<br>                goto=&quot;rejected_path&quot;,<br>                update={&quot;decision&quot;: &quot;rejected&quot;, &quot;files&quot;: files_to_reverse},<br>            )</pre><p>If user accept changes, we go to approved path. Or else we go to rejected path.</p><h3>approved_path &amp; rejected_path</h3><pre>def approved_path(self, state: CodeAssistantState):<br>        return {<br>            &quot;messages&quot;: state.messages,<br>            &quot;summary&quot;: &quot;Successfully updated the files.&quot;,<br>        }</pre><pre>def rejected_path(self, state: CodeAssistantState):<br>        # reverse the files to its original state<br>        if state.files:<br>            for file in state.files:<br>                # Use file_path if available, otherwise fallback to root/file_name<br>                path = (<br>                    Path(file.file_path)<br>                    if file.file_path<br>                    else Path(&quot;.&quot;) / file.file_name<br>                )<br>                if file.exists:<br>                    # If the file exists, update it<br>                    path.parent.mkdir(parents=True, exist_ok=True)<br>                    path.write_text(file.content, encoding=&quot;utf-8&quot;)<br>                else:<br>                    # If the file was added newly, delete it now.<br>                    if path.exists() and path.is_file():<br>                        path.unlink()<br>        return {<br>            &quot;messages&quot;: state.messages,<br>            &quot;summary&quot;: &quot;Successfully reversed the changes.&quot;,<br>        }</pre><p>This is simple. In the <strong>“rejected_path”</strong>, we already have the final set of files to update our state to. We just traverse files and if the file exists on disk before, we update its content to our new content inside disk. If the file didn’t exist, we just delete that file from disk.</p><p>After this, the flow ends.</p><p>Edit: I transformed this guided flow into an autonomous AI agent that plans, executes, learns from mistakes, and revises its strategy. Check out the writeup: <a href="https://medium.com/@varunkukade999/turning-a-coding-assistant-into-a-cost-effective-autonomous-ai-agent-768aafcd358b">https://medium.com/@varunkukade999/turning-a-coding-assistant-into-a-cost-effective-autonomous-ai-agent-768aafcd358b</a></p><p>That’s it! We completed the AI Code assistant. Of course, there’s a lot to add here or make optimizations. I may create new articles and explain that also. Also, let me know if you want me to make an article on a specific topic you have in mind.</p><p>To stay updated on future articles, don’t forget to follow me! After following, you’ll get new articles right in your email inbox. Also, give this post <strong>50 claps 👏</strong> if you enjoyed this post and found it helpful. Your enthusiasm and support fuel my passion for sharing knowledge in the tech community.</p><p>I’ve already created various tech blogs in my leisure time. You can find more of such articles on my profile → <a href="https://medium.com/@varunkukade999">https://medium.com/@varunkukade999</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e9079e8b9fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>