Cross-Device Remote Execution for AI Coding Agents: Architecture and Practice
How to design an AI coding agent system where the mobile device acts as a control plane for initiating, approving, and tracking tasks, while the desktop environment serves as the execution plane for real code, commands, and workspace changes. This article covers the overall architecture, persistent session design, sandboxing and tool integration, approval workflows, observability, common anti-patterns, and a phased rollout checklist.
Cross-Device Remote Execution for AI Coding Agents: Architecture and Practice
Background: Mobile for Command, Desktop for Execution
In a traditional development workflow, developers sit at a fixed workstation with an editor, terminal, browser, and log panels open so that an AI coding agent can read code, run tests, fix issues, or call external services. As agent capabilities grow, a workflow better aligned with real-world usage is emerging: the mobile device no longer performs computation. Instead, it becomes the entry point for initiating, approving, tracking, and confirming tasks. Tasks that actually need access to local files, command execution, and workspace changes are still handled by a desktop execution environment with a full development setup.
The core idea of this architecture is not “mirroring the desktop to the phone” or “running a full coding agent on the phone.” Rather, the system is split into two planes:
- Control plane: runs on the mobile device, handling authentication, task description, permission confirmation, progress monitoring, result review, interruption, and audit queries.
- Execution plane: runs on the developer’s desktop or a managed workspace, handling file read/write, code analysis, command execution, tool invocation, artifact generation, and diff reporting.
The two planes are linked by a persistent session. After a user initiates a task on the mobile device, the execution side continues working within the session context. Even if the phone goes briefly offline, switches networks, or the app is backgrounded, the user can restore the full task thread via session cursors upon return. This approach leverages real code, configuration, dependencies, and credentials that exist in the desktop environment, while avoiding the transfer of high-compute, high-privilege local operations to the phone.
The value of this model is threefold:
- Lower interruption cost: Developers can initiate low-risk tasks, approve critical steps, and check stage results even after leaving their workstation.
- Context continuity: Tasks are not one-shot question-answer exchanges but sustainable threads with state, events, and artifacts.
- Stronger permission boundaries: The phone only sends intent and confirmation, never holding full local execution privileges. Sensitive operations are governed by sandboxing and approval policies on the execution side.
Overall Architecture: Decoupling Control and Execution
A reasonably complete cross-device remote execution system typically includes a mobile console, access gateway, session and task service, event bus, execution agent, tool gateway, and audit/artifact storage. A schematic structure looks like this:
[Mobile Console]|v[Access Gateway] <--> [Session & Task Service] <--> [Event/Message Bus]| |v v[Audit & Artifact Store] [Workspace Execution Agent]|+---------+----------+| |[Sandbox Environment] [Tool Connectors]| |[Local Code/Commands] [External Services]
Responsibilities should be clearly defined:
- Mobile Console: Provides task creation, session restoration, risk alerts, approval buttons, diff summaries, artifact download, and interruption controls. It stores no long-lived high-privilege credentials and performs no model inference or local command execution.
- Access Gateway: Handles device pairing, identity verification, transport encryption, rate limiting, and session routing. Mobile networks are unstable, so the gateway must support reconnection and event compensation.
- Session & Task Service: Maintains session metadata, task state machines, event sequences, approval records, and idempotency keys. It should be the single trusted entry point for control logic.
- Event & Message Bus: Asynchronously delivers control commands, execution events, heartbeats, and result notifications. Critical events must be persisted, not dependent on transient push.
- Workspace Execution Agent: Runs in a managed desktop environment, receiving tasks, negotiating capabilities, invoking local tools, executing commands, and returning structured events. It must support sandbox isolation, least privilege, and abortable execution.
- Tool Connectors: Wrap files, commands, repositories, messaging, email, cloud storage, ticketing systems, and other capabilities into controlled tools. Each tool must declare required permissions, risk levels, and audit fields.
- Audit & Artifact Store: Records who performed what operation, when, from which device, and through which session—including which files were read, which commands were run, and which artifacts were produced.
The key architectural principle here is: separation of control and execution, event-driven design, durability and recoverability, least privilege, and end-to-end auditability. Skip these principles, and the system easily degrades into a high-risk tool with a remote command entry point.
Core Workflow: From Task Initiation to Result Confirmation
Cross-device remote execution is not a simple request-response chain but a multi-stage, stateful event flow. A workable process:
- Device pairing and identity establishment: The user initiates device pairing on the mobile side; the execution side generates a one-time pairing code or confirmation event, establishing a device binding. Bindings should be revocable at any time and support display of device name, last active time, and trust status.
- Create a persistent session: The mobile side creates a session bound to a target workspace. Session context includes user, device, workspace, permission scope, and task subject. Sessions can persist across tasks, but each task should have its own identifier.
- Describe intent and generate a plan: The user describes the goal in natural language or via a structured form—for example, “analyze why tests are failing and suggest fixes.” The execution agent reads the necessary context, generates a task plan, and flags the files, commands, and external tools it may need to access.
- Capability negotiation and risk classification: The execution agent reports required capabilities back to the control plane—read-only file access, file writes, test runs, external service calls, etc. The system classifies operations into risk tiers: read-only, writable, command execution, and external side effects.
- Human approval: Operations such as writing files, running destructive commands, accessing sensitive files, or sending external messages may require explicit confirmation per policy. The approval UI should show the blast radius, intended actions, rollback options, and artifact locations.
- Execution and event reporting: Once approved, the execution side runs the task in a sandbox, continuously reporting stage status, key log summaries, change overviews, and anomaly events. The mobile side should not be flooded with raw logs; it should show structured summaries and traceable artifacts.
- Result summary and diff review: After completion, the system reports change summaries, test results, risk items, pending confirmations, and downloadable artifacts. Users can do coarse-grained review on mobile and fine-grained edits and final verification on desktop.
- Completion, rollback, and audit archival: On completion, failure, or cancellation, the state machine enters a terminal state. Rollback is triggered if needed, and audit records plus key artifacts are archived per retention policy.
A simplified state machine describes the task lifecycle:
created -> authorized -> planned -> awaiting_approval -> running -> completed| | | | |cancelled expired failed rejected timed_out
The state machine should avoid “implicit transitions.” Every state change must have an event record, operator, timestamp, and reason. Otherwise, once an unauthorized or accidental operation occurs, reconstructing what happened becomes very difficult.
Persistent Session Design: Unstable Networks Must Not Lose Context
The persistent session is the core of the cross-device experience. It is not just “chat history” but the combination of task context, event sequences, execution state, and permission decisions. A production-grade session system must address at least the following.
1. Event Sequences and Cursor-Based Recovery
Every time the mobile side pulls or receives events, it should carry the last confirmed event cursor. The server returns missing events by monotonically increasing sequence number. This way, even if the mobile client goes offline, reconnects, or restarts, the full session can be restored—rather than showing only the last message.
{"session_id": "s-97f3","task_id": "t-1024","device_id": "d-42","intent": "Run tests and suggest fixes","capabilities": ["file.read:workspace/src", "process.run:test"],"approval_policy": "write_and_command_requires_confirmation","status": "awaiting_approval","seq": 18}
2. Idempotency and Deduplication
On mobile networks, users may tap “Approve” or “Cancel” repeatedly, and messages may be delivered more than once. All control commands should carry idempotency keys, with the server deduplicating by task and action. On the execution side, command execution must also use task identifiers to prevent duplicate runs from causing side effects.
3. Backpressure and Summarization
The execution side can generate huge volumes of logs. Pushing all of them to the mobile client wastes bandwidth and hurts readability. The better approach: store raw logs and artifacts in controlled storage, and have the mobile client receive only stage status, error summaries, risk alerts, and artifact references. Users can pull detailed content on demand.
4. Heartbeats, Timeouts, and Checkpoints
The execution side should send heartbeats periodically so the task service can determine whether the workspace is online. Long tasks need segmentation with recorded checkpoints. A lost connection does not mean a failed task—the system should support resumption, cancellation, or safe termination after a timeout.
5. Multi-Task Queuing and Isolation
Multiple tasks may run concurrently in the same workspace. The system needs a concurrency policy: read-only analysis tasks can run in parallel, while write and command-execution tasks should be serialized or locked by default to avoid conflicts from simultaneous edits to the same file. Every task should be bound to an explicit workspace snapshot or change baseline.
Execution-Side Design: Local Capabilities Must Be “Tooled” and “Sandboxed”
The execution side carries the highest risk in the entire system. It can access local files, run commands, and connect to external services, so “arbitrary command execution” must not be exposed directly to the control plane. A safer design wraps local capabilities into controlled tools with multiple layers of restriction.
1. Capability Declaration and Minimum Authorization
Each tool should provide a capability manifest, for example:
{"tool": "workspace_file","actions": ["read", "list", "write"],"risk": "medium","constraints": ["path_prefix_allowlist","secret_file_denylist","write_requires_approval"]}
File access should be based on path allowlists, excluding key files, credential directories, and sensitive configuration. Command execution should not expose a full command line; instead, offer wrapped task templates for tests, builds, formatting, and static analysis. If custom commands are truly needed, combine them with risk classification and explicit approval.
2. Sandboxing and Resource Limits
The execution environment should use a lightweight sandbox, container, or managed virtual environment, restricting at minimum:
- Accessible file paths and mount scopes;
- The set of executable commands and parameter constraints;
- Network egress—for example, deny unknown external addresses by default;
- CPU, memory, execution duration, and output size;
- Concurrency and task queue length;
- Writable directories and rollback-capable snapshots.
Sandboxes are not a panacea, but they significantly reduce the blast radius of mistakes. For tasks that modify the workspace, create a change snapshot or reversible patch before execution.
3. Tiered Approvals
Approval policy should not be binary “allow all / deny all.” Design multi-tier policies by risk:
- Read-only analysis: allow reading and summarizing within restricted paths, with notification at most.
- Generate patches without applying: allow generating diffs; apply only after user confirmation.
- Writing to the workspace: require explicit approval by default, showing the list of affected files.
- Command execution: classify by command-template risk—test and check commands may be auto-approved, destructive operations require human confirmation.
- External side effects: sending messages, filing tickets, uploading artifacts must show the target and content summary.
Approval UIs should let users make an “informed confirmation” rather than just clicking “I agree.” For example, show changed files, key diffs, estimated impact, rollback options, and failure handling.
4. Cancellation and Emergency Stop
The system must support task-level cancellation and device-level emergency stop. Cancellation signals should reach the execution side as quickly as possible; the execution agent must check cancellation flags and terminate child processes or roll back incomplete writes. For high-privilege tools, also provide one-click device de-authorization and temporary credential cleanup.
Tool Integration: Bringing External Capabilities into a Unified Permission Model
AI coding agents typically connect to many capabilities: repositories, file systems, command lines, log systems, messaging, email, cloud storage, ticketing, and more. A cross-device remote execution system should not let each connector implement its own permission logic; instead, all capabilities should go through a unified tool gateway and permission model.
Recommended practices:
- Unified capability descriptions: Each connector declares available actions, inputs/outputs, risk levels, required credentials, and audit fields.
- Per-task authorization: Users approve a capability for a specific task within a time window—not a permanently open account permission.
- Credential isolation: Mobile devices never touch long-lived credentials; the execution side accesses external services via short-lived tokens or a proxy gateway.
- Content minimization: Content returned to the mobile client should be summarized and redacted, avoiding leakage of full logs, keys, or personal information.
- Revocability and traceability: External calls should record the caller, task, target, parameter summary, and result status, supporting post-hoc audit and revocation.
Note: the more tool capabilities you expose, the more you need default-deny and explicit enablement. Designing “callable” as the exception rather than the default state is key to reducing privilege-escalation risk.
Observability and Audit: Making Every Execution Explainable
Without observability, a cross-device execution system struggles to diagnose failures, assign responsibility, and improve the experience. Three capabilities should be built at minimum.
1. Metrics and Alerting
- Task success, failure, and cancellation rates;
- Average queue time from initiation to execution;
- Approval wait times and distribution of rejection reasons;
- Mobile reconnection rate and event delivery latency;
- Execution-side heartbeat loss rate and task timeout rate;
- Tool invocation failure rate and count of high-risk operations.
2. Distributed Tracing
Record correlation identifiers for every user request, task, command, and tool call, forming a complete trace from mobile initiation to execution completion. That way, when problems like “approved but not executed,” “completed but not reported back,” or “missing logs” occur, the responsible stage can be quickly pinpointed.
3. Audit Logs
Audit logs should cover device binding, authentication, session creation, capability negotiation, approval decisions, command execution, file modifications, external calls, cancellations, rollbacks, and authorization revocations. Logs should be tamper-proof or tamper-evident, and queryable by user, device, workspace, and time range.
Mobile Experience: Don’t Shove a Terminal Onto a Phone
The mobile’s strengths are immediacy and confirmation, not long, detailed editing sessions. Product design should avoid two pitfalls: cramming a full terminal and raw logs onto a small screen, or showing only “task completed” with no way for the user to judge risk.
A more sensible mobile information structure includes:
- Task stage: planned, awaiting approval, running, completed, failed;
- Impact summary: which files, commands, and external operations are involved;
- Key risks: whether writes are needed, whether sensitive resources are accessed, whether rollback is possible;
- Review entries: diff summaries, test results, artifact lists, and references to detailed logs;
- Actions: approve, reject, cancel, handle later;
- Recovery: after reconnection, restore the full thread via cursors.
For complex changes, the mobile side can perform “directional approval,” with final application and verification done on the desktop execution side. This division of labor fits real workflows better than reluctantly editing large amounts of code on a phone—and is safer.
Common Anti-Patterns and How to Fix Them
Turning remote control into a bare command channel
Offering only a “send command, get output” API makes permissions, approvals, and audit meaningless. Use controlled tools and task templates instead.Storing long-lived high-privilege credentials on mobile
Mobile devices can be lost or stolen. The control side should use short-lived sessions, device binding, and revocable authorization; long-lived credentials stay on the managed execution side.Ignoring idempotency and duplicate execution
Repeated approval taps, message redelivery, and network retries can all cause a command to run twice. All writes and command executions need idempotency keys and deduplication.Pushing raw logs directly to mobile
This wastes bandwidth and risks leaking sensitive information. Use structured summaries, redaction, and on-demand retrieval.No rollback path
Any task that modifies the workspace should provide a change preview, snapshot, or patch rollback. High-risk operations that cannot be rolled back should require a higher approval level.No heartbeats or timeouts on the execution side
Users end up in limbo, unsure whether a task is actually running. Heartbeats, timeouts, cancellation, and checkpoint recovery should be baseline capabilities.
Rollout Roadmap and Checklist
For phased implementation, proceed in this order:
Phase 1: Device pairing and persistent sessions
Device binding, session restoration, event cursors, basic notifications, and task status display.Phase 2: Read-only capabilities and safe execution
Restricted file reading, code summaries, test result analysis, and other low-risk capabilities; establish path allowlists and output redaction.Phase 3: Approvals and controlled writes
Capability negotiation, risk classification, diff previews, explicit approvals, and snapshot rollback.Phase 4: Tool gateway and audit system
Unified tool descriptions, per-task authorization, short-lived credentials, end-to-end tracing, and audit queries.Phase 5: Multi-task scheduling and operations
Queuing, concurrency control, quotas, alerting, gradual rollout, and emergency stop.
Before launch, check each item:
- Are the control plane and execution plane clearly separated?
- Does the mobile side handle only control and confirmation, not heavy computation?
- Do sessions support offline recovery and event replay?
- Do all control commands carry idempotency keys?
- Does the execution side have sandboxing, file allowlists, and resource limits?
- Are writes, commands, and external side effects governed by approval policies?
- Are task cancellation, device revocation, and emergency stop available?
- Are complete audit logs recorded and traceable?
- Does the mobile side show risk summaries rather than floods of raw logs?
- Do long tasks have timeouts, heartbeats, checkpoints, and rollback?
Conclusion
Using the mobile device as the “remote control” for AI coding agents essentially splits the AI execution chain into a movable control plane and an execution plane with a full environment and privileges. It delivers a more continuous working experience, while pushing permission governance, state synchronization, sandbox isolation, and auditability to the architectural center. A reliable cross-device remote execution system should not aim to expose desktop capabilities indiscriminately on the phone; it should be designed around persistent sessions, controlled tools, least privilege, human approval, and end-to-end observability. Only then can mobile convenience come without sacrificing security and controllability.
