Desktop Coding Tools in Practice: Bridging the Stateful Responses API and Stateless Chat Completions API

    This article examines desktop coding assistants and explains how to connect them to cloud model services through a local protocol bridge. It covers the user experience of desktop clients, the differences between stateful Responses APIs and stateless Chat Completions APIs, and the practical steps for implementing session-state mapping, request conversion, streaming transformation, deployment, configuration, and operational risk control.

    1. Background: From a Coding Assistant on the Desktop

    Developers working in terminals are already familiar with command-line coding assistants. Such tools can understand repository structure, retrieve relevant code, propose modifications, and, after user confirmation, write files or run tests. These tools have mostly existed as command-line utilities.

    Recently, several mainstream coding tools have introduced desktop clients. Application notifications, graphical change review and history, and more intuitive configuration screens make it possible to use AI coding assistants like an IDE. As a result, announcements of desktop releases have generated substantial discussion.

    Whether a tool runs in a terminal or on a desktop, however, real-world effectiveness still depends on three questions:

    1. Whether it can reliably connect to an appropriate model service.
    2. Whether the tool-calling workflow is smooth.
    3. Whether long-context scenarios are reliable.

    A common way to evaluate such tools is to configure them locally and connect them to a cloud provider’s coding package or model service. These services usually offer ready-made integration methods for mainstream coding tools, but the process is not always smooth.

    A typical blocker appears when combining a new version of a tool with a cloud service:

    • New tool: It supports only the newer stateful Responses API, in which the service stores conversation state.
    • Cloud service: It provides only a stateless Chat Completions API, so every request must include the full conversation history.
    • Platform documentation: The official documentation may state that the stateful Responses API used by the new tool is not yet supported.

    The root cause is that although both the Responses API and the Chat Completions API accept a conversation and return output, they differ significantly in request structure, streaming event format, and tool-calling mechanics. Simply changing the URL or model name is not enough.

    It is important to note that this mismatch is a protocol-level issue in a particular combination of components. It does not mean that either side lacks capability.

    There are two possible approaches:

    1. Wait for the platform to support the new tool.
    2. Add a protocol adaptation layer so that the two APIs can work together.

    The second approach is faster and also helps developers understand how model integration works internally. This article follows a practical exercise of configuring a cloud coding package. It first evaluates the actual experience of using the desktop tool, then walks through the full process of building a protocol bridge.

    2. Using a Desktop Coding Tool

    1. Immediate benefits of a graphical interface

    The most obvious change in a desktop client is better interaction and visualization:

    • Clearer task management: Multiple conversation turns, changes awaiting confirmation, and history can be displayed together, making it less likely to lose context during long tasks.
    • More intuitive change review: File diffs are more prominent, and commands or write operations that require manual approval have clearer boundaries.
    • More complete access to system capabilities: The client can use the system clipboard, access local files, and send desktop notifications about background task progress.

    For everyday development, these improvements reduce operational friction rather than increasing the underlying model’s capabilities.

    2. Capabilities still depend on the underlying model

    The core workflow of a coding assistant usually follows these steps:

    1. Collect context: Read the user’s instructions, relevant files, and repository structure.
    2. Locate relevant code: Find candidate code snippets through keyword or semantic retrieval.
    3. Build the prompt: Organize code and instructions into a structured input.
    4. Call the model: Send one or more inference requests.
    5. Execute and verify: The model returns tool-call intentions such as reading a file, writing a file, or running a command. The client executes them locally and sends the results back. The model continues reasoning until it produces a final answer or modification.

    The desktop version mainly improves the interaction experience in steps 1 and 5. The quality of step 4 is primarily determined by the connected model’s long-context understanding, code generation, and complex reasoning capabilities.

    Therefore, connecting to a stable and suitable model service is the prerequisite for a good user experience. It is also the problem that the protocol bridge described in this article aims to solve.

    3. Protocol Differences: The Basis for Designing a Bridge

    1. Where conversation state lives

    This is the most fundamental difference between the two protocols.

    • Responses API: Conversation state is stored on the server side. A request carries an identifier returned by the previous response, and the service uses it to restore context and generate a new response.
    • Chat Completions API: The server does not store state. The client must send the system prompt, historical messages, and tool results in full on every request. The server answers based only on what it receives.

    The bridge must therefore maintain a state-mapping table: it translates the previous-response identifier carried by a Responses API request into the complete message array required by the Chat Completions API.

    2. Request body structure

    • Responses API: Main fields include instructions, the input item array, tool definitions, tool-choice strategy, and the previous-response identifier. The input array can contain multiple types of content items.
    • Chat Completions API: Main fields include the messages array, tool definitions, tool-choice strategy, and sampling parameters. Messages have explicit roles such as system, user, assistant, and tool.

    3. Streaming event format

    • Responses API: Returns a structured event stream. Typical events include output-item added, text delta, output-item done, and response completed.
    • Chat Completions API: Uses Server-Sent Events (SSE) to push data chunks in a fixed format. Text deltas appear in delta.content under the choices array, tool-call deltas appear in delta.tool_calls, and the finish reason appears in finish_reason.

    4. Tool-calling round-trip format

    • Responses API: The model outputs function-call items with unique identifiers, and call results are returned as output items of the corresponding type.
    • Chat Completions API: The model outputs tool_calls with call identifiers, and call results are returned as messages with role set to tool.

    The differences can be summarized as follows:

    Dimension Responses API (stateful) Chat Completions API (stateless)
    Context management Stored on the server; the request carries the previous-response identifier Stored on the client; every request sends the full message list
    Request body Instructions + input item array Message array with explicit roles
    Streaming output Structured event stream: output items, text deltas, completion events SSE data chunks with token-level deltas
    Tool calling Function-call items + output items of the corresponding type tool_calls + messages with role set to tool
    Integration Natively supported by newer coding tools Commonly provided by default by many model services, including coding packages

    In one sentence: the Responses API keeps state on the server, while the Chat Completions API keeps state on the client.

    The bridge’s job is to reconstruct the client-managed state into a message sequence the server can understand, and then repackage the server’s response into the event stream expected by the client.

    4. Overall Bridge Design

    1. Positioning

    The bridge is essentially a local protocol adapter service. It listens on a local port as a reverse proxy. Upstream, it behaves as a Responses API client. Downstream, toward the coding tool, it behaves as a Responses API server.

    The data flow is as follows:

    1. ┌─────────────┐ Responses request ┌──────────────────┐ Chat Completions request ┌─────────────────────┐
    2. │ Coding tool │ ───────────────────▶ │ Protocol bridge │ ───────────────────────────▶ │ Cloud model service │
    3. │ (terminal or desktop) │ ◀─────────────────── │ State + format conversion │ ◀─────────────────────────── │ (Chat Completions API) │
    4. └─────────────┘ Responses event stream └──────────────────┘ SSE stream └─────────────────────┘
    5. │
    6. └── Local session-state table ("memory" for stateless APIs)

    This design has several advantages:

    • No need to modify the coding tool’s source code.
    • No additional adaptation is required from the platform provider.
    • Session state is fully controlled locally, which makes troubleshooting, metering, and auditing easier.

    2. Main modules of the bridge

    • Inbound parsing: Parse the Responses request and extract system instructions, input items, tool definitions, and session identifiers.
    • State management: Maintain the mapping between response identifiers and conversation message sequences. Set limits on the number of sessions and expiration policies to avoid unbounded memory growth.
    • Request conversion: Convert instructions into a system message, convert text and image input items into the corresponding user messages, convert tool definitions into standard tool descriptions, and restore historical function calls and results as tool_calls and tool messages.
    • Streaming conversion: Translate SSE data chunks into structured event streams and correctly route text, tool calls, and reasoning content.
    • Error handling: Convert HTTP errors, rate limits, timeouts, and upstream error events into error information that the client can recognize.

    5. Core Implementation Details

    1. Session-state mapping

    State mapping is the core of the design. A two-level index is recommended:

    • Response identifier to session: Record the response identifier returned by the service and its corresponding local session record. The session record contains the full message list, system prompt, tool definitions, sampling parameters, and other metadata.
    • Session to tool calls: Record each function-call identifier and its position in the message list so that call results can be inserted accurately.

    For lifecycle management, short-lived sessions can be kept in memory or persisted using a lightweight local database. Set expiration times and capacity limits, and periodically clean up idle sessions.

    If the tool sends the complete input on every turn and does not rely on server-side state, a stateless approach that reconstructs the request each time can also work. However, this approach deviates from the stateful assumption and has higher repeated-transfer costs. Therefore, stateful mapping remains the preferred approach.

    2. Request-body conversion

    1. Responses request Chat Completions request
    2. ──────────────────────────── ────────────────────────────
    3. instructions ──────convert──────▶ messages[0] = {role: "system", ...}
    4. input: [ messages[1..n] = restored historical messages
    5. {type: "message", tools = tool definitions
    6. role: "user", tool_choice = tool-choice strategy
    7. content: [...]}, stream = true
    8. {type: "function_call", ──history──▶ {role:"assistant", tool_calls:[...]}
    9. call_id: "..."}, {role:"tool", tool_call_id:"...", ...}
    10. {type: "function_call_output", ──history──▶ ...
    11. call_id: "...", ...},
    12. ...
    13. ]
    14. tools ──────convert──────▶ tools
    15. tool_choice ──────convert──────▶ tool_choice
    16. previous_... ──restore via lookup────▶ complete messages

    Several details require special attention:

    • History replay semantics: The Responses API allows historical items to refer to content stored by the service, and the service charges only for newly added input. The Chat Completions API requires the client to send all messages every time. The bridge must therefore faithfully reconstruct the history.
    • Multimodal input: Content items such as images and files must be converted into the content-block structure expected by the Chat Completions API.
    • Cleaning invalid history: Some models impose format constraints on historical tool_calls and tool messages, such as requiring call identifiers to match one-to-one. The bridge should validate the history before sending and, when necessary, trim records that cannot be matched to prevent the request from being rejected outright.
    • Parameter mapping: Sampling parameters such as temperature and maximum output length must be mapped item by item. Parameters unique to the Responses API should be ignored or rejected according to the agreed policy when the upstream does not support them, and the behavior should be recorded.

    3. Streaming-event conversion

    Streaming conversion determines how responsive the tool feels. If the Responses API uses a structured event stream carried over SSE, the bridge must translate the upstream stream into the following event sequence:

    1. Example event order
    2. Upstream SSE data chunk Downstream structured event stream
    3. ────────────────────── ─────────────────────────────────────
    4. delta.role = "assistant" ──▶ response.created
    5. delta.reasoning_content = ... ──▶ response.reasoning_summary_text.delta
    6. delta.content = "H" ──▶ response.output_item.added (message)
    7. response.content_part.added
    8. response.output_text.delta (delta="H")
    9. delta.content = "i" ──▶ response.output_text.delta (delta="i")
    10. delta.tool_calls[0] ... ──▶ response.output_item.added (function_call)
    11. response.function_call_arguments.delta
    12. response.output_item.done
    13. finish_reason = "tool_calls" ──▶ response.completed

    Important details include:

    • Text deltas: Text returned by the upstream in token fragments must be forwarded as text-delta events without first concatenating it and sending it all at once. Otherwise, the streaming experience of generating and displaying content incrementally is lost.
    • Tool-call arguments: Arguments often arrive in fragments. Clients usually parse the arguments and execute the call only after receiving the completion event. Therefore, the bridge must wait until the upstream finish_reason is tool_calls and the arguments are fully assembled before sending the function-call completion event.
    • Reasoning content: If the upstream returns reasoning summaries in a separate field, as some reasoning models do, these should be mapped to reasoning-summary events. Whether the client displays them depends on its own settings.
    • Non-streaming requests: If the client requests a non-streaming response, return the converted complete result directly; there is no need to simulate an event stream.
    • Usage statistics: The response.completed event should include usage information such as input and output token counts so the client can display usage and verify billing.
    • Citations: If the model can return sources for search results, these should be mapped to the corresponding citation or annotation events.

    4. Error handling and recoverability

    • HTTP errors: 401 or 403 responses usually indicate credential or permission problems, 429 indicates rate limiting, and 5xx responses indicate server-side failures. The bridge should convert these into error responses that the client can recognize and provide readable reasons instead of passing through a status code that the client cannot parse.
    • Upstream error events: If an error event appears in the upstream stream, the bridge should immediately end the current response and return an error rather than leaving the client waiting indefinitely.
    • Timeouts and dropped connections: Set timeouts for both individual connections and the overall response. If the upstream connection drops, close the downstream connection promptly to avoid resource leaks.
    • Retries and rate limits: 429 and 5xx responses can be retried with exponential backoff, but a maximum retry count must be enforced to prevent infinite loops and duplicate billing.

    6. Deployment and Configuration

    1. Environment preparation

    A bridge service typically has two components:

    1. An upper-layer service for protocol conversion and state management.
    2. A lower-layer component written in a systems language for efficient forwarding.

    Before deployment, confirm the following:

    • The runtime version of the upper-layer service meets requirements and the package manager is available.
    • The Rust toolchain is installed. Rust 1.85 and later support the 2024 edition syntax. On Windows, the official rustup-init installer can install it in one step. After installation, refresh environment variables and verify with version commands:
    1. Invoke-WebRequest -Uri "https://win.rustup.rs/x86_64" -OutFile "rustup-init.exe"
    2. .\rustup-init.exe -y
    3. $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
    4. rustc --version
    5. cargo --version
    • The build and installation directories have been created, and the current account has write permission.
    • The model service endpoint, model name, and access key are ready.

    2. Build and install the bridge service

    1. npm install -g @heungtae/codex-chat-bridge
    1. cd <node_modules>/@heungtae/codex-chat-bridge
    2. npm run build:bridge
    3. Copy-Item -Path "target\release\codex-chat-bridge.exe" -Destination "<install-directory>\codex-chat-bridge.exe" -Force
    4. codex-chat-bridge --version

    After the build succeeds, copy the executable to the installation directory, add it to the PATH environment variable, and verify the version output from any terminal.

    3. Write the bridge configuration

    The bridge configuration file is usually located in a hidden configuration directory under the user’s home directory. On Windows, this is typically C:\Users\.config\. On Linux or macOS, it is typically ~/.config//.

    The configuration structure may vary across versions. The following is a generic example:

    1. # Bridge listen address: bind to localhost only to avoid public exposure
    2. [bridge]
    3. listen = "127.0.0.1:8787"
    4. request_timeout_secs = 300
    5. max_sessions = 1000
    6. # Upstream model service (example: a cloud provider's Chat Completions API)
    7. [upstream]
    8. base_url = "https://<model-service-endpoint>/v1"
    9. api_key = "<access-key>"
    10. model = "<model-name>"
    11. # Model parameter mapping (optional)
    12. [transform]
    13. system_message = "developer"
    14. drop_unsupported_params = true

    The configuration above is illustrative; field names and default values should follow the actual version. More importantly, several principles matter:

    • Local-only listening: Bind only to 127.0.0.1 to avoid exposing the bridge to the public internet.
    • Credential security: Keep the API key only in a local configuration file or environment variable, and restrict configuration-file permissions so that only the current user can read them.
    • Model-name consistency: The model name in the bridge configuration must match a model identifier supported by the platform.

    4. Point the coding tool to the bridge

    Using OpenAI Codex as an example, the same general approach applies to other newer tools:

    1. In system settings, confirm that you are signed in or have an available model authorization.
    2. Edit ~/.codex/config.toml, add a custom model provider, set base_url to the bridge service address, for example http://127.0.0.1:8787/v1, and configure it to read the key from an environment variable.
    3. In profiles, specify the model provider and model name.
    4. If you want to use it by default long-term, set the profile as the global default or specify it through command-line arguments at startup.
    1. model_provider = "bridge"
    2. model = "bridge-model"
    3. [model_providers.bridge]
    4. name = "Bridge"
    5. base_url = "http://127.0.0.1:8787/v1"
    6. env_key = "BRIDGE_API_KEY"
    7. wire_api = "responses"
    8. [profiles.bridge]
    9. model_provider = "bridge"
    10. model = "bridge-model"
    11. model_reasoning_effort = "high"

    5. End-to-end verification

    1. export BRIDGE_API_KEY="any-non-empty-value" # PowerShell: $env:BRIDGE_API_KEY = "..."
    2. codex-chat-bridge --config ~/.config/codex-chat-bridge/conf.toml
    3. codex --profile bridge "Explain the TCP three-way handshake in one sentence."

    A recommended verification order is:

    1. Health check: request the root path and confirm that the service has started.
    2. Single-turn conversation: confirm that text is returned correctly.
    3. Streaming output: confirm that text appears incrementally.
    4. Tool calling: ask the model to read a file and answer a question, and confirm that the full call-and-return chain works.
    5. Multi-turn conversation: ask follow-up questions and confirm that context is preserved.
    6. Long context: provide a large code file and confirm that the request is neither truncated nor rejected.

    7. Common Risks and Recommendations

    • Quota and rate limits: The bridge sends the full history on every turn, so input-token consumption grows as the conversation becomes longer. It is advisable to control history length in session management, for example through summary compression or sliding windows, and to check usage regularly.
    • Protocol version drift: Upstream API evolution may introduce incompatible fields. Pin the bridge service version and validate with a small amount of traffic before upgrading.
    • Security risks: The bridge service holds model-access credentials. Bind it to localhost only, restrict configuration-file permissions, and never commit keys to repositories or write them to logs.
    • Compliance and stability: The quality, update frequency, and security of third-party bridge services should be evaluated independently. In production environments, combine monitoring alerts, log auditing, and fallback strategies to avoid a single point of failure disrupting the development workflow.
    • Desktop-client limitations: Desktop clients may still have feature differences or known issues on some platforms. Always enable manual confirmation when file writes or command execution are involved.

    8. Conclusion

    Desktop coding tools make it possible to use AI coding assistants like an IDE, but the upper limit of their effectiveness still depends on the connected model service.

    When a newer tool supports only the stateful Responses API while a cloud service provides only the stateless Chat Completions API, the problem is not necessarily the tool or the platform itself. It is a mismatch at the protocol layer.

    By adding a lightweight protocol bridge that reconstructs server-side state as client-side messages and translates upstream streams into the target event stream, the two sides can work together with almost no changes on either side.

    This experience also shows that when facing compatibility problems such as a new tool combined with an older API, identifying the differences and applying a minimal adaptation layer is often faster and more controllable than waiting for official support.

    Regardless of the tool used, credential security, usage control, and observability should be treated as equally important as functionality.