Design and Prototype for Cross-Device Remote Access to AI Coding Sessions

    This article presents a design and prototype for accessing an AI coding session from multiple devices, covering network reachability, state consistency, security boundaries, P2P connection with relay fallback, end-to-end encryption, approval workflows, and a test checklist. It defines the roles of host, client, and coordinator, introduces session view data structures, and explains how to handle out-of-order events, duplicate commands, and approval conflicts. The design is intended for prototyping and remote access layer only, not production deployment or AI model internals.

    1. What Problems Does Cross-Device Remote Access to AI Coding Sessions Solve?

    AI coding assistants have evolved from single-turn Q&A to long-running tasks that can read and write code, execute commands, and wait for human confirmation. A common developer scenario: start a task on a desktop in the office, then check progress, add instructions, or approve sensitive operations from a phone while away, and if needed, take over on another computer. This can be summarized as “one session, multiple terminals.”

    Achieving this goal involves three categories of typical problems.

    First, network reachability. Development machines are usually behind intranets or home broadband, without public IP addresses. NAT types vary across ISPs and enterprise networks. Direct connections will fail in a significant portion of network environments, so the solution must provide a reliable fallback path.

    Second, state consistency. The same session may be viewed and operated on by multiple clients simultaneously. If each client maintains its own state independently, issues such as message reordering, duplicate command submission, and inconsistent approval results will arise.

    Third, security boundaries. Remote endpoints can trigger file modifications and command execution. Any channel that is intercepted or impersonated effectively grants full control of the development machine. Therefore, encryption, identity verification, and permission control must be incorporated from the initial design.

    After reading this article, you will gain:

    • The responsibilities and trust boundaries of the host, client, and coordinator.
    • The data structure of session views and rules for handling out-of-order and duplicate events across multiple endpoints.
    • The complete flow of P2P direct connection and relay fallback, mapped to ICE, STUN, and TURN concepts.
    • Methods for end-to-end encrypted key exchange, encrypted transmission, and replay protection.
    • A state machine for approval requests and the recovery process after disconnection.
    • A test checklist for validating the prototype.

    This document is a prototype design description, not a production-grade implementation guide. The illustrative code is simplified to explain the logic and is not ready for deployment. It only covers the remote access layer and does not address AI model inference or training.

    2. Overall Architecture and Trust Boundaries

    The system can be split into three roles.

    • Host: The machine that runs the actual session, executing tasks and producing an event stream. The host is the single source of truth and the root of trust.
    • Client: Desktop, mobile, or web interface that displays content and sends commands.
    • Coordinator: Handles device discovery, signaling exchange, and relay allocation.
    1. [Client] --- signaling ---> [Coordinator] <--- signaling --- [Host]
    2. | |
    3. +------ P2P direct (preferred, end-to-end encrypted) ----+
    4. | |
    5. +------ relay forwarding (fallback, still ciphertext) ---+

    The visibility of the coordinator and relay nodes must be clarified separately. The coordinator knows device IDs, device public keys, network addresses, and communication timestamps, but does not store session content. Relay nodes can see the network addresses of both connected parties, packet sizes, and send/receive timestamps, but only see ciphertext and cannot decrypt. Therefore, “only forwarding ciphertext” describes content confidentiality, but does not guarantee metadata invisibility.

    To control this risk, the system should implement the following:

    • Relay authentication: The coordinator issues short-lived tokens for each connection, bound to device ID, session ID, and expiration time, typically valid for a few minutes. Relay nodes verify the token before forwarding data.
    • Metadata minimization: Session identifiers in the coordinator use hashed temporary IDs, not project names, paths, or user nicknames.
    • Clear trust boundaries: Only public keys confirmed during pairing are considered trusted identities. Even if the coordinator is compromised, it cannot impersonate the host during pairing.

    3. Session View Mapping and Multi-Device Consistency

    The same session is mapped to a “session view” at the remote access layer. The view contains only the index, status, and events needed for display, without copying the full workspace content.

    This approach offers three benefits. First, the data source remains single; the source workspace is still the only source of truth. Second, the remote layer does not persist data, reducing the exposure of sensitive information. Third, closing remote access only revokes the view; the original session history remains unaffected.

    The session view fields are described below. The field names are illustrative and used to convey design intent.

    Field Meaning Correspondence in a real implementation
    session_id Unique identifier of the source session Primary key of the host session manager
    workspace_ref Workspace reference, not file content Hash or alias of the workspace path
    status idle, running, awaiting_approval, stopped Session runtime status enumeration
    last_seq Latest event sequence number applied in order Cursor stored locally by the client
    pending_approvals List of pending approval requests Snapshot of the host approval queue
    buffer Temporarily stored out-of-order events In-memory queue on the client

    Event sequence numbers are assigned uniformly by the host. All clients apply events according to the host-assigned sequence, so there is no contention among multiple writers. The following code handles duplicates, out-of-order events, and approval conflicts.

    1. function apply_event(view, event):
    2. if event.session_id != view.session_id:
    3. return view
    4. if event.seq <= view.last_seq:
    5. return view // duplicate or stale event, discard
    6. if event.seq > view.last_seq + 1:
    7. view.buffer[event.seq] = event // gap detected, buffer for now
    8. return view
    9. commit(view, event)
    10. while (view.last_seq + 1) in view.buffer:
    11. commit(view, view.buffer.remove(view.last_seq + 1))
    12. return view
    13. function commit(view, event):
    14. view.last_seq = event.seq
    15. view.status = event.status or view.status
    16. if event.type == "approval_update":
    17. merge_approval(view, event.approval)
    18. function merge_approval(view, approval):
    19. local = view.pending_approvals[approval.id]
    20. if local is null or approval.version > local.version:
    21. view.pending_approvals[approval.id] = approval // higher version wins

    When multiple clients are concurrent, the following rules must be respected:

    • Host processes commands serially: Commands from all clients enter the same queue on the host, are executed in arrival order, and receive new sequence numbers.
    • Commands are idempotent: Each command carries a client_cmd_id. The host keeps a deduplication record for a recent time window. Duplicate commands return the result of the first execution without being executed again.
    • Approval conflicts are resolved by first come, first served: If two devices approve or reject the same request simultaneously, the host accepts only the first decision. Later requests receive an already_decided response along with the final status.

    4. P2P-First Connection Strategy

    The success rate of P2P direct connection depends on the NAT types and firewall policies of both ends. A practical connection flow can be mapped directly to the four phases of the ICE framework.

    1. Candidate Gathering: Collect local network interface addresses (host candidates), public-mapped addresses obtained through STUN servers (server reflexive candidates), and relay addresses allocated via TURN servers (relayed candidates).
    2. Candidate Exchange (Signaling): The client and host exchange candidate lists through the coordinator. Each list is signed with the device’s long-term identity private key; the receiver verifies the signature using the public key saved during pairing. This prevents the coordinator from injecting forged candidate addresses even if compromised.
    3. Connectivity Checks: Probe candidate address pairs concurrently by priority, selecting the lowest-latency available direct path as the current path.
    4. Fallback Decision: If no direct path succeeds within a defined time limit, switch to a TURN relay.

    Timeout parameters should be set in layers. The following ranges are starting points and need to be measured and adjusted in target networks.

    • Single candidate pair check timeout: approximately 500 ms to 2 seconds.
    • Overall direct-connection attempt limit: approximately 5 to 10 seconds. After exceeding this, fall back to relay immediately to avoid long user waits.
    • Path upgrade stability period: once a direct connection is restored, it must succeed continuously for a certain number of times and duration before switching back, to prevent path flapping.

    For testing, statistics should be reported in the following metrics, grouped by network type, such as home broadband, enterprise network, and mobile cellular (often behind CGNAT).

    • Direct connection success rate: ratio of sessions that establish a direct connection to total sessions.
    • Connection establishment time: from initiation to the ability to send/receive events; report median and p95.
    • Fallback time: from the detection of direct connection failure to the availability of the relay.
    • Relay ratio: share of sessions transmitted through a relay; this directly impacts service cost.

    The connection state can be modeled as a finite state machine with at least four states: connecting, direct, relayed, and disconnected. Legal transitions include: connecting to direct or relayed; direct to relayed (direct interruption); relayed to direct (path upgrade); any state to disconnected. Each transition should log an entry without sensitive information for troubleshooting.

    Common issues and debugging methods:

    Symptom Common cause Debugging approach
    Direct connection always fails Symmetric NAT or UDP blocked by enterprise firewall Inspect candidate type distribution; confirm whether only relayed candidates exist
    Relay latency is high TURN node too far or bandwidth constrained Select TURN nodes by region; record RTT for each relay
    Path upgrade flapping Direct line quality fluctuates near threshold Increase stability period and hysteresis threshold; count per-minute transitions
    Candidate signature verification fails Pairing public key mismatch or signature Recheck the stored public key and regenerate the candidate list