# OxideTerm Architecture
> **Scope**: The native desktop application and the UI components it shares with the separate Web/WASM build target.
> **Source of truth**: the current Rust/GPUI workspace; see [Cargo.toml](../../../Cargo.toml) for its version and [development guides](../../development/README.md) for contributor workflows.
This document describes the native system's components, data and control paths, and lifecycle ownership. For daily navigation, start with [Workspace Navigation](workspace.md).
## Contents
1. [Design Principles](#design-principles)
2. [Architecture Overview](#architecture-overview)
3. [Two-Plane Architecture](#two-plane-architecture)
4. [Native Workspace Layers](#native-workspace-layers)
5. [Node-First Runtime Model](#node-first-runtime-model)
6. [Desktop Workspace Architecture](#desktop-workspace-architecture)
7. [Terminal Architecture](#terminal-architecture)
8. [SSH Connection Registry and Runtime](#ssh-connection-registry-and-runtime)
9. [SFTP Architecture](#sftp-architecture)
10. [IDE Architecture](#ide-architecture)
11. [Port Forwarding Architecture](#port-forwarding-architecture)
12. [Remote Desktop and WSL Graphics](#remote-desktop-and-wsl-graphics)
13. [Reconnect And Recovery](#reconnect-and-recovery)
14. [Settings And Persistence](#settings-and-persistence)
15. [Cloud Sync, Backups, And Portable Bundles](#cloud-sync-backups-and-portable-bundles)
16. [OxideSens AI Architecture](#oxidesens-ai-architecture)
17. [Plugin Architecture](#plugin-architecture)
- [Dynamic Plugin Discovery Data Flow](#dynamic-plugin-discovery-data-flow)
18. [CLI Companion Boundary](#cli-companion-boundary)
- [Public MCP Host, Approval, and Local Takeover](#public-mcp-host-approval-and-local-takeover)
19. [Security Design](#security-design)
20. [Performance Design](#performance-design)
21. [Detailed Module Structure](#detailed-module-structure)
22. [Data Flow Walkthroughs](#data-flow-walkthroughs)
23. [State Machines And Lifecycles](#state-machines-and-lifecycles)
24. [Ownership And Persistence Matrix](#ownership-and-persistence-matrix)
25. [Event And Notification Model](#event-and-notification-model)
26. [Failure Model](#failure-model)
27. [Native Crate Map](#native-crate-map)
---
## Design Principles
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Desktop["GPUI desktop workspace"]
Fast["Terminal data path
input, output, resize"]
Control["Management operations
files, forwards, AI, sync"]
Owners["Explicit runtime owners
nodes, sessions, tasks"]
Shared["SSH node capabilities
registry-owned transport shared by consumers"]
Local["Local settings and saved profiles"]
Secrets["Separate secret storage"]
Desktop --> Fast
Desktop --> Control
Fast --> Owners
Control --> Owners
Owners -->|"SSH-backed work"| Shared
Control -->|"When settings or profiles change"| Local
Control -->|"When credentials are needed"| Secrets
```
### Core Principles
1. **Desktop app first** - The GPUI desktop app is the primary user surface. The CLI is a companion for automation and diagnostics.
2. **Terminal responsiveness** - Terminal input, output, resize, and rendering are latency-sensitive hot-path work.
3. **Node-first remote workspace** - SSH-backed workflows are anchored by a stable node, not by a transient terminal pane.
4. **Default shared connection** - Terminal, SFTP, forwarding, and IDE can share a node's registry connection; AI and plugins use validated capability handles, snapshots, or hooks rather than becoming physical connection consumers.
5. **Explicit lifecycle ownership** - Saved profiles, live nodes, terminal sessions, SFTP sessions, forwards, editor buffers, and tabs have different owners.
6. **Local-first state** - SSH, SFTP, local terminal, settings, plugins, and AI provider configuration work without an OxideTerm cloud account.
7. **Secret separation** - Navigation metadata, settings, AI prompts, logs, support bundles, and plugin labels are not secret storage.
8. **Minimum visible coupling** - User-facing surfaces should not require users to reason about internal transport handles.
### Why Rust + GPUI
| Concern | Native Rust/GPUI Direction |
|---|---|
| User experience | One desktop workspace for terminal, files, forwarding, IDE, AI, settings, and plugins |
| Backend ownership | Core rules and models live in Rust domain crates; `oxideterm-gpui-app` owns coordinating Entities, subscriptions, and final runtime shutdown instead of treating them as ad hoc view state |
| Terminal path | Terminal input/output stays isolated from heavy management work |
| Safety | SSH, SFTP, forwarding, persistence, secrets, and AI boundaries are explicit Rust domains |
| Portability | Desktop package can include app resources, agent binaries, icons, and CLI companion |
| Maintainability | Crates split by responsibility rather than by screen or file size |
---
## Architecture Overview
### Native Desktop and Web/WASM Target
OxideTerm's main product is the native desktop application. Its host, `oxideterm-gpui-app`, manages native windows, SSH nodes and local processes. [`oxideterm-gpui-web`](../../../crates/oxideterm-gpui-web/src/boot.rs) is a separate Web/WASM build target that runs in a web browser; it is not a browser embedded in the desktop app. Both targets use [`WorkspaceShell`](../../../crates/oxideterm-gpui-shell/src/frame.rs) for tab strips, rails and pane layout. Each host provides the pages and routes input or close requests to the correct session.
Both targets share the terminal emulator and canvas. `oxideterm-terminal-emulator` parses bytes and produces grid snapshots; `oxideterm-gpui-terminal-view` handles layout, painting and input. The desktop `TerminalPane` implements `TerminalCanvasHost` while a native session reads and writes the PTY or SSH channel. The Web/WASM frontend mounts a standalone `TerminalView` and routes input, protocol replies and resize events to its own session.
Both hosts use the shared tab context menu and supply the actions each target can execute. The Web/WASM frontend can use local directories authorized through Web APIs for file management and IDE. Its WSS gateway does not provide remote SFTP, an IDE file bridge, or remote desktop. See the [desktop–WASM parity audit](../../development/wasm-desktop-parity.md).
Without a gateway, the Web/WASM demo's terminal and file pages use in-memory sample data; its Host Tools shows sample captures. With `?gateway=wss://…`, the terminal requests sessions over the [WebSocket protocol](../../../crates/oxideterm-gpui-web/src/transport.rs); a failed connection does not switch back to the demo. Where Web Bluetooth is available, the frontend connects directly to the selected BLE device's GATT service. The native Wasm plugin runtime is separate from this build target.
### Native Desktop Runtime Overview
This diagram and the SSH and SFTP lifecycles below describe the native desktop application. Thick arrows show lifecycle ownership or a retained handle, solid arrows show calls or data flow, and dotted arrows show scoped access or metadata delivery.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
subgraph Core["Application coordination and runtime domains"]
direction TB
Views["Windows and workspace controls
tabs, scopes, sidebars, dialogs"]
App["WorkspaceApp
actions, subscriptions, shutdown"]
Tabs["WorkspaceTabHostEntity
pane trees, terminal entities, window mounts"]
Terminal["TerminalPane / TerminalSession
local, SSH, Mosh, Telnet, serial, BLE and container terminals"]
Grid["oxideterm-terminal-emulator / oxideterm-terminal-graphics
ANSI, grid, history, protocol images"]
Paint["TerminalPane snapshots and oxideterm-gpui-terminal-view
row layout, glyph caches, image uploads"]
Media["Background media and effects
decode, animation, composition"]
Services["GPUI feature entities
SFTP, IDE, forwards and Host Tools"]
Consumers["SFTP and IDE file adapters; forwarding runtime
IDE upload and download use Agent or staged SFTP"]
HostJobs["Host Tools workers
container CLI and Redis discovery, capture and actions"]
Wsl["oxideterm-wsl-graphics
WSLg detection and ownership of WSL VNC and child processes"]
X11["oxideterm-x11-forwarding
SSH X11 channel bridge"]
Runtime["WorkspaceRuntimeEntity
connect, probe, reconnect, restore"]
Router["NodeRouter / NodeRuntimeStore
node identity, state, routing"]
Registry["SshConnectionRegistry
shared connections and consumer leases"]
DesktopSession["oxideterm-gpui-remote-desktop / oxideterm-remote-desktop
viewer, session worker, frames and relative pointer capture"]
AudioRouting["oxideterm-pcm-audio in the GUI process
macOS AirPods playback-route arbitration"]
Plugins["PluginWorkspaceEntity
install, enable, delivery, shutdown"]
PluginRuntime["Plugin registry and host API
manifests, capabilities, process and Wasm runtimes"]
Discovery["oxideterm-discovery
provider sources and resolved targets"]
AcpSessions["oxideterm-gpui-ai / AcpWorkspaceEntity
agent sessions and process delivery"]
AcpTools["oxideterm-acp-host-tools
per-conversation loopback tool relay"]
PublicMcp["oxideterm-public-mcp / oxideterm-public-mcp-host
loopback authorization, approval wait and host dispatch"]
Sync["oxideterm-gpui-cloud-sync / oxideterm-cloud-sync
v3 replicas, preview, journaled apply and publish"]
AiContext["AI context and approval boundaries
target handles, generations, permissions"]
AI["oxideterm-ai / ai-tasks
provider streams, tools, RAG, MCP client"]
end
subgraph Durable["Configuration, durable data and secrets"]
direction TB
Stores["Connections and settings stores
validation and durable writes"]
Bundles["Local backups and .oxide bundles"]
Metadata["Settings and saved profiles
plugin metadata, secret references"]
Secrets["OS keychain / encrypted secret storage
credential values, provider keys, tokens"]
Knowledge["AI conversations and RAG storage"]
Audit["Audit records and managed recordings"]
end
subgraph Outside["OS resources, helper processes and remote endpoints"]
direction TB
LocalIO["Local files, processes and PTYs
Mosh and Telnet endpoints, serial and BLE devices"]
SSH["SSH servers and jump hosts"]
Helpers["Plugin-provided RDP, VNC and SPICE helpers
protocol channels and supported PCM playback/capture"]
DesktopTargets["RDP, VNC and SPICE endpoints"]
AgentProcesses["ACP agent processes"]
McpClients["Authorized local MCP clients"]
Providers["AI providers / external MCP servers"]
SyncRemote["Cloud sync backend"]
end
Views --> App
App ==> Tabs
App --> Media
App ==> Services
App --> Wsl
App --> X11
App ==> Runtime
App --> DesktopSession
App ==> Plugins
App ==> AcpSessions
App ==> AiContext
App ==> PublicMcp
App ==> Sync
App --> Stores
App --> Audit
Tabs ==> Terminal
Terminal --> Grid
Terminal -->|"SSH consumer lease and shell channel"| Registry
Terminal --> LocalIO
Grid --> Paint
Media -->|"Background layers in the workspace scene"| Views
Services --> Consumers
Consumers -->|"SSH-backed targets"| Router
Consumers -->|"Local host and local files"| LocalIO
Services --> HostJobs
HostJobs -->|"Selected SSH connection"| Registry
HostJobs -->|"Local execution"| LocalIO
Wsl --> LocalIO
X11 -->|"SSH session channel"| Registry
Runtime --> Router
Runtime -->|"Authentication"| Secrets
Router --> Registry
Registry --> SSH
DesktopSession -->|"Optional SSH gateway through forwarding service"| Consumers
DesktopSession ==>|"Session worker"| Helpers
Helpers -->|"Playback state"| DesktopSession
DesktopSession -->|"Acquire or release playback route"| AudioRouting
DesktopSession -.->|"Routing ready for this generation"| Helpers
Helpers --> DesktopTargets
Plugins --> PluginRuntime
PluginRuntime -.->|"Verified desktop provider metadata"| DesktopSession
PluginRuntime -.->|"Verified ACP adapter package"| AcpSessions
PluginRuntime -.->|"Discovery providers"| Discovery
Discovery -.->|"Session tree and command palette"| Views
Discovery -->|"Resolved SSH target"| Runtime
AcpSessions ==> AgentProcesses
AcpSessions -->|"Publish tools for the active turn"| AcpTools
AgentProcesses -->|"Call application tools"| AcpTools
AcpTools --> AI
McpClients --> PublicMcp
PublicMcp -.->|"Authorized workspace calls"| App
PublicMcp -.->|"Authorized node operations"| Router
AiContext --> AI
AI -->|"Provider credentials"| Secrets
AI --> Knowledge
AI --> Providers
Stores --> Metadata
Stores -->|"Secret-aware writes"| Secrets
App -->|".oxide import and export"| Bundles
Sync -->|"Read and apply selected local state"| Stores
Sync -->|"Separate backup and restore workflow"| Bundles
Sync -->|"Fetch and publish replicas"| SyncRemote
```
### System Context
```mermaid
flowchart LR
User["User"]
subgraph Local["Local Machine"]
App["OxideTerm native desktop app"]
Cli["oxideterm CLI companion"]
Config["Shared configuration
settings and saved profiles"]
Secrets["Secret Storage
provider keys · SSH credentials · plugin tokens"]
Pty["Local PTY"]
Plugins["Installed desktop plugins"]
Helpers["Remote desktop helper processes"]
McpClients["Authorized local MCP clients"]
end
subgraph Remote["Remote Environments"]
SshHost["SSH Hosts"]
SftpHost["SFTP Subsystems"]
RemotePorts["SSH forwarding endpoints"]
Agent["Optional Remote File/Code Agent
Linux musl targets"]
RemoteDesktop["RDP, VNC or SPICE server"]
end
subgraph External["External Services"]
AiProviders["AI Providers"]
McpServers["External MCP servers"]
SyncBackend["Cloud Sync v3 backend"]
UpdateServer["Update Channel"]
end
User --> App
User --> Cli
McpClients -->|"Loopback Public MCP"| App
App --> Config
Cli --> Config
App --> Secrets
Cli --> Secrets
App --> Pty
App --> Plugins
Plugins -.->|"Provide verified helper packages"| Helpers
App -->|"Launch and communicate with helper"| Helpers
Helpers --> RemoteDesktop
App -->|"SSH sessions and optional desktop gateway"| SshHost
SshHost --> SftpHost
SshHost --> RemotePorts
App -->|"Optional IDE agent over SSH"| Agent
App --> AiProviders
App --> McpServers
App --> SyncBackend
Cli --> SyncBackend
App --> UpdateServer
```
### User-Facing Summary
The app is a workspace shell around stable remote nodes. Tabs and panes are views. Saved connections are profiles. SSH nodes are live or reconnecting runtime objects. Terminal sessions, SFTP sessions, IDE workspaces, and forwards consume node capabilities directly; AI targets and plugin surfaces use validated capability handles, host snapshots, or terminal hooks.
That separation explains common behavior:
- Closing a terminal tab does not delete the saved connection.
- A node may remain visible in Connection Monitor after a pane closes.
- SFTP and IDE can recover after a reconnect because they are tied to the node, not only to a terminal pane.
- AI tools must select explicit targets before they run commands or read files.
- The CLI companion can inspect the same state, but it is not the main interactive surface.
---
## Two-Plane Architecture
The native application separates the terminal data path from structured control operations even though both live in the same Rust process.
### Data Plane
The data plane handles high-frequency terminal activity:
```text
terminal input
-> terminal runtime
-> local PTY or SSH shell channel
-> terminal output
-> terminal renderer
```
Properties:
- Low latency.
- High event volume.
- No dependence on cloud sync or backups.
- No user-visible confirmation flow for ordinary input.
- Rendering and input focus stay local to the terminal surface.
### Control Plane
The control plane handles structured management operations:
```text
user action or AI-approved tool
-> workspace command
-> domain runtime
-> persistence / connection / file / sync action
-> result, notification, or recovery hint
```
Examples:
- Create a saved connection.
- Open an SSH node.
- Start SFTP.
- Create a forward.
- Inspect host tools such as processes, containers, Redis, services, tmux, packages, logs, ports, and filesystems.
- Open an IDE workspace.
- Open a remote desktop session.
- Confirm a terminal file-transfer prompt.
- Change a setting.
- Manage privilege credentials.
- Run a cloud-sync action.
- Execute an approved AI tool.
- Generate a support bundle.
### Persistence Plane
The persistence plane stores durable state:
- Settings.
- Saved connections.
- Forward rules.
- Plugin state.
- Privilege credential metadata.
- AI conversations and summaries.
- Cloud sync snapshots.
- Backups.
- Portable runtime metadata.
Secret-bearing data must cross into secret-aware storage rather than ordinary JSON/text fields. For privilege helpers, durable scope metadata can live with settings or saved connections, but the secret value belongs to the secret store.
### Plane Interaction
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Input["Ordinary terminal input"]
Pane["Terminal pane
focus and input encoding"]
Runtime["TerminalSession
PTY or protocol backend"]
Model["Terminal emulator
parser, grid and history"]
Snapshot["TerminalPane
stamped row snapshots and presentation state"]
Draw["GPUI terminal view
layout and cached drawing"]
Action["User management action
or authorized application tool"]
Route["Feature action or host bridge
target and operation validation"]
Owner["Domain owner
node, file, forward, settings or sync"]
Persist["Durable configuration stores
metadata and safe references"]
Secret["Secret-aware storage
credential values"]
Result["Structured outcome
domain state and scoped UI update"]
Input --> Pane
Pane --> Runtime
Runtime -->|"Terminal output"| Model
Model -->|"Protocol replies"| Runtime
Model --> Snapshot
Snapshot --> Draw
Action --> Route
Route --> Owner
Owner -->|"Configuration operations"| Persist
Owner -->|"Credential operations"| Secret
Owner --> Result
```
The two input paths are separate: ordinary typing does not pass through management approval. Management outcomes update their owning surface; they are not all terminal output. Persistence is a durable boundary used by control operations, not a stage in every terminal frame.
Implementation: [workspace](../../../crates/oxideterm-gpui-app/src/workspace.rs), [terminal_entity](../../../crates/oxideterm-gpui-app/src/workspace/terminal_entity.rs).
---
## Native Workspace Layers
### Layer 1: GPUI Application Shell
`oxideterm-gpui-shell` provides the frame; `oxideterm-gpui-app` composes desktop windows, feature views and sessions inside it. Feature entities own their state.
Responsibilities:
- Create the desktop window.
- Render window chrome and pane layout; mount feature-owned dialogs, sidebars and settings views.
- Route user actions to domain crates.
- Keep UI state separate from durable domain state while holding runtime entity
handles, subscriptions, task delivery, and final shutdown ownership.
- Provide app-level notifications and command palette actions.
Representative modules:
```text
crates/oxideterm-gpui-app/src/workspace.rs
crates/oxideterm-gpui-app/src/workspace/tabs/
crates/oxideterm-gpui-shell/src/panes.rs
crates/oxideterm-gpui-app/src/workspace/sidebar/
crates/oxideterm-gpui-app/src/workspace/settings/
crates/oxideterm-gpui-app/src/workspace/knowledge.rs
```
### Layer Dependency Shape
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
App["oxideterm-gpui-app
native composition, action dispatch and shutdown"]
Shell["oxideterm-gpui-shell
shared frame, tab and pane layout models, navigation"]
TabHost["WorkspaceTabHostEntity
pane entities, subscriptions and window mounts"]
Views["Feature GPUI crates
connections, SFTP, IDE, remote desktop, Host Tools and settings"]
Owners["Workspace runtime and feature host bridges
shared services, actions and lifecycle"]
Terminal["Terminal domains
protocol, grid, graphics and rendering"]
Remote["Remote domains
SSH, SFTP, forwarding and connection monitoring"]
Editor["IDE / editor domains
project model, text and file adapters"]
RemoteDesktop["Remote desktop domain
session worker and helper protocol"]
Extensions["AI, plugin and discovery domains
capabilities, providers and resolved targets"]
Persistence["Configuration and Cloud Sync v3
validation, local apply and publication"]
Pty["OS PTY and protocol endpoints"]
Node["NodeRouter / connection registry
SSH channels and consumer leases"]
External["Provider streams and external helpers"]
Disk["Configuration, documents and backups"]
Vault["Separate credential storage boundary"]
App --> Shell
App --> TabHost
TabHost --> Shell
TabHost --> Terminal
App --> Views
App --> Owners
Views -.->|"Actions needing the workspace host"| Owners
Views -->|"Feature-owned state and logic"| Editor
Views -->|"Feature-owned sessions and rendering"| RemoteDesktop
Owners --> Terminal
Owners --> Remote
Owners --> Editor
Owners --> RemoteDesktop
Owners --> Extensions
Owners --> Persistence
Terminal --> Pty
Terminal -->|"SSH path"| Node
Remote --> Node
Editor -->|"SSH-backed file adapters"| Node
RemoteDesktop -->|"Protocol helper"| External
Owners -->|"Forwarding service opens optional desktop gateway"| Node
Extensions --> External
Persistence --> Disk
Persistence -->|"Secret-aware operations"| Vault
```
This is a responsibility-layer map, not an exhaustive Cargo dependency graph. App owners connect the views to domain APIs; reusable text/project models remain transport-free. Forward listeners, graphics helpers and samplers have concrete runtime owners described in their chapters. Saved connection files belong to the connections store rather than the SSH transport crate.
Implementation: [workspace](../../../crates/oxideterm-gpui-app/src/workspace.rs), [lib](../../../crates/oxideterm-ide-core/src/lib.rs), [lib](../../../crates/oxideterm-connections/src/lib.rs).
### Layer 2: Domain Crates
Domain crates own reusable business logic and protocol models.
Examples:
- `oxideterm-ssh`: SSH configuration, connection registry, node routing, reconnect model.
- `oxideterm-sftp`: SFTP protocol/session and transfer semantics.
- `oxideterm-connections`: saved connection storage and validation.
- `oxideterm-forwarding`: forward rule model.
- `oxideterm-ai`: AI providers, context window logic, RAG, MCP, orchestrator tool definitions, policy.
- `oxideterm-settings`: settings load/save/mutation logic.
- `oxideterm-cloud-sync`: sync and backup logic.
- `oxideterm-plugin-*`: plugin manifest, protocol, registry, and host API types.
### Layer 3: Runtime Integrations
Runtime integrations bridge UI requests to active resources:
- Local terminal process.
- SSH shell channel.
- SFTP channel.
- Forward listener or remote forward.
- IDE file system access.
- Plugin host lifecycle.
- Cloud sync backend.
- AI provider requests.
The important rule is ownership: a runtime object should have one clear owner.
The app layer may own the coordinating Entity and its lifecycle while reusable
rules remain in domain crates; UI views consume runtime state through explicit
handles, subscriptions, or snapshots.
### Layer 4: Persistence And Secret Storage
Persistent state is shared by the desktop app and CLI companion. Secret values must not be serialized into ordinary settings, support bundles, AI context, or plugin labels.
---
## Node-First Runtime Model
### Problem Avoided
SFTP, IDE, and forwarding must not depend on transient terminal session IDs. A terminal session can be recreated; the remote node is the stable unit of work.
### Current Topology
```text
saved connection
or SSH target resolved by a discovery provider
-> node identity
-> node runtime (`NodeRuntimeStore` + `NodeRouter`)
-> shared or dedicated SSH connection handle
-> terminal session(s)
-> SFTP session
-> forward rules
-> IDE workspace
-> AI capability handles
-> plugin host snapshots and hooks
-> authorized Public MCP node leases
```
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
subgraph Ownership["Workspace, consumers and shared SSH transport"]
direction TB
Owner["WorkspaceApp"]
Host["WorkspaceTabHostEntity
pane entities, mounts, subscriptions"]
PaneA["Terminal pane A"]
SessionA["Terminal session A
shell channel and consumer registration"]
PaneB["Terminal pane B"]
SessionB["Terminal session B
shell channel and consumer registration"]
ServiceOwner["Workspace file and forwarding runtimes"]
Files["SFTP / IDE adapters
file channels and transfer leases"]
Forwards["ForwardingRuntimeService
listeners, remote bindings and leases"]
NodeOwner["WorkspaceRuntimeEntity
connection attempts, health, recovery"]
Recovery["Reconnect orchestrator
probe, retry, consumer restoration"]
Profile["Saved profile
connection metadata and secret references"]
Discovered["Discovered SSH target
resolved by its plugin provider"]
NodeRouter["NodeRouter
node routes and runtime state"]
ConnectionRegistry["SshConnectionRegistry"]
Connection["Shared SSH connection
example: consumers allowed to reuse the node route"]
Dedicated["Dedicated consumer transport
registered separately when required"]
Parent["Jump-host parent transport
retained by the child registry entry"]
Capabilities["AI / plugin target projections
validated handles and snapshots"]
McpLease["Authorized Public MCP node lease"]
end
Owner ==> Host
Owner ==> ServiceOwner
Owner ==> NodeOwner
Host ==> PaneA
Host ==> PaneB
PaneA ==> SessionA
SessionA -->|"Channel and consumer lease"| Connection
PaneB ==> SessionB
SessionB -->|"Channel and consumer lease"| Connection
ServiceOwner ==> Files
ServiceOwner ==> Forwards
Files -->|"Channel and consumer lease"| Connection
Forwards -->|"Channel and consumer lease"| Connection
NodeOwner ==> Recovery
NodeOwner --> NodeRouter
Recovery -->|"Reconnect and restore"| NodeRouter
Profile -->|"Open saved SSH profile"| NodeOwner
Discovered -->|"Open or reconnect resolved target"| NodeOwner
NodeRouter --> ConnectionRegistry
ConnectionRegistry ==> Connection
ConnectionRegistry ==> Dedicated
Connection ==>|"Jump route retains a parent consumer"| Parent
Dedicated ==>|"Jump route retains a parent consumer"| Parent
Capabilities -.->|"Target resolution"| Host
Capabilities -.->|"Validated access"| NodeRouter
McpLease -->|"Acquire via router"| NodeRouter
McpLease -->|"Registered consumer lease"| Connection
```
The thick arrows identify lifecycle holders; channel and consumer-lease arrows identify use of a connection. Closing one pane removes that terminal consumer. SFTP, IDE and forwarding retain their own consumers; an authorized Public MCP client can also hold a node lease. The workspace runtime coordinates reconnect, and jump-host routes retain the parent transport while it is needed. AI and plugin target projections provide validated access without taking ownership of the physical connection. Standalone connections have a separate runtime.
### Stable And Transient Objects
| Object | Stable Role | Transient Implementation Detail |
|---|---|---|
| Saved connection | User profile | Current transport state |
| Node | Remote workspace identity | Current connection handle |
| Terminal tab | Visible shell view | Current PTY/channel instance |
| SFTP view | File workflow for node | Current SFTP channel |
| IDE workspace | Project/editing context | Current file operation channel |
| Forward rule | Desired tunnel | Current listener/task |
| AI target | Tool-facing snapshot | Current target state |
### User Rule
When something remote fails, check the node first. Do not assume the focused tab is the owner of the whole runtime.
### Jump-Host Ownership
Jump-host routing has two related ownership layers:
- `NodeRuntimeStore` records the logical parent/child node tree.
- `ConnectionRegistry` records the physical parent connection relationship and
retains a parent consumer while a child connection depends on it.
- A child connection must not infer its parent from a matching hostname; it uses
the exact node and connection identities.
- Explicit disconnect releases the child subtree before releasing the parent
connection, so a child terminal cannot silently tear down a still-used hop.
---
## Desktop Workspace Architecture
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Actions["Tab, scope and layout actions"]
Host["WorkspaceTabHostEntity
pane entities, subscriptions and locations"]
Filter["Main-window scope
affinity, remembered selection and detached-tab exclusion"]
Visible["Scoped main-window tabs
navigation, reorder, bulk close"]
Validate["Validate layouts and pane identities
source, destination and pane limit"]
Reject["Rejected layout edit
both layouts and locations unchanged"]
Move["Tile or extract existing pane IDs
split can insert an existing pane or a new one"]
Layout["PaneNode tree
terminal and utility leaves, up to 16"]
Detach["Reserve and commit a native-window mount
roll back the reservation if detach fails"]
Mount["Tab mount and zoom
native window and visible panes"]
View["Render active pane surfaces"]
Transport["Existing session / node owners
unchanged by layout moves"]
Actions --> Host
Host --> Filter
Filter --> Visible
Host --> Validate
Validate -->|"Invalid"| Reject
Validate -->|"Valid layout edit"| Move
Host -->|"Detach the tab"| Detach
Detach -->|"Mount committed"| Mount
Host -->|"Return the tab"| Mount
Move --> Layout
Layout --> Mount
Mount --> View
Mount -.->|"Existing sessions survive moves and remounts"| Transport
```
Scope filtering changes presentation, while layout operations move existing resources after validation. Neither is an implicit reconnect. Mixed tabs retain all pane memberships instead of being split by a filter.
Implementation: [entity](../../../crates/oxideterm-gpui-app/src/workspace/tabs/entity.rs), [scope](../../../crates/oxideterm-gpui-app/src/workspace/tabs/scope.rs), [split_drop](../../../crates/oxideterm-gpui-app/src/workspace/tabs/split_drop.rs).
### Workspace Shell
The workspace shell owns visible layout:
- Tabs.
- Pane tree.
- Activity bar.
- Sidebar.
- Command palette.
- Dialog stack.
- Notifications.
It should not own low-level SSH transport or secret material.
### Tabs
Tabs are visible surfaces. A tab can represent:
- Local terminal.
- SSH terminal.
- SFTP.
- IDE workspace.
- Settings.
- File manager.
- Plugin manager.
- Connection monitor.
- Cloud sync.
- Knowledge workspace.
Tabs are closeable views. They are not the durable source of truth for saved connections or secrets.
Tab scopes are window-local filters: all tabs, global pages, local terminals, a specific connection, or a standalone file-transfer endpoint. Mixed layouts combine their panes' memberships and stay intact in every matching scope. Scope selection and last-active-tab memory affect presentation, not runtime ownership, and are not persisted across restart. Rendering, keyboard navigation, reordering, bulk closing, and scroll positioning share the visible tab list and content-based widths.
`PaneNode` represents terminal leaves, utility-page leaves and nested groups. A tab can contain up to 16 panes, as defined by `MAX_PANES_PER_TAB`. Splitting and combining tabs use this same limit. The host validates the source and destination before changing their layouts; a rejected drop leaves both trees and their session locations unchanged.
`WorkspaceTabHostEntity` owns terminal entities, subscriptions, window mounts and session-to-pane locations. Tiling moves 2 to 16 existing terminal panes into one layout while preserving their pane IDs, sessions and runtime consumers. Pane zoom changes which pane is visible without replacing the underlying pane tree. Extraction moves an existing pane into another tab. These operations do not reconnect the terminal transport.
See the [pane model](../../../crates/oxideterm-workspace/src/lib.rs) and [tab host](../../../crates/oxideterm-gpui-app/src/workspace/tabs/entity.rs) for layout limits, validation and ownership transitions.
### Activity Bar
The left activity bar opens connection management and global pages. The right bar opens OxideSens and individual Host Tools, with overflow only when height is insufficient. The top bar owns scope selection, command-palette access, Zen mode, theme switching, and background-task summary. It remains visible in full screen and hides in Zen mode.
### Knowledge Workspace
Knowledge is a first-class central tab with its own internal split layout. Its left navigator owns collection and document browsing; its right pane owns Markdown editing. It is not a global companion-sidebar panel and it is not implemented as a stack of Settings cards.
Source and read-only Preview share one Markdown draft. `TextEditorView` owns editing and undo; `oxideterm-gpui-markdown` renders the preview. The [knowledge workspace](../../../crates/oxideterm-gpui-ai/src/knowledge/workspace.rs) coordinates selection, asynchronous loads, autosave, conflicts and background indexing. When the user tries to leave an unsaved document, the feature handles the save or discard decision and the app handles the tab or window action. The RAG store persists collections, document revisions, chunks and search indexes.
Knowledge settings configure embedding and retrieval; document navigation and editing stay in the Knowledge workspace.
### Notifications
Notifications turn asynchronous domain events into user-visible messages. They should help users decide what to inspect next: connection monitor, settings, SFTP, cloud sync, plugin manager, or support bundle.
### Knowledge Draft And Storage
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Select["Collection / document selection"]
Owner["KnowledgeWorkspaceEntity in oxideterm-gpui-ai
document identity and load generation"]
Guard["Unsaved draft
defer the switch until resolved"]
Load["Load document revision from RAG store"]
LoadError["Report current load failure"]
Draft["Editable document draft
TextEditorView and undo history"]
Preview["Read-only native Markdown preview"]
Save["Explicit or delayed autosave
expected revision and chunk preparation"]
Store["RAG document storage
commit content, revision and chunks"]
Index["Queue coalesced keyword index rebuild
report keyword and embedding status separately"]
Conflict["Save failure or revision conflict
retain local draft"]
Delivery["Apply the saved version
reschedule autosave if newer edits remain"]
Select --> Owner
Owner -->|"Switch allowed"| Load
Owner -->|"Different document and dirty draft"| Guard
Guard -->|"Switch confirmed"| Load
Load -->|"Current document and generation"| Draft
Load -->|"Current request failed"| LoadError
Draft -->|"Markdown documents"| Preview
Draft --> Save
Save -->|"Version matches and transaction commits"| Store
Save -->|"Version conflict or write error"| Conflict
Store --> Index
Index --> Delivery
```
Source and Preview use the same draft. A preview switch does not create another editable copy; indexing is derived work after document storage, and an old load must not replace a newly selected document.
Implementation: [knowledge](../../../crates/oxideterm-gpui-app/src/workspace/knowledge.rs), [operations](../../../crates/oxideterm-gpui-ai/src/knowledge/workspace/operations.rs).
---
## Terminal Architecture
`oxideterm-terminal-triggers` matches rules against streaming terminal output; `oxideterm-terminal` parses OSC 133/633 shell-integration markers for prompt and command boundaries, and the terminal view uses those boundaries alongside text classification from `oxideterm-terminal-semantic`.
### Local Terminal
Local terminal tabs run on the local machine. They validate renderer, keyboard input, shell startup, font configuration, and terminal settings before any remote host is involved.
Local terminal responsibilities:
- Start the configured local shell.
- Render output.
- Accept keyboard input.
- Handle resize.
- Apply terminal appearance settings.
- Apply terminal background and graphics settings without making them part of the terminal buffer.
- Detect terminal-native file-transfer prompts and privilege prompts without logging secrets.
- Keep local command state separate from remote SSH node state.
### SSH Terminal
SSH terminal tabs attach to a live node. They are consumers of an SSH connection, not the connection profile itself.
SSH terminal responsibilities:
- Present a shell channel.
- Maintain visible screen and scrollback context.
- Send input.
- Render output.
- Expose terminal observations to AI tools when approved.
- Report readiness and waiting-for-input hints.
- Reuse the node-owned SSH transport while keeping shell-channel state pane-local.
- Resolve privilege credential scope through the active terminal's owning node, not through host/title/prompt heuristics.
The terminal session interface also has Telnet, Mosh, serial, BLE and container-exec backends. They adapt their transport to terminal input, output, resize and lifecycle operations. BLE uses a GATT notification/write stream and shares serial send/display options; it does not acquire an SSH node merely to display terminal text. Transport-specific state lives in `oxideterm-terminal/src/session/` and the corresponding protocol crates.
### Terminal Rendering And Graphics
The terminal renderer combines several layers:
- The emulator text grid and scrollback.
- Cursor, selection, command marks, and inline hints.
- Terminal image protocols such as Kitty/Sixel/iTerm2.
- App-level background images, video, generated effects, opacity, and blur.
- Native whole-window opacity, applied separately from background-image opacity.
- Context-menu and command-bar overlays.
The emulator owns the text grid and scrollback. `oxideterm-terminal-graphics` tracks protocol images and their placements alongside grid events. Background media and application overlays belong to presentation state.
Kitty resources and placements are scoped to the normal or alternate screen. Entering the alternate screen clears its previous Kitty resources while retaining normal-screen images. Screen selection, erasure, scrolling, history trimming and reset update the corresponding graphics state. Sixel placements also follow grid changes and cell geometry. The renderer displays placements for the active screen; an ordinary screen switch is not a request to discard every protocol image.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
subgraph TerminalFlow["PTY and SSH output: protocol state, display caches and GPU submission"]
direction TB
Transport["oxideterm-terminal
local PTY and SSH terminal backends"]
Ingress["GraphicsIngress in oxideterm-terminal-graphics
ordered terminal bytes and graphics events"]
ShellMarks["Decode text and scan shell-integration markers
private OSC excluded from recordings"]
Parser["vte ANSI processor
shared components in oxideterm-terminal-emulator"]
TextGrid["alacritty_terminal
screen grid and compact history"]
Snapshot["TerminalPane stamps terminal-model snapshots
shared cells, stable line IDs and row signatures"]
Roles["Logical lines and semantic roles
command-mark snapshot version"]
RowLayout["Row layout in oxideterm-gpui-terminal-view
selection, cursor, links and theme"]
RunCache["Unchanged text runs
font shaping and paint-cache reuse"]
GlyphBatch["Prepared glyph batches
raster baseline, colors, live decorations"]
Scene["Scene construction
glyphs, image primitives, clipping, opacity"]
GPU["Platform GPU backend
submit and present"]
ProtocolImages["Protocol images and placements
screen, grid anchors, pixel leases"]
ImageCache["Image render cache
image version, crop, animation clock"]
Replies["Protocol reply bytes
return through the owning session"]
Visibility["Tab / detached window / lock / zoom
release hidden presentation resources"]
Background["Background media and UI overlays"]
end
Transport -->|"output bytes"| Ingress
Ingress -->|"Terminal byte segments"| ShellMarks
Ingress -->|"Image and placement events"| ProtocolImages
Ingress -->|"Graphics protocol replies"| Replies
ShellMarks --> Parser
ShellMarks -->|"command marks"| Roles
Parser --> TextGrid
TextGrid -->|"Terminal control replies"| Replies
Replies -->|"write back"| Transport
TextGrid --> Snapshot
TextGrid -.->|"Erase, scroll and screen changes"| Ingress
Snapshot --> Roles
Snapshot --> RowLayout
Roles --> RowLayout
RowLayout --> RunCache
RunCache --> GlyphBatch
GlyphBatch --> Scene
Scene --> GPU
ProtocolImages --> ImageCache
ImageCache --> Scene
Visibility -.->|"invalidate / rebuild"| RowLayout
Visibility -.->|"Rebuild display resources without losing protocol pixels"| ImageCache
Background --> Scene
```
Terminal drawing passes through these boundaries:
| Stage | Owner | Reuse and invalidation |
|---|---|---|
| Transport output and protocol parsing | `oxideterm-terminal`, `oxideterm-terminal-graphics`, `vte` and `alacritty_terminal` | Ordered graphics/control parsing feeds the text grid and graphics events. OSC payload scanning stops at BEL or ESC and preserves the storage limit and partial-input state. |
| Grid and history | `alacritty_terminal` | Writable rows use dense cells. History can use repeated-tail or packed storage when beneficial; read-only iteration does not expand compact rows. |
| Display snapshots | `oxideterm-terminal-model` defines the data; `oxideterm-terminal-emulator` builds snapshots from the grid | Rows share cell data through `Arc`, with stable line identities and paint-relevant signatures. |
| Row layout and text shaping | `TerminalLayoutCache` in `oxideterm-gpui-terminal-view` | Row keys include content, selection, cursor, theme and highlight state. When a row changes, unchanged text runs can retain shaping and paint caches if text, column, cell count and complete style match. Font size, cell width and line height changes invalidate run reuse. |
| Semantic roles | Terminal logical-line layout | Classification uses absolute logical-line ranges, active-input state and the immutable command-mark snapshot. A weak snapshot reference detects replacement without retaining command text. |
| Glyph batches and decorations | GPUI `LinePaintCache` | Prepared glyph data is reused while layout, colors, scale and renderer resources remain valid. Uniform full-run underlines and strikethroughs reuse glyphs and draw their strokes with current styles. Partial decorations use the general painter. |
| Protocol image display | Terminal image cache and GPUI image resources | Image identity, version and source crop determine cache reuse. Shared pixel leases track decoded memory; bounded display caches and visibility control renderer-resource retention. |
For glyphs that share a baseline and use integer vertical rasterization, the batch anchor is the rounded device baseline. Vertical scrolling can then translate the batch without repeating glyph preparation or changing rasterized positions. Glyphs with additional vertical shaping offsets retain device-phase invalidation. Prepared colors normalize hue once, while each draw applies current opacity. Blank cells avoid unused foreground conversion, and theme-default backgrounds reuse the converted background color.
The [row layout](../../../crates/oxideterm-gpui-terminal-view/src/element.rs), [GPUI glyph painter](../../../crates/gpui-pre/gpui/src/text_system/line.rs), [image cache](../../../crates/oxideterm-gpui-terminal/src/app/image_cache.rs) and [graphics/grid synchronization](../../../crates/oxideterm-terminal-graphics/src/graphics/grid.rs) own these boundaries.
### Privilege And File-Transfer Helpers
Privilege prompts and modem transfers are terminal-adjacent helpers, not ordinary typed text:
- Prompt detection watches the active terminal output.
- Secret submission uses a dedicated secret path and must not pass through plugins, AI context, logs, recordings, or shell history.
- Local privilege credentials are scoped to local terminal use; SSH privilege credentials are scoped through active terminal -> node -> saved owner.
- X/Y/ZMODEM byte-level state lives in `oxideterm-modem-transfer`; GPUI only asks for files/directories, displays progress, and writes protocol responses back to the current PTY/channel.
- Detection must stay conservative so normal command output and full-screen TUI redraws are replayed as terminal text unless protocol context is proven.
### Command Bar And Context Actions
The command bar and terminal context menu are workspace controls. They may send text, paste, select, search, trigger transfers, or route commands, but their state should not be inferred from the terminal title or prompt text. Selection actions operate on the terminal snapshot and renderer coordinates, while mutating actions route through explicit terminal/session APIs.
### Terminal Ownership Rule
Closing a terminal pane closes that pane. It should not be interpreted as deleting the saved connection profile. Depending on runtime state, other consumers such as SFTP, forwards, or IDE may still need the node or may need reconnect.
---
## SSH Connection Registry And Runtime
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Node["NodeRouter
logical node, parent route and policy"]
Registry["SshConnectionRegistry
connection identity and physical state"]
Shared["Shared physical connection"]
Dedicated["Dedicated consumer transport
separate registry key"]
Consumers["Registered consumers
terminal, SFTP, IDE, forwarding, monitor, router and others"]
External["Authorized Public MCP node lease
ConnectionConsumer::PublicMcp"]
Release["Release one consumer"]
Retain["Active consumer remains
keep the transport available"]
Idle["Shared transport has only idle owners
no consumers, or only node route bindings"]
Immediate["Retire the connection entry without an idle wait"]
Held["Remain idle
keep-alive or no timeout"]
Cleanup["Timeout rechecks connection ID, idle generation and owners
retire the eligible connection and any recorded descendants"]
Runtime["WorkspaceRuntimeEntity
node events, probes and reconnect jobs"]
Monitor["Connection Monitor
read-only runtime projection"]
Node --> Registry
Registry --> Shared
Registry --> Dedicated
Shared --> Consumers
Dedicated --> Consumers
External --> Consumers
Consumers --> Release
Release -->|"Still in use"| Retain
Release -->|"Shared and idle-eligible"| Idle
Release -->|"Unowned dedicated, broken or cancelled connection"| Immediate
Idle -->|"Ephemeral discovery transport without asset channels"| Immediate
Idle -->|"Keep-alive or no deadline"| Held
Idle -->|"Deadline reached"| Cleanup
Registry -->|"Physical-state events through NodeEventEmitter"| Runtime
Runtime -->|"Probe and reconnect update registry state"| Registry
Registry -->|"connection snapshots"| Monitor
```
The release path is based on registered consumers and connection identity, not foreground-tab visibility. A jump child retains its parent route while it needs that transport. Native OxideSens and plugin hooks are not separate `ConnectionConsumer` variants; an external Public MCP node lease is.
Implementation: [connection_registry](../../../crates/oxideterm-ssh/src/connection_registry.rs), [runtime_entity](../../../crates/oxideterm-gpui-app/src/workspace/runtime_entity.rs).
The SSH connection pool keeps remote runtime state separate from UI tabs.
### Responsibilities
- Track active, idle, stale, reconnecting, and failed connections.
- Share one connection across consumers where possible, or use dedicated transport for supported consumers when the node's channel strategy requires it.
- Own physical connection state, registry consumers, health probes, and idle reclamation.
- Expose connection snapshots to the workspace runtime and monitor surfaces.
- Keep reconnect scheduling in `WorkspaceRuntimeEntity`, not in the monitor surface.
### Consumer Model
```text
Shared SSH connection
|-- terminal consumer
|-- SFTP consumer
|-- forwarding consumer
|-- IDE consumer
|-- Public MCP node lease
`-- NodeRouter consumer
Dedicated consumer connection
`-- for example, a terminal or SFTP consumer with its own registry key and transport
Native AI and plugins use capability handles, host snapshots or hooks. The
registry can also track Monitor, X11Forward and MoshBootstrap consumers.
```
### Monitor Model
Connection Monitor reads registry and workspace-runtime state to answer:
- Which nodes are active?
- Which are reconnecting?
- Which have failed?
- Which registry consumers are attached?
- Which forwards or transfers need attention?
### Host Tools Model
Host Tools use the selected local machine or SSH connection. The native app mounts the surfaces and supplies window-input and terminal-launch hooks; resource commands run independently of any visible terminal pane.
Host Tools cover:
- Process lists and process actions.
- [Container and image management](workspace.md#manage-containers).
- [Redis endpoint discovery and key browsing](workspace.md#browse-and-edit-redis-keys).
- Services.
- tmux sessions, windows, and panes.
- Package inventory.
- System logs.
- Listening ports and exposure hints.
- Filesystem and disk usage.
- Scheduled tasks.
- CPU, memory, disk, GPU, and network metrics.
Architecture rules:
- `oxideterm-connection-monitor` owns sampler commands, parser logic, row signatures, filters, action command construction, and domain DTOs.
- `oxideterm-gpui-host-tools` owns tool views, the selected target, sampling and action state; the native host mounts those views and bridges workspace callbacks.
- Resource snapshots are runtime observations. They can refresh, become stale, or fail without mutating saved connection profiles.
- `ConnectionRegistry` owns physical SSH state, health probes, consumer bookkeeping, and idle cleanup.
- `WorkspaceRuntimeEntity` schedules active probes, handles node events, and starts or cancels reconnect jobs.
- `ForwardingRuntimeService` owns forwarding listeners and bridge tasks.
- The monitor surface owns neither SSH transport nor reconnect lifecycle.
- Heavy or repeated host sampling must not block terminal input or become the source of truth for SSH connection ownership.
### Host Tools Sampling And Actions
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Page["Host Tools rail and panels
selected host, tool and visibility"]
Owner["HostToolsEntity in oxideterm-gpui-host-tools
captures, interaction state and result delivery"]
Sample["Page-scoped resource and GPU samplers"]
Action["On-demand capture or user action"]
Container["Container builders in oxideterm-connection-monitor
Docker, Podman, nerdctl and wslc"]
Redis["Redis builders in oxideterm-connection-monitor
host, Docker or Podman redis-cli"]
Terminal["Workspace terminal bridge
interactive container exec and follow logs"]
Route["Host command target
local shell or selected SSH exec channel"]
SampleState["Profiler state or latest GPU sample"]
Reliable["Separate reliable queue
including container captures and Redis operations"]
Check["Parse output and accept only the matching request / target"]
Ui["Metrics, resource lists and action outcome"]
Page --> Owner
Owner --> Sample
Owner --> Action
Action --> Container
Action --> Redis
Action -->|"Other host captures and actions"| Route
Container -->|"Capture and action commands"| Route
Container -->|"Interactive command"| Terminal
Redis -->|"Discovery or stdin-backed browse and edit"| Route
Sample -->|"Local sample shell or SSH sampler"| SampleState
Route --> Reliable
Reliable --> Check
SampleState --> Ui
Check --> Ui
```
The paths distinguish periodic observations from user-requested results. Sampling traffic must not delay an operation result. Hiding a page changes sampling activity; it does not transfer SSH ownership to the page.
Implementation: [Host Tools state](../../../crates/oxideterm-gpui-host-tools/src/entity.rs), [desktop capture target](../../../crates/oxideterm-gpui-host-tools/src/entity/desktop.rs), [container discovery](../../../crates/oxideterm-connection-monitor/src/container/discovery.rs), [Redis operations](../../../crates/oxideterm-connection-monitor/src/redis.rs).
---
## SFTP Architecture
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Ui["SftpWorkspaceEntity in oxideterm-gpui-sftp
path, selection and preview state"]
Node["NodeRouter resolves the SSH node
browser and transfer backends retain route leases"]
Browse["SFTP browser session
shared node channel or dedicated SSH transport per policy"]
Preview["Preview limits and content renderer
bounded reads on a transfer channel, outside the download queue"]
Request["Transfer request
direction, file / directory, protocol"]
Manager["SftpTransferManager in oxideterm-sftp
transfer controls, concurrency and snapshots"]
Resolve["SSH transfer executor
saved or explicit protocol first, otherwise use preference"]
Sftp["SFTP transfer channel
resume from a supported offset"]
Scp["SCP transfer
exec channel on the resolved route; retries from byte zero"]
Control["Pause, resume, cancel or node interruption"]
Outcome["Progress and completion / error"]
ProgressStore["Persisted transfer progress
protocol, strategy and supported resume offsets"]
Resume["Reconnect / retry decision
SFTP offset or SCP from zero"]
Ui --> Node
Node --> Browse
Node -->|"Open a transfer channel for the preview"| Preview
Ui --> Request
Request --> Manager
Manager -->|"Register and acquire a permit"| Resolve
Node --> Resolve
Resolve -->|"Selected SFTP, or Auto opens SFTP"| Sftp
Resolve -->|"Selected SCP, or Auto finds no SFTP subsystem but SCP is supported"| Scp
Resolve -->|"Channel error or no supported protocol"| Outcome
Control --> Manager
Sftp --> Outcome
Scp --> Outcome
Sftp -->|"Persist supported progress"| ProgressStore
Scp -->|"Persist restart record"| ProgressStore
ProgressStore -->|"Find an eligible incomplete transfer"| Resume
Resume --> Request
```
Browsing and previews on the node use SFTP. SCP uses an exec channel on the transfer route. The manager owns transfer controls, and the progress store preserves resumable or retryable records independently of the visible progress row.
Implementation: [file-view state](../../../crates/oxideterm-gpui-sftp/src/state.rs), [route selection](../../../crates/oxideterm-gpui-app/src/workspace/sftp/runtime.rs), [SSH transfer executor](../../../crates/oxideterm-sftp/src/ssh_transfer.rs), [transfer manager](../../../crates/oxideterm-sftp/src/transfer_manager.rs).
The diagram shows the node-backed path. Standalone SFTP and FTP/FTPS reuse the file view but supply their own endpoint runtime. On an SSH route in Auto mode, SFTP is preferred; legacy SCP is selected only if the SFTP subsystem is unavailable and the host supports SCP. Users can also explicitly select SCP for transfers on a compatible route.
### Responsibilities
- Acquire SFTP access for a connected node.
- List directories.
- Preview files.
- Upload and download files.
- Write file content when explicitly requested.
- Manage transfer progress.
- Retry or reacquire transport after reconnect when supported.
SCP opens an exec channel from the existing `NodeRouter` connection handle. It never creates an independent SSH transport, follows node disconnect/cancel ownership, rejects unsafe control-record names, contains downloads under the chosen local target, and uses generated temporary siblings for single-file replacement. Capability probes are cached only for one live connection generation, including negative results.
### Directory Transfers
Directory transfers use a different execution path than single-file transfers. The app must distinguish:
- Single file upload.
- Single file download.
- Directory upload.
- Directory download.
- Background transfer state.
The transfer record stores the selected protocol. SFTP may restart from a saved byte offset. SCP can pause and resume only while the live channel remains open; after channel loss its persisted failed record is retryable from byte zero, not resumable from the recorded byte count.
### Safety Model
Remote file writes are real writes on the target host. Before overwriting important files, users should verify path, target, and backup state. AI and plugins should use explicit targets and approvals for file writes.
### Directory Strategy And Path Boundaries
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Request["Directory transfer
resolve SFTP or SCP on the live SSH connection"]
Sftp["SFTP directory strategy
honor the recorded strategy when resuming if still supported"]
Archive["Tar stream over SSH exec
unpack downloads within the local destination"]
Files["Directory scheduler
bounded per-file parallelism"]
Scp["Legacy SCP over SSH exec
send or parse bounded control records"]
Path["SCP download staging
validate received names and local containment before installing"]
Progress["Track bytes, completed items and actual strategy"]
Complete["Success
remove the resumable record"]
Cleanup["Cancellation or failure
stop current work; SCP retry starts from zero"]
Request -->|"SFTP"| Sftp
Request -->|"SCP is available and selected, directly or when Auto finds no SFTP subsystem"| Scp
Request -->|"no usable protocol"| Cleanup
Sftp -->|"tar supported and selected by profile or recorded strategy"| Archive
Sftp -->|"per-file strategy"| Files
Archive -.->|"new transfer fails for a reason other than transfer control"| Files
Archive -->|"cancel, interrupt or shut down without fallback"| Cleanup
Scp -->|"download"| Path
Scp -->|"upload"| Progress
Archive --> Progress
Files --> Progress
Path --> Progress
Progress -->|"success"| Complete
Progress -->|"cancel or fail"| Cleanup
```
Directory strategies are not interchangeable with single-file streaming. Capability caches are connection-scoped. SCP validates protocol names and destination containment before writes, and never interprets a persisted byte count as a resume offset.
Implementation: [directory_scheduler](../../../crates/oxideterm-sftp/src/session/directory_scheduler.rs), [tar_transfer](../../../crates/oxideterm-sftp/src/tar_transfer.rs), [paths](../../../crates/oxideterm-sftp/src/scp/paths.rs).
---
## IDE Architecture
The IDE has separate owners for project state, text editing, syntax analysis and file access. A project can be opened from an SSH node or by converting a terminal's current Shell environment. These entry points share the editor surface but have different transport and recovery lifetimes.
### Responsibilities
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Registry["IdeWorkspaceEntity in oxideterm-gpui-app
surface registry, node index, subscriptions"]
Surface["IdeSurface in oxideterm-gpui-ide
one project owner and async coordination"]
Model["IdeWorkspace in oxideterm-ide-core
transport-free project state"]
Editor["TextEditorView in oxideterm-gpui-editor
input, IME, viewport and drawing"]
Fs["Surface-scoped NodeAgentIdeFileSystem in oxideterm-ide-fs
selected backend"]
Tasks["IdeSurface-owned work
search, watching, backend preparation and file transfers"]
State["Project root, tree, tabs
saved versions, dirty and close state"]
Text["TextBuffer in oxideterm-editor-core
text, selection and undo"]
Lease["Node IDE: independent SSH consumer lease
Shell IDE: bound ShellChannel"]
Lifetime["Hidden mount suspends editor caches and watch work
project changes invalidate stale results"]
Registry -->|"register / restore / remove"| Surface
Surface -->|"owns"| Model
Surface -->|"owns per-tab views"| Editor
Surface -->|"dispatches file work"| Fs
Surface -->|"owns task lifecycle"| Tasks
Model --> State
Editor --> Text
Fs -->|"retains the scoped owner"| Lease
Tasks --> Lifetime
```
| Layer | Owned state and boundary |
|-------|--------------------------|
| `IdeWorkspaceEntity` in the app | Registers project surfaces by tab and node, retains subscriptions and close history, and coordinates reconnect. It does not own the SSH transport. |
| `IdeSurface` in `oxideterm-gpui-ide` | Owns one project's core model, editor views, file backend, search state, Markdown previews and background task handles. It applies asynchronous results to the current project. |
| `IdeWorkspace` in `oxideterm-ide-core` | Owns the root, file tree, editor-tab metadata, buffer snapshots, saved versions and dirty-close decisions. It has no GPUI, SSH or SFTP dependency. |
| `TextEditorView` and `oxideterm-editor-core` | Own interactive text, cursor and selection, undo/redo, find/replace, IME handling and viewport drawing. The surface synchronizes live text into the project model before save, close and snapshot operations. |
| `oxideterm-editor-syntax` | Computes syntax metadata from text snapshots. It neither paints GPUI elements nor changes editor text. |
| `oxideterm-ide-fs` | Implements file operations and owns scoped backend resources. Node-based IDE consumers share the connection through `NodeRouter`; terminal-bound IDEs use their selected Shell channel. |
### Editor And Syntax Pipeline
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Input["TextEditorView
keyboard, pointer, IME, find / replace"]
Buffer["TextBuffer
edit transaction and new text version"]
Grammar["Built-in grammar or EditorLanguagePlugins
grammar and query definitions"]
Request["Native syntax request for an active editor cache
skip large files and unavailable grammars"]
Schedule["One dedicated job per editor
while busy, keep only the latest request metadata"]
Worker["SyntaxSession in oxideterm-editor-syntax
parse a shared text snapshot, reusing the tree when the edit is consecutive"]
Check["Publish only with an active cache
generation, text version and language must match"]
Metadata["Highlight spans, folds
bracket pairs and indent guides"]
Viewport["Viewport and layout caches
visible rows, wrapping and selection"]
Paint["GPUI editor drawing"]
Owner["IdeSurface synchronizes editor text
before save, close and snapshots"]
Input --> Buffer
Buffer --> Request
Grammar --> Request
Request --> Schedule
Schedule -->|"take the snapshot when the job starts"| Worker
Worker --> Check
Check --> Metadata
Buffer --> Viewport
Metadata --> Paint
Viewport --> Paint
Buffer -->|"shared text"| Owner
```
`TextBuffer` supplies versioned text snapshots. The editor schedules Tree-sitter work on a background executor, using a built-in grammar or a loaded language plugin. Highlighting, folding, bracket matching and indent guides return as byte-range metadata. The foreground applies a result only when its generation, text version and language still match and the editor's render cache is active.
While syntax work is running, the editor retains the latest pending request instead of starting overlapping parsers. Hiding the editor invalidates pending syntax work and releases derived syntax/layout caches while retaining the buffer. Showing it schedules fresh syntax work. Large-file and missing-grammar paths can continue displaying text without syntax metadata.
IDE and SFTP editors share the search bar and search model. Search supports case sensitivity, regular expressions, multiline input, and capture-group replacement; terminal search uses the same matching capability with a single-line default. Text-input viewports keep caret, selection, and IME coordinates aligned, and editing histories belong to individual inputs. Markdown previews are owned by the project surface and rendered through the native Markdown renderer.
### Relationship To SFTP
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Node["Node project entry
node identity and selected access mode"]
Shell["Terminal conversion
current user, container and directory"]
Router["NodeRouter
IDE consumer on shared SSH connection"]
BoundShell["Bound ShellChannel
Commands or Agent only"]
Sftp["NodeSftpIdeFileSystem
node-backed SFTP subsystem"]
Channel["IDE-owned SSH channel
Commands or Agent, separate from the terminal pane"]
Commands["Pure Shell protocol
file operations and bounded search"]
Agent["Remote Agent RPC
files, search and symbol services"]
Watch["Directory watch
visible node project with a ready registered Agent session"]
Results["Typed file results and errors
text format and saved-file version"]
Tree["IDE file tree
upload or download a single file"]
Backend["Resolve the project's existing backend
a bound shell never falls back to the host node"]
Transfer["NodeAgentIdeFileSystem::transfer_file
overwrite policy, progress and cancellation"]
TransferSftp["Routed SFTP transfer
stage upload or download"]
TransferRpc["Bound Commands or Agent file RPC
requires single-file-transfer capability"]
FileResult["Commit a staged download
after upload, refresh the destination tree and eligible clean tab"]
TransferError["Report the current transfer failure
cancellation does not show an error"]
Node --> Router
Shell --> BoundShell
Router -->|"SFTP selected"| Sftp
Router -->|"Commands / Agent selected"| Channel
Channel --> Commands
Channel --> Agent
BoundShell --> Commands
BoundShell --> Agent
Sftp --> Results
Commands --> Results
Agent --> Results
Node -->|"when the backend supports watching"| Watch
Tree --> Transfer
Transfer --> Backend
Backend -->|"SFTP project"| TransferSftp
Backend -->|"bound RPC session"| TransferRpc
Backend -->|"binding unavailable or capability missing"| TransferError
TransferSftp -->|"success"| FileResult
TransferRpc -->|"success"| FileResult
TransferSftp -->|"failed or cancelled"| TransferError
TransferRpc -->|"failed or cancelled"| TransferError
```
The diagram shows explicitly selected file backends. SFTP is one implementation of file access; project state and editor buffers remain in the IDE owners. The core defines synchronous and asynchronous file-system contracts for reads, directory listings, version checks and writes. `LocalIdeFileSystem` also implements the local-disk contract, but the project surface shown here is wired through `NodeAgentIdeFileSystem`.
File-tree upload and download use the [same transfer entry point](../../../crates/oxideterm-ide-fs/src/agent/transfer.rs) across SFTP, Commands and Agent. The [IDE surface](../../../crates/oxideterm-gpui-ide/src/surface/transfer.rs) owns the progress and cancel controls; an older Agent needs the `single-file-transfer` capability before running a transfer.
| Access path | Environment and capabilities |
|-------------|------------------------------|
| Node + SFTP | Acquires the node's SFTP subsystem and an independent IDE consumer. Closing an unrelated terminal does not release this consumer. |
| Node + Commands or Agent | Opens an IDE-owned channel through the node. Commands provide Shell-based file operations; Agent provides RPC file operations and symbol services. |
| Terminal + Commands or Agent | Binds to the current Shell, retaining its user, container and working directory. It cannot substitute the node's SFTP or default exec environment. |
Pure Shell operations have bounded search execution and result sizes; writes retain version-conflict checks and restricted temporary-file permissions. Agent symbol-definition requests can locate and open a file at the returned line and column. Directory watching additionally depends on backend capability and is disabled for terminal-bound IDEs. Tree-sitter syntax metadata and Agent symbol lookup are separate paths; they do not constitute a general LSP client.
### Save, Close, And Recovery
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Trigger["Save request
manual, save-before-close, or autosave when switching away"]
Snapshot["Synchronize editor into IdeWorkspace
capture text, revision, format and file version"]
Serial["Serialize saves for this file tab
coalesce further save requests"]
Write["Backend write with expected version
atomic replacement when supported"]
Completion["Check project generation, file tab and file location
discard stale completions"]
Success["Write succeeded
compare current state with submitted snapshot"]
Conflict["Remote version conflict
cancel, reload or explicitly overwrite"]
Failure["Write failed
retain dirty text, stop queued saves and report error"]
Clean["No newer edits
mark clean; finish pending close if applicable"]
Dirty["Newer edits remain dirty"]
Pending["Use the latest buffer and new saved version"]
Reconnect["Node IDE reconnect snapshot
project path, open files, dirty text and file formats"]
Restore["Rebind the selected backend and restore buffers
do not overwrite a currently dirty buffer"]
Suppress["Skip a project explicitly closed after the snapshot"]
Trigger --> Snapshot
Snapshot --> Serial
Serial --> Write
Write --> Completion
Completion -->|"success"| Success
Completion -->|"conflict"| Conflict
Completion -->|"other error"| Failure
Success -->|"matches"| Clean
Success -->|"changed"| Dirty
Dirty -->|"a save is pending"| Pending
Pending --> Write
Reconnect -->|"project still eligible"| Restore
Reconnect -->|"last surface closed by user"| Suppress
```
File contents travel with their encoding, BOM and line-ending format, plus a saved-file version used for conflict checks. The surface selects atomic replacement only when the backend reports support. A successful write records the submitted text and revision; edits made during that write remain dirty. Repeated save requests are serialized and coalesced rather than issuing concurrent writes for the same tab. Configured autosave currently saves a dirty editor when switching away from its tab.
| Lifecycle event | State and cleanup rule |
|-----------------|------------------------|
| Close a dirty file or leave a project | The owner requests save, discard or cancel. A failed save or newer edits cannot silently complete a pending close. |
| Hide an IDE surface | Stop page sampling and directory watching; suspend hidden editor caches. Retain buffers and the node consumer. Visibility does not cancel user-requested file operations. |
| Node connection interrupted | Stop sampling/watch work, invalidate search results, mark the project disconnected and release its old backend consumer. The reconnect snapshot carries project path, open files, dirty text and file formats. |
| Restore a node IDE | Rebind the selected backend and restore the same project. An already-open different project or a project closed after the snapshot is not replaced. Snapshot dirty text is applied only to clean buffers, so newer local edits win. |
| Terminal-bound IDE | It is excluded from the node IDE reconnect snapshot. Its binding belongs to the source Shell; returning to the terminal follows the dirty-buffer decision path. |
| Release a surface | Cancel backend preparation and owned sampling/watch tasks; complete watch cleanup and release only this owner's resources. Other IDE or AI consumers keep their own leases. |
Reconnect snapshots are runtime recovery state, not proof that unsaved text has been written to disk. Generation checks prevent stale project/search/syntax completions from being applied to a replacement owner or newer request.
Implementation references: [app registry and reconnect](../../../crates/oxideterm-gpui-app/src/workspace/ide.rs), [surface lifecycle](../../../crates/oxideterm-gpui-ide/src/surface/lifecycle.rs), [editor actions and save completion](../../../crates/oxideterm-gpui-ide/src/surface/editor_actions.rs), [syntax scheduling](../../../crates/oxideterm-gpui-editor/src/surface/syntax_task.rs), [file-system contract](../../../crates/oxideterm-ide-core/src/filesystem.rs), and [backend binding](../../../crates/oxideterm-ide-fs/src/agent/binding.rs).
### User Rule
Before closing an IDE tab or reconnecting an unstable host, check unsaved buffers. Recovery can restore access and in-memory project state; saving or discarding edits remains a separate decision.
---
## Port Forwarding Architecture
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Rule["Saved rule or manual request
node identity, direction and endpoints"]
Tunnel["Standalone SSH tunnel profile
acquire its SSH route without a terminal"]
Service["ForwardingRuntimeService
node route, consumer binding and restoration"]
Route["NodeRouter
resolve transport without a terminal pane"]
Manager["ForwardingRegistry and node's ForwardingManager
oxideterm-forwarding"]
Local["Local listener
accepted socket to SSH direct channel"]
Remote["Remote bind request
forwarded channel to local endpoint"]
Socks["Dynamic listener
SOCKS target to SSH direct channel"]
Bridge["Rule owns its SSH consumer lease and bridge work"]
Snapshot["Saved rows and runtime states
traffic stats from active rules"]
View["ForwardingWorkspaceEntity feeds oxideterm-gpui-forwards"]
Stop["Stop, delete, node loss or app shutdown"]
Cleanup["Stop local listeners or cancel remote binds
stop bridge work and release rule leases"]
Restore["Rebind eligible rules on a replacement connection
honor stop or delete requests made after the snapshot"]
Rejected["Reject dedicated single-channel routes"]
Rule --> Service
Tunnel --> Service
Service --> Route
Route -->|"usable SSH connection"| Manager
Service -->|"single-channel strategy"| Rejected
Manager --> Local
Manager --> Remote
Manager --> Socks
Local --> Bridge
Remote --> Bridge
Socks --> Bridge
Service -->|"saved rules, even offline"| Snapshot
Manager -->|"runtime rule state"| Snapshot
Bridge -->|"active traffic"| Snapshot
Snapshot --> View
Stop --> Service
Service -->|"stop, remove or suspend"| Cleanup
Cleanup --> Snapshot
Restore --> Service
```
The service owns live listeners independently of UI mounts. Closing a terminal or hiding the forwarding page does not stop a rule. Stopping a saved rule does not connect its host just to perform cleanup; reconnect restoration must use the new connection identity.
Implementation: [runtime service](../../../crates/oxideterm-gpui-app/src/workspace/forwards/runtime_service.rs), [forwarding manager](../../../crates/oxideterm-forwarding/src/manager.rs), [view mount](../../../crates/oxideterm-gpui-app/src/workspace/forwards/mount.rs), [reconnect](../../../crates/oxideterm-gpui-app/src/workspace/forwards/reconnect.rs).
Port forwarding is a connection-level capability.
### Forward Types
- **Local**: local port to remote target.
- **Remote**: remote port to local target.
- **Dynamic**: SOCKS-style dynamic forwarding.
### Runtime Responsibilities
- Create listeners or remote forward requests.
- Track running, failed, stopped, or suspended state.
- Attach forwards to an owning node.
- Restore saved or suspended forwards when reconnect succeeds.
- Show actionable errors when ports conflict or connections fail.
### Auto-Start Rule
Use auto-start only for forwards that should start whenever the owning connection opens. Otherwise, start forwards manually from the forwarding surface.
---
## Remote Desktop and WSL Graphics
For application setup and viewer controls, see [RDP, VNC, and SPICE](desktop.md#remote-desktop).
A saved desktop profile distinguishes an explicitly empty password from an absent credential. The viewer intersects the session's clipboard preferences with the provider's capabilities before passing options to the worker. The actual SSH tunnel endpoint belongs to the active route, not the saved server identity.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Profile["Saved RDP/VNC/SPICE profile
metadata and secret references"]
Provider["Compatible, enabled marketplace helper
resolved by the trusted plugin registry"]
Gateway["Optional SSH gateway
ForwardingRuntimeService opens a loopback listener"]
Owner["RemoteDesktopSessionEntity in oxideterm-gpui-remote-desktop
owns the gateway lease, input and framebuffer"]
Worker["oxideterm-remote-desktop
child process and framed stdio"]
Helper["External RDP, VNC or SPICE helper"]
Spice["OxideSpice inside the SPICE helper
Main, Display, Inputs and Cursor
optional Playback, Record, USB, Smartcard and Port channels"]
Playback["Helper PCM playback
PcmS16LePlayback"]
Record["Helper microphone capture
SPICE Record uses PcmS16LeCapture; RDP has AUDIO_INPUT"]
Routing["Shared macOS HostAudioRoutingArbiter in the GUI process
AirPods automatic switching"]
Wsl["oxideterm-wsl-graphics
distro, VNC server and child processes"]
Vnc["WSL VNC endpoint"]
WslViewer["Built-in WSL Graphics viewer"]
X11["oxideterm-x11-forwarding
DISPLAY, xauth and channel bridge"]
XServer["Local X server"]
Profile --> Owner
Profile -->|"SSH gateway configured"| Gateway
Provider --> Owner
Gateway -->|"loopback endpoint and scoped lease"| Owner
Owner -->|"StartConnect, input and session requests"| Worker
Worker -->|"starts helper and writes requests"| Helper
Helper -->|"frames and events"| Worker
Worker -->|"frame and event delivery"| Owner
Helper <-->|"SPICE adapter exchanges requests and events"| Spice
Helper -->|"remote audio when enabled and supported"| Playback
Record -->|"local PCM when capture is separately enabled and supported"| Helper
Owner -->|"playback activity acquires or releases a lease"| Routing
Routing -->|"AudioRoutingReady for the helper's audio generation"| Worker
Wsl -->|"starts and owns the VNC server"| Vnc
WslViewer <-->|"direct RFB, independent of marketplace helpers"| Vnc
X11 <-->|"bidirectional X11 channel bridge"| XServer
```
Graphics sessions are visual runtime surfaces. They are separate from terminal buffers even when a terminal or command launches the remote visual program.
Visual remoting has three related but separate ownership paths:
- **WSL Graphics**: `oxideterm-wsl-graphics` owns WSL distro probing, VNC server startup, desktop/app child processes, and cleanup.
- **Remote Desktop**: `oxideterm-gpui-remote-desktop` owns viewer state; `oxideterm-remote-desktop` owns the helper worker and binary protocol. The worker starts the separately installed RDP, VNC or SPICE executable selected by the trusted plugin registry. Supported helpers use `oxideterm-pcm-audio` for playback or capture; on macOS the GUI process separately coordinates system routing for active playback.
- **SSH X11 forwarding**: `oxideterm-x11-forwarding` owns DISPLAY, xauth, fake-cookie, setup rewrite, and SSH X11 channel bridge semantics; it is not a full desktop viewer.
### Responsibilities
- Track graphics sessions separately from terminal tabs.
- Start or reconnect the backing graphics session through the graphics runtime.
- Connect the GPUI viewer to the backing framebuffer source.
- Route keyboard, pointer, and scroll input to the viewer worker.
- Keep rendered frames as viewer state, not terminal output or scrollback.
### Ownership Rule
WSL Graphics manages its own VNC server and child processes. Its built-in viewer connects to that VNC endpoint, separately from plugin-backed VNC connections.
For RDP/VNC/SPICE, `oxideterm-connections` manages saved profiles and secret references. When a profile selects an SSH gateway, the session leases a tunnel through that SSH node. The worker receives its transport endpoint separately from the saved server identity. See [host and helper development](../../development/remote-desktop.md) for frame recovery and input ownership.
Display layout and viewer fitting are separate. With an active multi-monitor layout, window resizing changes local fitting without replacing the topology. With one monitor, the viewer can request a remote resolution based on its viewport.
### Frame Delivery And Helper Lifetime
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Session["RemoteDesktopSessionEntity
tab identity and current worker generation"]
Worker["Remote desktop worker
helper startup, requests and shutdown"]
Engine["Trusted RDP / VNC / SPICE helper
protocol engine outside app"]
Frames["Background event reader
normalize pixels to opaque BGRA"]
Queue["Bounded frame delivery queue
base frame and dirty regions"]
Hidden["Hidden without observers
keep latest usable frame only; worker stays alive"]
Recovery["Missing lineage or queue overflow
request a new base frame"]
Validate["Drain bounded batches for current worker
drop stale graphics epochs and wait for a fresh base after reset"]
View["GPUI viewer
framebuffer and input coordinates"]
Mcp["Public MCP frame snapshot
from the same session framebuffer"]
Watch["Visible viewer or active Public MCP frame observer"]
Input["Keyboard and pointer input
click to capture in relative mode, send deltas
Escape or focus loss releases the grab"]
Close["Close or replace worker
release remote input state, then stop and reap helper"]
Session --> Worker
Worker --> Engine
Engine --> Frames
Frames --> Queue
Watch -->|"enable bounded presentation"| Queue
Queue -->|"when not presenting"| Hidden
Queue -->|"delta chain needs recovery"| Recovery
Hidden -->|"retained frame cannot recover the chain"| Recovery
Recovery -->|"current session sends RequestFrame"| Worker
Queue -->|"ready to present"| Validate
Validate --> View
Validate --> Mcp
Input --> Session
Close --> Session
```
The frame queue keeps input dispatch independent of rendering. The viewer waits for a base frame in the new graphics epoch and discards events from retired workers. An active Public MCP frame observer keeps frame delivery enabled even when the viewer is hidden. A helper is retired before its executable is replaced.
Implementation: [worker](../../../crates/oxideterm-remote-desktop/src/worker.rs), [frame queue](../../../crates/oxideterm-remote-desktop/src/frame_queue.rs), [session lifecycle](../../../crates/oxideterm-gpui-remote-desktop/src/session/lifecycle.rs), [viewer frame state](../../../crates/oxideterm-gpui-remote-desktop/src/state.rs), [workspace session bridge](../../../crates/oxideterm-gpui-app/src/workspace/remote_desktop/session.rs).
### Remote Layout Versus Local Fitting
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Connect["Connect or reconnect
start helper with initial size and supported topology"]
Change["Display topology change
all-monitors option and provider support must both be on"]
Layout["Skip empty or unchanged layouts
adapt a one-monitor update to the viewport"]
Window["Measured viewport or window size change"]
Follow["Follow window size
deduplicate and debounce automatic resize"]
Manual["Fit current window or choose a resolution
fixed resolution turns off Follow window size"]
Resize["Remote Resize request
connected, negotiated support and no active multi-monitor layout"]
Remote["Helper and server negotiate remote dimensions"]
FitMode["Stretch to fill toggle"]
Fit["Local paint bounds and input mapping
do not request a remote resize"]
Connect -->|"StartConnect"| Remote
Change --> Layout
Layout -->|"UpdateDisplayLayout"| Remote
Window --> Fit
FitMode --> Fit
Window -->|"following enabled"| Follow
Follow --> Resize
Manual --> Resize
Resize -->|"Resize"| Remote
```
In single-monitor mode, a fixed resolution stops automatic viewport following. In multi-monitor mode, a change in active displays recomputes the topology; a transient empty layout during hotplug leaves the last layout in place.
Implementation: [layout and resize lifecycle](../../../crates/oxideterm-gpui-remote-desktop/src/session/lifecycle.rs), [viewer controls](../../../crates/oxideterm-gpui-remote-desktop/src/session/panel.rs), [layout model](../../../crates/oxideterm-remote-desktop/src/model.rs).
---
## Reconnect And Recovery
When several opens need the same SSH route, connection-chain and node locks serialize conflicting work. Pending reconnects wait for the active chain; a pane becoming visible is not a reason to start another transport.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Detect["Link down with reconnect enabled
for nodes not supplied by discovery"]
Owner["WorkspaceRuntimeEntity
debounce roots and own reconnect jobs by node"]
Snapshot["Capture the affected subtree
old connection IDs, terminal sessions, forwards and IDE"]
Grace["Read incomplete transfer records and probe old SSH transport"]
Recovered["Keep the recovered transport
drain waiting terminal opens and restore forwarding session"]
Connect["Reconnect root, then link-down descendants along the parent route
bounded retries"]
Identity["Reject stale job or connection completions"]
Terminals["Rebind SFTP and Public MCP node leases
remount terminal panes"]
Restore["Restore forwarding rules when needed
then resume pending transfers and restore IDE"]
Report["Record stage outcomes and notify the user"]
Cancel["User disconnect / removal / shutdown"]
Stop["Cancel owned attempts and probes
reject late completions"]
Manual["Manual terminal reconnect on an ordinary node"]
Pane["Reuse a ready route or queue the pane to reopen
connect missing hops when needed"]
Discovery["User reconnect for a discovered SSH target"]
Resolve["Ask the discovery provider again
validate the current request and compare resolved access identity"]
ExistingNode["Start a replacement transport on the original node
capture its state before reconnecting"]
Separate["Offer a separate session if identity changed or cannot be matched
never rebind the original node in that case"]
Detect --> Owner
Owner --> Snapshot
Snapshot --> Grace
Grace -->|"old connection still current and alive"| Recovered
Grace -->|"expired or lost"| Connect
Connect -->|"connected"| Identity
Connect -->|"exhausted or failed"| Report
Identity -->|"current"| Terminals
Terminals --> Restore
Recovered --> Report
Restore --> Report
Cancel --> Stop
Manual --> Pane
Discovery --> Resolve
Resolve -->|"same access identity"| ExistingNode
ExistingNode --> Identity
ExistingNode -->|"replacement failed"| Report
Resolve -->|"different or unconfirmed access identity"| Separate
Resolve -->|"stale or failed provider request"| Report
```
The runtime coordinates recovery and rejects late results after cancellation or job replacement. A discovered SSH node uses an explicit provider re-resolution path rather than the saved-connection grace retry. AI and plugin callers reacquire resources through their own runtime boundaries.
Implementation: [reconnect owner](../../../crates/oxideterm-gpui-app/src/workspace/runtime_entity.rs), [SSH recovery stages](../../../crates/oxideterm-gpui-app/src/workspace/tabs/nodes.rs), [discovered SSH reconnect](../../../crates/oxideterm-gpui-app/src/workspace/discovery/open.rs).
Reconnect is a workflow across several subsystems, not a terminal-only event.
### Recovery Inputs
A recovery attempt may need:
- Node state.
- Connection status.
- Terminal panes.
- SFTP transfers.
- Forward rules.
- IDE workspaces.
- Notifications and errors.
### Conceptual Pipeline
```text
detect stale state
-> snapshot affected consumers
-> attempt reconnect
-> recreate or refresh terminal access
-> restore forwards
-> resume or retry transfers
-> reopen or refresh IDE state
-> update monitor and notifications
AI and plugin capability handles are not direct reconnect stages. They observe
node or connection generation changes through their runtime boundary and must
invalidate, refresh, or reacquire resources on a later call.
```
### User Workflow
1. Open Connection Monitor.
2. Identify the affected node.
3. Reconnect or wait for reconnect.
4. Refresh SFTP, IDE, forwarding, or AI target state.
5. Verify any write, transfer, or command result.
---
## Settings And Persistence
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Ui["oxideterm-gpui-settings-view
desktop settings drafts and edit requests"]
Cli["CLI settings mutation"]
Model["Desktop SettingsStore
in-memory PersistedSettings"]
CliGuard["Normalize and check the diff
warnings, dry run or no changes do not write"]
Write["SettingsStore or save_settings_to_path
sanitize under a lock and atomically replace the file"]
File["settings.json envelope
schema version, settings and timestamp"]
Apply["Desktop applies settings to runtime owners
theme, terminals and other features"]
Secret["Discovery source secret input"]
Store["Stage new secrets in the credential store
persist only revision references"]
Error["Storage rejects invalid or unreadable input
or returns a write failure"]
Ui -->|"ordinary preference edits"| Model
Model -->|"ordinary edits apply immediately; external edits apply after reload"| Apply
Model -->|"save"| Write
Cli --> CliGuard
CliGuard -->|"approved write with changes"| Write
Write -->|"saved"| File
Write -->|"persistence error"| Error
File -->|"desktop watcher reloads external changes"| Model
Secret --> Store
Store -->|"save discovery source metadata"| Write
```
Shared persistence does not mean an external CLI mutation immediately changes every mounted view. The desktop must load and apply the new state. Secret values use their own store; settings retain only the safe metadata or reference.
Implementation: [settings view](../../../crates/oxideterm-gpui-settings-view/src/lib.rs), [store](../../../crates/oxideterm-settings/src/store.rs), [normalization](../../../crates/oxideterm-settings/src/normalize.rs), [desktop runtime apply](../../../crates/oxideterm-gpui-app/src/workspace/root/runtime_settings.rs), [CLI settings](../../../crates/oxideterm-cli/src/settings.rs).
Settings are durable application state. The desktop Settings surface is the primary way to edit them interactively.
### Settings Domains
- General app behavior.
- Appearance and theme.
- Terminal behavior.
- Local terminal behavior.
- Terminal graphics, background images, and transfer helpers.
- SSH behavior.
- Privilege credentials.
- SFTP behavior.
- IDE behavior.
- AI providers and model settings.
- AI memory, tool use, and Knowledge embedding or retrieval settings.
- Plugins.
- Cloud sync.
- Portable runtime.
- Keybindings.
- Help and update channel.
### Persistence Rule
Settings should store configuration, not secret values. Secret fields should write to secret-aware storage.
Privilege credential entries are split: labels, prompt matchers, enabled state, and saved-node scope are configuration; passwords or equivalent secret values must be stored only through the secret-aware boundary.
### CLI Relationship
The CLI companion is the script and maintenance entry point for the shared
persistent model. It covers settings, connections, forwards, plugins, quick
commands, secrets, portable bundles, diagnostics, reports, batch plans,
backups, and cloud sync. The CLI can ask the desktop app to open a terminal
or connection; the desktop process owns their runtime state. Mutating commands
normally use dry-run plans and `--yes` confirmation. For exploratory or visual
configuration, use the desktop Settings surface.
---
## Cloud Sync, Backups, And Portable Bundles
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Start["Manual or configured automatic Cloud Sync v3
with the configured scope"]
Recover["Recover any pending local journal
on the live configuration owners"]
Prepare["CloudSyncOperationService
operation permit and PreparedSync"]
Replica["Cloud Sync v3
local replica and encrypted remote publications by writer"]
Plan["Plan summary and conflict candidates
default to Upload with no remote, or Download on first sync with remote history"]
Review["Review direction and conflict choices"]
Apply["PreparedSync.apply
re-read live owners and merge scoped fields"]
Journal["If configuration changes, journal before writing owners and committing replica
otherwise save only the replica"]
Refresh["Queue a refresh for affected runtime owners"]
Finish["AppliedSync.publish
finish download or process pending publication"]
Publish["Persist pending encrypted .oxide publication
upload and confirm; keep pending record if upload fails"]
Prune["Prune this writer's superseded remote publications when eligible
report pending cleanup if a remote delete fails"]
Outcome["Local apply, download, publication, conflicts and pending work
separate results"]
Error["Report recovery, prepare, apply or publication failure"]
Start --> Recover
Recover --> Prepare
Prepare --> Replica
Replica --> Plan
Plan -->|"manual, first sync or conflicts"| Review
Review -->|"confirmed choices"| Apply
Plan -->|"automatic, past first sync, no conflicts"| Apply
Apply --> Journal
Journal --> Refresh
Journal --> Finish
Finish -->|"upload or merge with publication needed and local cleanup clear"| Publish
Finish -->|"download or local cleanup pending"| Outcome
Finish -->|"upload or merge, local cleanup clear, no new publication"| Prune
Publish -->|"confirmed"| Prune
Prune --> Outcome
Recover -->|"recovery failed"| Error
Prepare -->|"prepare failed"| Error
Apply -->|"apply failed"| Error
Publish -->|"publication failed"| Error
```
Cloud Sync v3 applies local values and publishes remote data separately. It rereads live stores before merging, so edits made during network work participate in the merge. Each v3 publication is a replica snapshot encrypted with the sync password. Sync can read older structured backups for migration. A download does not write to the remote backend; if publication fails after local apply, the staged publication remains available for retry.
Implementation: [prepare, apply and publish](../../../crates/oxideterm-cloud-sync/src/operation/synchronize.rs), [v3 publication format](../../../crates/oxideterm-cloud-sync/src/sync_v3/publication.rs), [recovery journal](../../../crates/oxideterm-cloud-sync/src/sync_v3/recovery.rs), [desktop causal sync](../../../crates/oxideterm-gpui-cloud-sync/src/runtime/causal.rs).
Cloud sync, backups, and `.oxide` bundles operate on persisted state, not on live terminal bytes.
### Cloud Sync
Cloud sync aligns selected local state with a configured remote backend. The
current model supports WebDAV, HTTP JSON, Dropbox, OneDrive, Google Drive,
GitHub Gist, S3, and Git backends, with selectable sync partitions. Automatic
upload, conflict blocking, sync history, and up to five local rollback backups
are local state-machine behavior. UI and CLI use the same structured sync
model; live nodes and terminal buffers are not sync objects. It should be
inspectable before direction-changing actions such as push, pull, apply, or
conflict resolution.
### Backups
Backups protect users before high-impact changes:
- Bulk imports.
- Sync apply.
- Restore.
- Plugin migration.
- Settings migration.
- Portable bundle import.
### Portable Bundles
`.oxide` bundles are encrypted portable exports. They can contain connections, forwards, settings, plugin settings, quick commands, and optional portable secrets.
### Review Rule
Every import, restore, or sync apply should be previewable. Support bundles should be reviewed before sharing.
### Portable Import And Rollback
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Export["Export selected durable configuration
with optional credentials"]
Bundle["Encrypted .oxide bundle"]
Preview["Portable import preview
decrypt and inspect conflicts and sections"]
Import["Apply selected profiles and connection credentials
checkpoint the connection store first"]
Rollback["On core write failure, restore the checkpoint
and roll back prepared profile credentials"]
Extras["Apply selected forwards, Quick Commands, app and plugin settings,
and auxiliary secrets through their owning stores"]
ImportResult["Portable import summary
including errors from individual stores"]
ImportError["Report preview or core import error"]
Backup["Existing local Cloud Sync rollback backup"]
RestorePreview["Decrypt with the sync password
build a legacy import preview"]
Restore["Apply selected restore through the legacy .oxide import"]
RestoreResult["Restore summary or error"]
Export --> Bundle
Bundle --> Preview
Preview -->|"confirm selection and conflict policy"| Import
Preview -->|"cannot preview bundle"| ImportError
Import -->|"core import succeeded"| Extras
Import -->|"core write failed"| Rollback
Extras -->|"for portable import"| ImportResult
Rollback -->|"for portable import"| ImportError
Backup --> RestorePreview
RestorePreview -->|"confirm selection"| Restore
RestorePreview -->|"cannot preview backup"| RestoreResult
Restore -->|"core import succeeded"| Extras
Restore -->|"core write failed"| Rollback
Extras -->|"for backup restore"| RestoreResult
Rollback -->|"for backup restore"| RestoreResult
```
Portable import checkpoints the connection store before applying connection and credential changes. Restoring a Cloud Sync rollback backup is a separate preview-and-apply path; the backup is distinct from the Cloud Sync v3 recovery journal.
Implementation: [portable import view and workers](../../../crates/oxideterm-gpui-connections/src/session_manager/oxide_transfer.rs), [connection import](../../../crates/oxideterm-connections/src/oxide_file/transfer/import.rs), [desktop import stores](../../../crates/oxideterm-gpui-app/src/workspace/session_manager/oxide_actions.rs), [Cloud Sync restore](../../../crates/oxideterm-gpui-cloud-sync/src/runtime/operations.rs).
---
## OxideSens AI Architecture
The [conversation view](../../../crates/oxideterm-gpui-ai/src/conversation.rs) presents tool approvals, choices and usage. The [tool loop](../../../crates/oxideterm-ai/src/tool_loop/mod.rs) coordinates provider turns and child tasks. A child asks its parent for input; tool permissions still apply when a turn resumes.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Turn["OxideSens conversation and user request"]
Skills["Agent Skills catalog"]
NativePrompt["Provider prompt and history
scoped context, retrieval and input budget"]
AcpPrompt["Redacted ACP prompt
conversation handoff, scoped memory, current context and request"]
Stream["oxideterm-ai provider loop
sanitize message text, stream events and iterate tool calls"]
Acp["AcpWorkspaceEntity in oxideterm-gpui-ai
manages agent processes, sessions and protocol turns"]
Bridge["oxideterm-acp-host-tools
one bridge per conversation, authority for the active turn only"]
Tools["Shared application tool dispatcher
policy, approval and live target validation"]
Delivery["Apply events only to their conversation and stream generation"]
Transcript["Assistant text, usage and tool results"]
Cancel["Stop the current turn
invalidate the stream and revoke tool authority"]
Close["Close ACP thread
release its tool bridge and session"]
Turn --> NativePrompt
Turn --> AcpPrompt
Skills --> NativePrompt
Skills -->|"catalog changed for this conversation and agent"| AcpPrompt
NativePrompt --> Stream
AcpPrompt --> Acp
Stream --> Tools
Acp --> Bridge
Bridge --> Tools
Tools -->|"result for the next model round"| Stream
Tools -->|"reply to the originating MCP call"| Bridge
Stream --> Delivery
Acp --> Delivery
Tools --> Delivery
Delivery --> Transcript
Cancel --> Stream
Cancel -->|"send protocol cancellation"| Acp
Close --> Acp
```
Native provider requests and ACP sessions use separate prompt builders and transports. ACP reasoning options remain session configuration. The ACP host-tools bridge accepts calls for the active turn and passes them through the same application tool policy as provider tool rounds. This bridge is independent of the Public MCP endpoint for external clients.
Implementation: [provider turns](../../../crates/oxideterm-gpui-ai/src/conversation/provider.rs), [ACP turns](../../../crates/oxideterm-gpui-ai/src/conversation/acp_turn.rs), [ACP workspace](../../../crates/oxideterm-gpui-ai/src/acp.rs), [ACP host tools](../../../crates/oxideterm-acp-host-tools/src/runtime.rs).
OxideSens is a workspace-aware assistant. It uses configured providers and local app context; it does not require an OxideTerm account.
Agent Skills are a bounded instruction layer for repeatable workflows. The AI runtime discovers `SKILL.md` catalogs, loads full instructions and resources only on demand, and records the loaded skill hash in conversation metadata. Loading a skill does not grant runtime authority; terminal, file, credential, network, and other actions still require the existing capability and approval checks.
The chat surface also resolves a provider-aware reasoning level for the selected model. Known models are normalized against capability data; an unknown model with a known provider uses that provider's request format, while an unknown provider is treated as unsupported.
OxideSens has two execution backends. The native provider backend streams the
configured model protocol directly; the ACP backend uses an independent agent
process, ACP session, model selection, and session configuration. They share
the application context, policy, and UI, but their transport, tool injection,
reasoning configuration, and lifecycle are different. ACP does not use the
native provider's `reasoning_effort` field; its options belong to the ACP
session configuration.
### Context Sources
- Conversation history.
- Current terminal context.
- Saved connections.
- Live nodes.
- Terminal sessions.
- SFTP targets.
- IDE workspaces.
- Settings summaries.
- RAG knowledge collections.
- MCP resources and tools.
- Previous tool results.
### Orchestrator Tool Model
The AI tool layer exposes high-level app tools rather than arbitrary internal APIs. Examples include:
- Target discovery and selection.
- Connect target.
- Run command.
- Observe terminal.
- Send terminal input.
- Read resource.
- Write resource.
- Transfer resource.
- Open app surface.
- Get state.
- Recall or remember preferences.
### Approval Model
AI actions are classified by risk:
- Read-only.
- Interactive.
- Execute.
- Write.
- Destructive.
Writes, terminal input, command execution, file changes, and destructive operations should be explicit and reviewable. Secrets should never be pasted into prompts.
### Tool Authority And Result Flow
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Proposal["Application tool call from a provider turn or the ACP bridge"]
Preflight["Check exposed tool and argument shape
run live-target preflight for UI tools"]
Policy["Tool policy
operation risk, arguments and safety mode"]
Approval["Wait for user approval
show the operation and redacted arguments"]
Resolve["Recheck turn authority and live resource capability
before dispatching UI tools"]
Reject["Return rejection or cancel the request
without dispatching the operation"]
Owner["Dispatch to real domain owner
terminal, node, file, IDE or settings"]
Result["Structured result and safe error"]
Caller["Provider tool result or ACP bridge reply"]
Record["Turn status and applicable audit evidence"]
Proposal --> Preflight
Preflight -->|"accepted"| Policy
Preflight -->|"invalid"| Reject
Policy -->|"denied"| Reject
Policy -->|"approval needed"| Approval
Policy -->|"allowed without prompt"| Resolve
Approval -->|"not approved"| Reject
Approval -->|"approved"| Resolve
Resolve -->|"invalid or stale"| Reject
Resolve -->|"valid"| Owner
Owner --> Result
Result --> Record
Result --> Caller
Reject --> Record
Reject -->|"if the caller is still waiting"| Caller
```
Approval and capability validation answer different questions. Permission to attempt an action does not make an old target reference current. A denial or stale reference terminates the execution branch; the transcript can still record that outcome.
Implementation: [provider tool rounds](../../../crates/oxideterm-ai/src/tool_loop/round.rs), [ACP tool calls](../../../crates/oxideterm-ai/src/tool_loop/acp.rs), [policy](../../../crates/oxideterm-ai/src/policy.rs), [live target authority](../../../crates/oxideterm-ai/src/runtime_context/authority.rs).
---
## Plugin Architecture
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Package["Installed package and manifest"]
Registry["Plugin registry
compatibility, enable state and permission review"]
Gate["Eligible runtime plan"]
Blocked["Activation withheld
incompatible, disabled or awaiting permission review"]
Metadata["Manifest-only contributions"]
Runtime["Process or Wasm extension
scoped host API and UI contributions"]
Discovery["Active process discovery provider
device-local source catalog and open requests"]
DiscoveryTerminal["Local PTY using the provider's declared terminal entry"]
DiscoverySsh["Desktop opens native SSH
only established host-owned sessions survive provider failure"]
Grammar["Language package
grammar / queries and editor refresh"]
Helper["Resolve feature, protocol version and verified executable
outside the ordinary plugin supervisor"]
Desktop["Remote desktop session owner
RDP / VNC / SPICE binary protocol"]
Mosh["Mosh session owner
terminal-transport protocol"]
Acp["ACP workspace owner
direct ACP stdio session"]
Feature["SSH authentication task
security-key helper"]
Retire["Disable, update or remove"]
Cleanup["Invalidate contributions and discovery registrations
retire affected runtimes and feature-owned helpers"]
Package --> Registry
Registry -->|"not eligible"| Blocked
Registry -->|"eligible"| Gate
Gate --> Metadata
Gate --> Runtime
Gate --> Grammar
Gate --> Helper
Runtime -->|"active process with declared provider"| Discovery
Discovery -->|"terminal launch result"| DiscoveryTerminal
Discovery -->|"SSH launch result"| DiscoverySsh
Helper --> Desktop
Helper --> Mosh
Helper --> Acp
Helper --> Feature
Retire --> Cleanup
```
Editors consume language resources, ordinary extensions run through the plugin host, and specialized helpers are started and stopped by the features that use them. Process discovery providers populate a device-local catalog; when a target opens an SSH session, the desktop node runtime owns its transport. Compatibility checks apply both to installed packages and marketplace version selection.
Implementation: [runtime classification](../../../crates/oxideterm-plugin-registry/src/validation.rs), [compatibility](../../../crates/oxideterm-plugin-registry/src/compatibility.rs), [plugin lifecycle](../../../crates/oxideterm-gpui-app/src/workspace/plugin_entity.rs), [discovery runtime](../../../crates/oxideterm-gpui-app/src/workspace/plugin_entity/discovery.rs), [editor resources](../../../crates/oxideterm-editor-syntax/src/plugin.rs).
Plugins extend the app through manifest-declared capabilities and host-provided surfaces.
### Components
- Plugin manifest.
- Plugin registry.
- Plugin host API.
- Plugin settings.
- Plugin secrets.
- Plugin UI surfaces.
- Plugin lifecycle events.
### Boundary Rules
- Plugin settings are not plugin secrets.
- Plugin UI should use the host-provided API.
- Plugin errors should be isolated from the main workspace.
- Plugin permissions should be reviewed before enabling a plugin.
- A plugin should not receive unrelated app internals by default.
### Host Calls And Activation Lifetime
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Instance["Active extension instance"]
Call["Host API call, outbound effect or runtime registration"]
Gate["Host API permission check and registration validation"]
Denied["Protocol error or rejected message"]
Snapshot["Read a scoped host snapshot or obtain a domain result"]
Response["Return the response to the plugin runtime"]
Mutation["Queue an application effect"]
Owner["Workspace adapter and feature owner
apply the effect to the target"]
Confirm["Confirmation request
return the user's decision"]
Delivery["Apply runtime contributions and subscriptions
ignore pushes from retired instances"]
Ui["Declarative surfaces and event subscriptions"]
Storage["Ordinary plugin settings and local storage"]
Secrets["Plugin-scoped credential store
sensitive response for secret reads"]
Instance --> Call
Call --> Gate
Gate -->|"denied"| Denied
Gate -->|"read or synchronous domain call"| Snapshot
Gate -->|"explicit confirmation call"| Confirm
Gate -->|"allowed secrets call"| Secrets
Gate -->|"queued effect"| Mutation
Gate -->|"runtime contribution or subscription"| Delivery
Mutation --> Owner
Snapshot --> Response
Confirm --> Response
Secrets --> Response
Delivery -->|"current instance"| Ui
Owner -->|"ordinary storage or settings effect"| Storage
```
Host snapshots do not grant unrestricted access to the app. Calls are capability-scoped, late results from retired instances are rejected, and settings remain separate from secrets. A visible plugin panel is not an SSH transport owner.
Implementation: [host API snapshot](../../../crates/oxideterm-gpui-app/src/workspace/plugin_lifecycle/host_api_snapshot.rs), [runtime host](../../../crates/oxideterm-plugin-host-api/src/runtime.rs), [scoped delivery and cleanup](../../../crates/oxideterm-gpui-app/src/workspace/plugin_entity.rs).
### Dynamic Plugin Discovery Data Flow
Enabled discovery sources ask their plugin providers to list targets. `oxideterm-discovery` keeps a catalog snapshot per source in memory. The workspace publishes those entries to the session tree, which groups them by source and any provider-defined subgroups, and to the command palette, which shows them in a Discovery section with each entry's source name.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Provider["Discovery plugin provider"]
Catalog["oxideterm-discovery in-memory catalog"]
Tree["Session tree: grouped by source"]
Palette["Command palette: discovery results with source names"]
Existing["Reconnect an existing discovery session"]
Target["Check the current source and target"]
Open["Reuse eligible SSH session or launch PTY or SSH from provider result"]
Refresh["Ask the provider to resolve the target again"]
Pty["Replace PTY in the original pane; keep input broadcast membership and reapply triggers"]
Ssh["Restore transport on the original SSH node if the access identity matches"]
Provider -->|"list and refresh"| Catalog
Catalog --> Tree
Catalog --> Palette
Tree -->|"open target"| Target
Palette -->|"open target"| Target
Existing --> Target
Target -->|"opening"| Open
Target -->|"reconnecting"| Refresh
Refresh --> Pty
Refresh --> Ssh
```
Both views open targets by source and target ID. The workspace can reuse an eligible live SSH session or ask the provider for a fresh launch. Reconnecting asks the provider to resolve the target again. For a plugin terminal, the workspace replaces the PTY in the original pane, preserves scrollback and input broadcast membership, and reapplies output triggers. For an SSH transport reconnect, it restores the existing node's transport only if the provider returns the same access identity.
Source settings can persist, but discovered targets and their session origins live only in memory. Refreshing or removing a source changes its catalog independently of saved connections; opening or reconnecting a target does not write a profile to the persistent connection store.
Implementation: [in-memory catalog](../../../crates/oxideterm-discovery/src/catalog.rs), [workspace publication](../../../crates/oxideterm-gpui-app/src/workspace/discovery.rs), [session tree catalog](../../../crates/oxideterm-gpui-connections/src/session_manager/catalog.rs), [command palette](../../../crates/oxideterm-gpui-app/src/workspace/command_palette.rs), [open and reconnect](../../../crates/oxideterm-gpui-app/src/workspace/discovery/open.rs), [plugin launch and PTY replacement](../../../crates/oxideterm-gpui-app/src/workspace/plugin_entity/discovery/open.rs).
---
## CLI Companion Boundary
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Cli["oxideterm CLI
parsed command and structured arguments"]
Manage["Persistent-state management"]
Plan["Write guard
dry run or confirm and optionally back up before writing"]
Store["Shared domain stores
settings, profiles, backups and sync"]
Secrets["Secret input / resolution
secret-aware storage only"]
Open["terminal, ssh, open or connections open
pass a launch request to the desktop"]
Desktop["Desktop session owner
local terminal or connection startup"]
Bridge["mcp bridge
stdio client to loopback HTTP"]
Endpoint["oxideterm-public-mcp
client authentication and tool-group checks"]
Prepared["For a saved Quick Command in standard mode,
prepare the target and arguments on the host"]
Approval["ApprovalStore freezes the typed action
the original MCP request waits for the app decision"]
Abandoned["Discard the frozen action if the request closes"]
Rejected["MCP error; do not dispatch the action"]
Broker["DomainBroker rechecks client authorization
oxideterm-public-mcp-host receives the typed request"]
Native["Background domain work or desktop window action"]
Node["NodeRouter
shared live SSH nodes"]
Reply["MCP tool result"]
Result["CLI output and exit status"]
Cli --> Manage
Manage -->|"read or validate"| Store
Manage -->|"guarded write"| Plan
Plan -->|"confirmed write"| Store
Plan -->|"dry run, no changes or error"| Result
Secrets --> Store
Cli --> Open
Open --> Desktop
Open -->|"launch handoff"| Result
Cli --> Bridge
Bridge --> Endpoint
Endpoint -->|"standard mode and approval required"| Approval
Endpoint -->|"no approval required or unattended mode"| Broker
Endpoint -->|"scope or mode denied"| Rejected
Endpoint -->|"standard saved Quick Command"| Prepared
Prepared -->|"confirmation required"| Approval
Prepared -->|"confirmation not required"| Broker
Prepared -->|"preparation failed"| Rejected
Approval -->|"approved, consume frozen action once"| Broker
Approval -->|"denied, expired or revoked"| Rejected
Approval -->|"original request cancelled"| Abandoned
Broker -->|"authorization changed"| Rejected
Broker --> Native
Native -->|"for SSH operations"| Node
Native --> Reply
Rejected --> Reply
Reply --> Bridge
Store --> Result
```
Management commands operate on persisted stores. A GUI launch hands the request to the desktop; the desktop owns the connection and any authentication prompts. Public MCP authenticates and scopes client requests before dispatching to the host. The host routes background work and actions that need a live desktop window separately, while SSH operations reuse the app's node router.
Implementation: [CLI commands](../../../crates/oxideterm-cli/src/main.rs), [stdio bridge](../../../crates/oxideterm-cli/src/mcp.rs), [Public MCP service](../../../crates/oxideterm-public-mcp/src/service.rs), [host dispatch](../../../crates/oxideterm-public-mcp-host/src/background.rs), [desktop window adapter](../../../crates/oxideterm-gpui-app/src/workspace/public_mcp.rs).
The `oxideterm` CLI companion shares configuration and data paths with the desktop app, but it is not the primary interactive interface.
Use the CLI for:
- Headless diagnostics.
- CI validation.
- Scripted settings changes.
- Connection export or validation.
- Backup and restore automation.
- Cloud sync automation.
- Support bundle generation.
- Portable bundle validation.
`connections open` opens a saved SSH profile, `ssh` opens a temporary SSH terminal, `open` hands a connection URI to the desktop, and `terminal` opens a local terminal. `mcp bridge` connects a stdio client to the running app's authenticated loopback MCP endpoint.
### Public MCP Host, Approval, and Local Takeover
An external MCP client sends requests over stdio to `oxideterm mcp bridge` from `oxideterm-cli`. The bridge forwards them to the desktop app's loopback HTTP endpoint. `oxideterm-public-mcp-host` owns the endpoint and client policy; its `oxideterm-public-mcp` service authenticates the bearer credential and checks the required tool groups before dispatch.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Client["External MCP client"]
Bridge["oxideterm mcp bridge"]
Endpoint["Public MCP endpoint: client authentication and tool-group policy"]
Approval["Desktop approval: original request waits"]
Stop["End the request without executing the action"]
Broker["DomainBroker: recheck authorization"]
Host["oxideterm-public-mcp-host dispatch"]
Window["GPUI workspace adapter"]
Terminal["Terminal session"]
Sftp["Background SFTP work"]
Command["Background SSH command"]
Operation["operation_ref: query status or request cancellation"]
Gesture["Remote desktop gesture: validate graphics_epoch"]
Local["Local keyboard or mouse input"]
Release["Interrupt the gesture and release pressed keys and buttons"]
Client -->|"stdio"| Bridge
Bridge -->|"loopback HTTP"| Endpoint
Endpoint -->|"unauthorized"| Stop
Endpoint -->|"approval required in standard mode"| Approval
Endpoint -->|"authorized without per-call approval"| Broker
Approval -->|"approved; consume frozen action once"| Broker
Approval -->|"rejected, expired or cancelled"| Stop
Broker -->|"authorization changed"| Stop
Broker --> Host
Host --> Window
Host --> Sftp
Host --> Command
Window --> Terminal
Window --> Gesture
Sftp -->|"transfer started"| Operation
Command -->|"command started"| Operation
Local -->|"take over during a gesture"| Release
Gesture -->|"cancelled or invalidated while active"| Release
```
In standard mode, a high-risk call that requires approval is frozen in `ApprovalStore`, and the original request waits for the user's decision in OxideTerm. Approval consumes the frozen action once; rejection, expiry, or cancellation of the original request prevents dispatch. Unattended mode skips per-call approval but still enforces tool-group policy, and `DomainBroker` rechecks authorization before handing off the typed request.
The host dispatches terminal and remote desktop actions through the GPUI workspace adapter and handles SFTP and SSH command work in the background. A started SSH command or SFTP transfer can return an opaque `operation_ref` for checking status or requesting cancellation; both require the same client and the originating tool group. Cancelling a running operation does not undo effects already applied.
A remote desktop gesture validates `graphics_epoch` before sending input, as it sends each event, and before returning a matching frame. Local keyboard or mouse input in that desktop interrupts the active gesture and releases pressed keys and buttons before taking over; the interrupted task cannot send further input or release keys belonging to the user.
Implementation: [stdio bridge](../../../crates/oxideterm-cli/src/mcp.rs), [endpoint and client policy](../../../crates/oxideterm-public-mcp-host/src/endpoint.rs), [request policy and approval](../../../crates/oxideterm-public-mcp/src/service.rs), [background dispatch and operations](../../../crates/oxideterm-public-mcp-host/src/background.rs), [desktop adapter](../../../crates/oxideterm-gpui-app/src/workspace/public_mcp/desktops.rs), [gesture execution](../../../crates/oxideterm-gpui-remote-desktop/src/session/gesture.rs).
---
## Security Design
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Input["Credential input
passwords, keys, tokens"]
SecretBoundary["Short-lived secret buffers
zeroize at the owning boundary"]
Use["Authorized authentication or protocol use"]
Vault["System credential store or encrypted portable keystore"]
Metadata["Ordinary settings and profile data
metadata and secret references"]
Sync["Cloud Sync v3 replica
selected configuration fields and any selected credential records"]
Credentials["Separate credential resources
collect only within the enabled sensitive sync scope"]
Publication["Serialize and seal the entire publication
upload the staged ciphertext"]
Context["Selected terminal, file and workspace context"]
Ai["Scope and sanitize text before building AI context"]
Diagnostic["Audit fields, support bundle and CLI status"]
Projection["Audit redaction; reports use summaries, hints and revisions"]
Plugin["Authorized plugin secret call"]
SensitiveReply["Sensitive response to that plugin only"]
Input --> SecretBoundary
SecretBoundary --> Use
SecretBoundary -->|"when saved"| Vault
Metadata -->|"resolve reference when needed"| Vault
Vault -->|"load through a secret owner"| SecretBoundary
Metadata --> Sync
Vault -->|"when sensitive credential sync is enabled"| Credentials
Credentials --> Sync
Sync --> Publication
Context --> Ai
Diagnostic --> Projection
Plugin -->|"plugin-scoped account"| Vault
Vault -->|"for an authorized plugin read"| SensitiveReply
```
Cloud Sync v3 encrypts the entire publication. Credentials appear as separately scoped records only when sensitive credential sync is enabled. The Public MCP client registry also has its own boundary: it stores a digest of each bearer credential rather than a reusable token.
[`oxideterm-security-key`](../../../crates/oxideterm-security-key/src/lib.rs) delegates SSH signing to a FIDO2 hardware key through a signing helper: the private key stays on the device, and the PIN is held in short-lived zeroizing buffers and never written to disk. [`oxideterm-app-lock`](../../../crates/oxideterm-app-lock/src/lib.rs) stores an Argon2id verifier rather than the unlock password and supports unlocking through the system's biometric prompt where available.
Implementation: [connection credential storage](../../../crates/oxideterm-connections/src/keychain.rs), [v3 publication](../../../crates/oxideterm-cloud-sync/src/sync_v3/publication.rs), [Public MCP client authentication](../../../crates/oxideterm-public-mcp/src/auth.rs).
### Secret Categories
- SSH passwords.
- Private key passphrases.
- Cloud sync tokens.
- AI provider keys.
- Plugin tokens.
- Portable bundle passwords.
- Environment-derived credentials.
### Storage Rules
- Navigation metadata is not secret storage.
- Secret fields should use keychain-backed or secret-aware storage.
- CLI secret writes should prefer stdin or environment variables.
- Support bundles should contain hints and status, not raw values.
- AI context should be redacted before leaving the app boundary.
### Output Boundaries
Treat these as output boundaries:
- AI prompts.
- Tool-call payloads.
- Logs.
- Support bundles.
- Plugin messages.
- Cloud sync snapshots.
- CLI JSON output.
---
## Performance Design
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Session["Terminal session and emulator
consume bytes and maintain terminal state"]
Snapshot["Current terminal snapshot"]
Visibility["WorkspaceTabHostEntity
mounted tab surfaces, workspace lock and pane zoom"]
ShellPane["oxideterm-gpui-terminal pane"]
Hidden["Clear pane layout cache and suspend display images"]
Retained["Keep the session, protocol image pixels and animation clocks"]
Layout["oxideterm-gpui-terminal-view
check frame, row and text-run keys"]
Reuse["Reuse matching frame or row layouts and shaped runs"]
Rebuild["Rebuild invalidated layouts or shape changed runs"]
Scene["Paint and batch glyphs and other drawing into the GPUI scene"]
Background["Feature-owned workers
I/O, sync, AI and sampling"]
Budget["Feature-specific delivery and UI refresh"]
Session --> Snapshot
Snapshot --> ShellPane
Visibility --> ShellPane
ShellPane -->|"hidden"| Hidden
Hidden --> Retained
ShellPane -->|"visible"| Layout
Layout -->|"cache hit"| Reuse
Layout -->|"invalidated"| Rebuild
Reuse --> Scene
Rebuild --> Scene
Background --> Budget
```
These are separate cost centers: parsing, snapshot generation, layout, scene construction and presentation. Cache reuse depends on content, style and metrics; visibility controls presentation resources rather than transport ownership. CPU microbenchmarks cannot establish whole-window latency or cross-platform gains.
Implementation: [terminal pane](../../../crates/oxideterm-gpui-terminal/src/app.rs), [view rendering](../../../crates/oxideterm-gpui-terminal-view/src/element/frame.rs), [tab visibility](../../../crates/oxideterm-gpui-app/src/workspace/tabs/entity.rs), [delivery](../../../crates/oxideterm-gpui-app/src/workspace/delivery.rs).
### Terminal Responsiveness
Terminal hot-path work should avoid:
- Blocking disk I/O.
- Cloud sync work.
- Backup generation.
- Large plugin scans.
- Long AI summarization.
- Heavy settings serialization.
The tab host derives render-cache visibility from the active tab, detached windows, workspace lock and pane zoom. A hidden terminal releases row layouts, retained glyph batches and prepared display images; its terminal session, protocol pixels and animation clocks remain owned by the runtime/pane. Showing it again rebuilds presentation resources from current state. Hiding a pane does not disconnect its shared SSH node.
The rendering path above is shared across supported platforms. Measurements distinguish parsing, snapshot generation, row layout, scene construction and GPU presentation. CPU benchmark results alone do not establish input-to-display latency or performance on another platform. See [Performance and Benchmarking](../../development/performance-and-benchmarking.md) for paired workloads, results and retained or rejected experiments.
### Virtualized Views
Large lists such as files, transfers, connections, plugin entries, or logs should use stable row dimensions and virtualization where appropriate.
### Background Work
Long-running operations should show progress and avoid blocking the main workspace:
- SFTP transfers.
- X/Y/ZMODEM transfers.
- Host resource sampling.
- Remote desktop and WSL Graphics frame updates.
- Cloud sync.
- Backups.
- AI provider calls.
- Plugin loading.
- Remote file previews.
---
## Detailed Module Structure
This section maps the user-visible architecture to the native module layout. The purpose is not to document every file, but to make ownership clear enough that a user or contributor can understand where a behavior belongs.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
App["oxideterm-gpui-app
workspace composition and host adapters"]
Layout["WorkspaceTabHostEntity mounts surfaces
oxideterm-gpui-shell supplies shell UI"]
Runtime["WorkspaceRuntimeEntity
terminal bindings, pending opens, probes and reconnect jobs"]
Nodes["oxideterm-ssh NodeRouter
node readiness and capability routing through NodeRuntimeStore"]
Registry["SshConnectionRegistry
transport handles and consumer leases"]
Remote["Feature-owned GPUI entities and views
file manager, SFTP, IDE, forwards and host tools"]
Term["oxideterm-gpui-terminal and oxideterm-gpui-terminal-view
terminal panes and shared canvas"]
Graphics["oxideterm-gpui-remote-desktop and oxideterm-remote-desktop
viewer and external protocol helpers"]
AiTools["oxideterm-gpui-ai, oxideterm-ai and oxideterm-acp-host-tools
chat, provider and ACP turns"]
Plugins["PluginWorkspaceEntity
registry, host API, runtime and discovery delivery"]
PublicMcp["oxideterm-public-mcp and oxideterm-public-mcp-host
external tools and domain dispatch"]
Persist["GPUI settings and Cloud Sync views
settings and sync interaction"]
Core["Domain services
SFTP, IDE core and filesystem, forwarding, connection monitoring"]
Stores["Settings, connection and Cloud Sync stores"]
Knowledge["Knowledge workspace in oxideterm-gpui-ai
document and index state"]
App --> Layout
App --> Runtime
App --> Remote
App --> AiTools
App --> Plugins
App --> PublicMcp
App --> Persist
App --> Knowledge
Layout --> Term
Layout --> Graphics
Runtime --> Nodes
Runtime --> Registry
Nodes --> Registry
Remote --> Core
Core -->|"for node-backed operations"| Nodes
PublicMcp --> Nodes
Persist --> Stores
```
This map locates implementation responsibilities. The tables below identify the concrete files; the subsystem diagrams explain channel acquisition, mutation and cleanup. A line to a domain family is not permission for every UI module to open a transport directly.
Implementation: [workspace](../../../crates/oxideterm-gpui-app/src/workspace.rs), [runtime_entity](../../../crates/oxideterm-gpui-app/src/workspace/runtime_entity.rs), [entity](../../../crates/oxideterm-gpui-app/src/workspace/tabs/entity.rs).
### GPUI Workspace Modules
| Module | Responsibility | User-Visible Result |
|---|---|---|
| `workspace.rs` and `workspace/root/*` | Compose the top-level workspace and construct app services; long-lived node/reconnect ownership lives in `workspace/runtime_entity.rs` and domain crates | The app opens into one coherent desktop workspace without making the root view the owner of every transport |
| `workspace/tabs/*` | Create, select, render, and reconnect tab-bound views | Terminal, SFTP, IDE, and utility pages can be opened, closed, and restored independently |
| `workspace/pane_tree.rs` | Hold split-pane layout state | Users can arrange work without changing the underlying node or session ownership |
| `workspace/sidebar/*` | Render activity navigation and mount the session and AI sidebars | Navigation stays stable while the active work surface changes |
| `oxideterm-gpui-connections/src/session_manager` · `workspace/session_manager/*` | Catalog state, group and selection actions, import/export dialogs; the app applies changes to its stores and live sessions | Users can create, edit, import, export, and organize connection records |
| `oxideterm-gpui-connections/src` · `workspace/new_connection/*` | Owns drafts, host-key and interactive prompts, form submission and preflight decisions; the app starts real sessions and handles window focus | First connection setup is a guided desktop workflow, not a CLI-only path |
| `oxideterm-gpui-host-tools/src` · `workspace/connection_monitor/*` | Renders host tools and retains their state; the workspace provides the target and runtime access | Users can see connected nodes, resource status, host entities, reconnect state, and actionable failures |
| `oxideterm-gpui-sftp/src` · `workspace/sftp/*` | Renders remote file browsing and transfers; workspace adapters resolve the live file session | SFTP is a node-level file manager, not a terminal add-on |
| `oxideterm-gpui-file-manager/src` · `workspace/file_manager/*` | Owns local browsing and file views; the workspace connects them to windows and tabs | Local file workflows use the same desktop patterns as remote files |
| `workspace/graphics.rs` and `workspace/graphics_vnc.rs` | Render graphics sessions, connect the VNC viewer, and route pointer/keyboard input | Visual remote workflows are separate app surfaces, not terminal scrollback |
| `workspace/remote_desktop/*` | Resolve remote desktop targets, open viewer tabs, and bridge provider/helper lifecycle into the workspace | RDP/VNC/SPICE sessions use the same tab shell while keeping protocol work outside the app crate |
| `workspace/runtime_entity.rs` | Own long-lived node subscriptions, reconnect workers, runtime shutdown, and terminal-consumer bookkeeping | Closing a terminal consumer does not accidentally close a shared node or transport |
| `workspace/ide.rs` and IDE crates | Open folders, route file operations, and manage editor state | Remote editing is presented as a workspace, not as raw SFTP operations |
| `oxideterm-gpui-forwards/src` · `workspace/forwards/*` | Owns rule views and editing; the forwarding service manages listeners | Port forwarding is visible and recoverable from the desktop app |
| `oxideterm-gpui-settings-view/src` · `workspace/settings/*` | Renders settings pages and holds page-local interaction state; the workspace applies settings to active services | Configuration is app-first and persists through the shared settings model |
| `oxideterm-gpui-cloud-sync/src` · `workspace/cloud_sync/*` | Owns sync forms, selection, preview and progress; the workspace applies changes to shared stores | Cloud sync and backup operations are explicit and reversible where possible |
| `workspace/plugin_entity.rs`, `plugin_manager.rs`, `plugin_lifecycle/*`, `plugin_ui.rs` | Coordinate plugin discovery, lifecycle, host API snapshots, settings, secrets, and UI host calls | Plugins can extend app surfaces without owning core runtime state |
| `oxideterm-gpui-ai/src` · `workspace/sidebar/ai/*` | Owns the transcript, model selection and conversation UI; workspace adapters resolve live targets and window actions | OxideSens appears as an integrated workspace assistant with explicit tool boundaries |
| `workspace/acp_workspace.rs` and `oxideterm-acp-*` integration | Coordinate ACP agent configuration, sessions, model options, and ACP host-tool bridging beside the native provider path | ACP sessions have an independent agent/session lifecycle and are not ordinary provider streams |
| `workspace/terminal_context_actions.rs` | Build terminal context-menu actions for selection, search, transfers, and command routing | Terminal actions share app menu style while still dispatching through explicit session APIs |
| `oxideterm-gpui-quick-commands/src`, `workspace/quick_commands.rs`, and `workspace/terminal_command_bar/` | The feature view manages saved commands and editing; the workspace sends commands to the target terminal and handles command-line completion | Repeated terminal actions become reusable desktop controls |
| `oxideterm-gpui-command-sender` · `workspace/terminal_command_bar/sender.rs` · `oxideterm-gpui-web/src/host/sender.rs` | The native desktop and the separate Web/WASM target share sending drafts, expanded controls, paced sends, target snapshots, cancellation and progress | Each build binds existing panes to write callbacks. Running jobs keep those targets across tab changes and do not open SSH connections |
| `oxideterm-gpui-background`, `workspace/local_terminal_background.rs` and `workspace/root/background.rs` | The feature crate renders images and plays background media; the workspace selects and mounts the layer | Backgrounds do not change terminal buffer content |
| `oxideterm-gpui-audit` and `workspace/audit.rs` | The audit view manages activity, session summaries and offline recording playback; the app provides the playback pane and export file picker | Replaying a recording does not reopen a live session |
| `workspace/notification_center.rs` | Collect and render actionable app notifications | Background failures and recovery actions are visible without blocking terminal input |
| `oxideterm-gpui-onboarding/src` and `workspace/onboarding/` | The feature view presents first-run setup; the workspace applies the choices | Users can configure the main app without starting from CLI documentation |
### SSH Domain Modules
| Module | Responsibility | Architectural Boundary |
|---|---|---|
| `oxideterm-ssh/src/config.rs` | Define SSH connection configuration and validation-facing types | Saved metadata is kept separate from live transport handles |
| `connection_registry.rs` | Track reusable SSH connections and pool identity | Multiple consumers can share a node without each owning a socket |
| `router.rs` and `router/node_router.rs` | Route work to nodes and enforce node identity | User actions target nodes, not incidental terminal tabs |
| `router/runtime_store.rs` | Store in-process node state and export topology snapshots | `WorkspaceApp` helpers persist snapshots; runtime handles, terminal endpoints, and live identities are rebuilt rather than serialized |
| `router/events.rs` | Publish node and connection events | UI and tools receive state changes without polling every domain directly |
| `reconnect.rs` | Describe reconnect policy and retry behavior | Disconnects become recoverable lifecycle events where possible |
| `monitor.rs` | Convert lower-level state into monitor-facing health | Connection Monitor can show health without exposing transport internals |
| `host_key.rs` | Handle host-key verification semantics | Trust decisions stay explicit and auditable |
| `transport/auth.rs` | Handle password, key, agent, and keyboard-interactive authentication paths | Credential collection is isolated from ordinary UI state |
| `transport/client.rs`, `connection.rs`, `handler.rs`, `output.rs` | Open SSH clients, channels, handlers, and output streams | Terminal and file consumers share transport behavior but keep separate view state |
| `transport/paths.rs`, `signers.rs` | Resolve SSH paths and signing helpers | Key material and path resolution stay in the transport layer |
### Connection Monitor And Host Tools Modules
| Module | Responsibility | Architectural Boundary |
|---|---|---|
| `oxideterm-connection-monitor/src/profiler.rs` | Own sampling cadence, shell setup, timeout limits, and profiler state | Sampling is runtime observation, not saved connection data |
| `metrics.rs`, `summary.rs`, `stats.rs` | Parse metrics and build compact monitor rows | UI rows are derived from structured snapshots, not raw command text |
| `process.rs` | Filter, sort, display, and build actions for processes | Process actions are explicit host-tool commands, not terminal keystrokes |
| `docker.rs`, `service.rs`, `tmux.rs` | Model host managers and their actions | Manager-specific parsing stays in the monitor domain |
| `package.rs`, `log.rs`, `port.rs`, `filesystem.rs`, `scheduled_task.rs` | Sample package inventory, logs, ports, filesystems, and scheduled tasks | Resource tools can fail independently without changing SSH node ownership |
### SFTP Domain Modules
| Module | Responsibility | Architectural Boundary |
|---|---|---|
| `oxideterm-sftp/src/session.rs` | Own high-level SFTP session behavior | File browsing is tied to a node-level session |
| `session/basic.rs` | Provide basic session operations | Simple operations use one consistent session entry point |
| `session/file_ops.rs` | Implement read, write, rename, delete, and metadata operations | Mutating file operations stay outside UI rendering code |
| `session/preview.rs` and `preview_helpers.rs` | Build safe previews for text, media, and unsupported content | Preview logic is separated from transfer logic |
| `session/transfers.rs` | Bridge sessions to upload/download operations | Transfers reuse node/session state instead of terminal commands |
| `transfer_manager.rs` | Track transfer queue, status, progress, and cancellation | Users can inspect and cancel long-running file operations |
| `progress.rs` | Represent progress events and byte counts | UI progress is structured rather than parsed from text |
| `retry.rs` | Centralize retry decisions | Recoverable network failures do not need ad hoc UI retries |
| `tar_transfer.rs` | Handle directory transfers through archive-based paths where appropriate | Directory upload/download can remain efficient and progress-aware |
| `path_utils.rs` | Normalize and validate remote paths | Remote path behavior stays consistent across SFTP and IDE |
| `types.rs` and `error.rs` | Define common SFTP DTOs and errors | UI surfaces can display precise errors without depending on implementation details |
### AI Domain Modules
| Module | Responsibility | Architectural Boundary |
|---|---|---|
| `chat.rs` and `types.rs` | Define conversation and message types | UI transcript state is based on structured records |
| `context_window.rs` | Decide what fits into the model context | Token budgeting is centralized instead of scattered through the sidebar |
| `context_sanitizer.rs` | Redact sensitive values before model or tool boundaries | AI context is an output boundary |
| `key_store.rs` | Store provider keys through the native secret store or the portable keystore | Provider credentials stay out of normal settings text |
| `providers/*` and `streaming/*` | Discover models, select providers, build requests, and parse streaming responses | Provider differences are hidden behind shared streaming semantics |
| `reasoning.rs` | Normalize reasoning levels against provider and known-model capabilities | Unsupported provider formats are not emitted; ACP uses session options instead |
| `acp/*` | Own ACP transport, agent lifecycle, session configuration, and protocol state | ACP is a separate execution backend from native model providers |
| `orchestrator.rs` | Define orchestrator tool names, schemas, and dispatch contracts | Tool definitions remain stable for model-facing behavior |
| `policy.rs` | Decide which tool actions need approval or rejection | Dangerous or state-changing actions are not executed solely because a model requested them |
| `persistence.rs` | Store conversations and AI durable state | Long-running chat history survives app restarts where configured |
| `profiles.rs` and `settings.rs` | Manage AI profiles and settings | Model/provider choices are user configuration, not hardcoded defaults |
| `rag/*` | Persist, chunk, embed, index, and search knowledge documents | Retrieval and durable document state are domain services, not workspace rendering logic |
| `mcp/*` | Manage MCP registry, process startup, and protocol types | External tool servers are isolated from core app state |
| `references.rs`, `slash.rs`, `suggestions.rs` | Provide references, slash commands, and suggestions | Assistant input helpers remain separate from provider transport |
### Persistence, Settings, Plugin, And Sync Crates
| Area | Native Owner | Notes |
|---|---|---|
| Settings | `oxideterm-settings`, `oxideterm-settings-model`, `oxideterm-gpui-settings-view` | Settings are loaded and saved through shared models, then rendered by GPUI pages |
| Saved connections | `oxideterm-connections`, `oxideterm-gpui-connections` | Connection records are durable; active nodes are runtime objects |
| Forwarding | `oxideterm-forwarding`, `oxideterm-gpui-forwards` | Rules are configuration; listeners are runtime state |
| Privilege credentials | Settings privilege page, terminal privilege prompt, secret-aware storage | Scope and prompt matchers are configuration; secret values stay outside ordinary settings |
| Terminal modem transfers | `oxideterm-modem-transfer`, `oxideterm-gpui-terminal` modem worker | Protocol state is terminal-runtime work; file selection and progress are UI concerns |
| Graphics sessions | `oxideterm-wsl-graphics`, `oxideterm-remote-desktop`, `oxideterm-gpui-remote-desktop`, marketplace `plugins/rdp`, `plugins/vnc`, and `plugins/spice`, app graphics/remote-desktop modules | WSL lifecycle, remote protocol helpers, viewer framebuffer, and terminal buffers have separate owners |
| Plugins | `oxideterm-plugin-*`, plugin manager and lifecycle modules | Manifests, settings, host API calls, and plugin secrets have separate boundaries |
| Cloud sync | `oxideterm-cloud-sync`, `oxideterm-gpui-cloud-sync`, app cloud-sync modules | Sync plans, backup creation, and apply steps are explicit control-plane operations |
| Portable runtime | `oxideterm-portable-runtime`, settings portable-runtime modules | Portable metadata and encrypted payload handling are separate from normal settings pages |
| Notifications | `oxideterm-notification-center`, app notification module | Background status is surfaced as actionable notifications |
| CLI companion | `oxideterm-cli` | CLI reads and mutates shared state for automation, but does not replace the desktop workflow |
### Why This Split Matters
The module split preserves four user-visible invariants:
1. A view can be closed without destroying the underlying durable object.
2. A runtime object can recover without rewriting the saved profile.
3. A background operation can fail without blocking terminal input.
4. A secret can be used for authentication or provider access without becoming ordinary app text.
---
## Data Flow Walkthroughs
### First Launch And Local Terminal
```text
app start
-> load settings
-> initialize workspace state
-> render onboarding or main workspace
-> create local terminal tab
-> attach local PTY
-> stream output to terminal renderer
```
The local terminal path is intentionally short. It should not wait for cloud sync, plugin scans, AI provider discovery, or remote connection checks.
### Saved SSH Connection Open
```text
Sessions
-> select saved connection
-> load the profile, then reuse a compatible node or open a new one
-> on a new connection, resolve authentication and verify the host key
-> wait for the node and terminal channel to become ready
-> open SFTP alongside the terminal if requested
```
The saved profile remains durable metadata. The runtime can materialize a node and queue its terminal before the transport is ready, including along a jump-host chain.
```mermaid
sequenceDiagram
actor User
participant App as Connection flow
participant Store as Saved profiles and credential store
participant Trust as SSH host-key preflight
participant Runtime as Workspace runtime and SSH registry
participant Surface as Terminal and SFTP views
User->>App: Open saved SSH profile
App->>Store: Load saved profile and resolve available credentials
Store-->>App: Saved route and authentication inputs, or missing profile
alt Profile missing
App-->>User: Report missing profile
else Credentials missing but exact ready terminal can be focused
App->>Runtime: Check saved-route identity and node readiness
App->>Surface: Focus existing terminal without a new login
else Continue to prepare SSH configuration
opt Credentials must be entered
App->>User: Prompt for credentials
User-->>App: Submit authentication input or cancel
end
opt Valid configuration and user proceeds
alt Explicit jump-host chain
App->>Runtime: Materialize route nodes
loop Each required hop in route order
opt Host-key preflight needed
App->>Trust: Check host key using the ready parent for a child hop
Trust-->>App: Return trust result or challenge
opt Host-key confirmation requested
App->>User: Show the host-key challenge
User-->>App: Confirm or cancel
end
end
opt Trust permits this hop
App->>Runtime: Advance a ready hop or connect it, retaining its parent if present
Runtime-->>App: Report readiness or failure
end
end
else No explicit jump chain
App->>Trust: Check target host key
Trust-->>App: Return trust result or challenge
opt Host-key confirmation requested
App->>User: Show the target host-key challenge
User-->>App: Confirm or cancel
end
opt Trust permits connection
App->>Runtime: Reuse a compatible node or start the target connection
end
end
alt Target node ready
Runtime-->>App: Deliver or resolve the ready node
App->>Surface: Focus an eligible terminal or start a shell consumer
else Trust rejected or connection failed
App-->>User: Leave terminal unopened and report any error
end
end
end
opt Terminal focused or opened and SFTP enabled by profile or override
App->>Surface: Open SFTP for the same node
end
```
Authentication failure and shell-channel failure occur at different boundaries. A terminal error does not imply the registry-owned transport is unusable for other consumers.
### Terminal Input And Output
For local terminals:
```text
keyboard input -> terminal pane -> local PTY -> output stream -> renderer
```
For SSH terminals:
```text
keyboard input -> terminal pane -> node shell channel -> SSH transport -> output stream -> renderer
```
Both paths produce display state through protocol/ANSI parsing, grid and history updates, row snapshots, cached layout and GPUI drawing. Local PTY protocol replies are queued by the event loop with priority over ordinary input, so terminal queries can receive a response without waiting for a UI redraw. Shell integration supplies command marks to workspace controls and semantic coloring; search reads terminal text snapshots.
Terminal text is not a reliable structured API. Features that need file metadata, transfer progress, forward state, or tool results should use domain APIs rather than scraping terminal output.
### SFTP List And Preview
```text
SFTP page
-> select node
-> acquire SFTP session for node
-> list remote path
-> normalize entries
-> render file list
-> preview selected file through preview logic
-> surface permission/network/unsupported-content errors
```
Preview is separate from download. A preview may cap file size, choose a renderer, or refuse unsupported content while normal transfer remains available.
### SFTP And SCP Upload And Download
```text
user starts transfer
-> build transfer request
-> enqueue in transfer manager
-> retain the recorded protocol on retry, or resolve SFTP vs SCP for a new transfer
-> stream bytes through the endpoint's SFTP session or SSH exec channel
-> emit progress events
-> handle conflict/retry/cancel
-> update transfer list and notification center
```
Single-file transfers can stream directly. SFTP directory transfers may use archive-based helpers where that preserves structure and progress semantics. SCP directory transfers use bounded legacy `C`/`D`/`E` control records and do not provide offset restart.
```mermaid
sequenceDiagram
actor User
participant UI as SFTP transfer queue and workspace adapter
participant Manager as SftpTransferManager
participant Progress as Transfer progress store
participant Endpoint as Node-backed or standalone SSH endpoint
participant Worker as Background SSH transfer worker
User->>UI: Upload or download file / directory
UI->>Endpoint: Resolve backend and lease standalone transport if needed
alt Endpoint unavailable
UI-->>User: Show endpoint error
else Transfer backend available
UI->>Manager: Register transfer controls before spawning worker
Worker->>Manager: Wait for permit and check queued cancellation
opt Transfer may start
Worker->>Endpoint: Resolve current connection handle
Worker->>Worker: Choose saved protocol, override or configured preference
opt SCP preference or Auto with SFTP subsystem unavailable
Worker->>Manager: Check cached or probe live SCP capability
end
alt Protocol resolved
Worker-->>UI: Deliver resolved protocol
alt SFTP
Worker->>Endpoint: Open or reuse a transfer SFTP session
else SCP
Worker->>Endpoint: Run SCP through an SSH exec channel
end
Worker-->>UI: Deliver progress events
opt Transfer supports stored progress
Worker->>Progress: Save protocol, strategy and resumable progress
end
opt In-flight stop requested
alt User cancels
UI->>Manager: Signal cancellation
else Node interrupted
UI->>Manager: Interrupt that node's transfers without deleting stored progress
end
Manager-->>Worker: Worker observes cancel or interrupt control
end
else No eligible protocol or transport
Worker->>Worker: Return setup error
end
end
Worker-->>UI: Deliver final result and refresh the current endpoint's incomplete transfers
opt Resume or retry eligible interrupted transfer
UI->>Progress: Load unfinished record
UI->>Worker: Requeue with stored protocol and strategy
Worker->>Worker: Resume eligible SFTP work or restart SCP at byte zero
end
end
```
For a new transfer in Auto mode, an unavailable SFTP subsystem may fall back to SCP on a supported endpoint. Other SFTP setup failures are reported directly. Retry preserves the resolved protocol: a new SCP attempt starts at byte zero, while eligible SFTP transfers can use verified progress.
### IDE Open And Save
```text
open IDE workspace
-> choose node and root path
-> load tree through remote file APIs
-> open file into editor buffer
-> edit locally in workspace state
-> save through remote write path
-> reconcile the saved revision; retain newer edits or report failure
```
The editor buffer is a view/workspace object. The remote file is durable state on the node. Save is the explicit bridge between them.
### Forward Creation
```text
forward form
-> validate local/remote ports and direction
-> bind rule to node or saved connection
-> start listener through forwarding runtime
-> publish running/suspended/failed state
-> recover or suspend when node health changes
```
Forward rules can be persisted, but an active listener depends on node health and local port availability.
### AI Tool Call
```text
user message
-> build redacted context
-> select model/provider
-> stream model response
-> parse tool request
-> check tool availability, validate arguments and evaluate policy
-> request user approval when required
-> validate any live handle again at dispatch, then execute through its owner
-> append structured result to transcript
```
AI tools do not get implicit shell ownership. A command, file read, file write, or settings action must resolve to an allowed target and pass policy.
```mermaid
sequenceDiagram
actor User
participant AI as Native AI tool loop
participant Policy as Tool policy
participant Targets as Workspace tool dispatch
participant Domain as Domain owner
AI->>AI: Check advertised tool name and parse arguments
alt Tool unavailable or arguments invalid
AI->>AI: Return a pre-execution rejection
else Valid workspace tool request
AI->>Targets: Preflight the active tool session and applicable live handle
Targets-->>AI: Ready or rejected
alt Preflight passed
AI->>Policy: Evaluate the operation
Policy-->>AI: Allow, deny or require approval
opt Approval required
AI->>User: Request approval for the concrete operation
User-->>AI: Approve, reject or cancel
end
alt Allowed or approved
AI->>Targets: Admit execution and revalidate applicable live authority
alt Dispatch admitted
Targets->>Domain: Execute through the owner
Domain-->>AI: Structured result or execution error
else Session or authority no longer valid
Targets-->>AI: Return rejection without executing
end
else Denied or not approved
AI->>AI: Record rejection or cancellation
end
end
end
AI-->>User: Show the outcome if the turn is still active
```
### Cloud Sync Apply And Backup
Cloud Sync v3 recovers any pending local journal before preparing a scoped causal plan. Automatic runs apply only eligible conflict-free plans. Portable-file import and backup restore use a separate preview and safety-backup path.
```mermaid
sequenceDiagram
actor User
participant UI as Cloud Sync runtime
participant Service as Cloud Sync v3 plan
participant Stores as Live configuration owners
participant Remote as Remote backend
UI->>Stores: Recover any pending local journal
Stores-->>UI: Recovery succeeded or failed
alt Recovery failed
UI-->>User: Report recovery failure and stop
else Recovery succeeded
UI->>Service: Prepare scoped plan from local snapshots
opt Existing remote destination
Service->>Remote: List publications and fetch selected encrypted replicas
Remote-->>Service: Replica objects or fetch error
end
Service-->>UI: Prepared plan or preparation failure
alt Preparation failed
UI-->>User: Report error without applying
else Plan available
UI->>UI: Set default direction and summarize conflicts
opt Manual review required
UI->>User: Show directions and conflict candidates
User-->>UI: Confirm choices or cancel review
end
alt Review cancelled
UI->>UI: Discard the prepared plan
else Confirmed or eligible automatic apply
UI->>Service: Apply the prepared plan on the live owners
Service->>Stores: Re-read current values and journal changes if needed
Service-->>UI: Applied plan or apply failure
alt Local apply failed
UI-->>User: Report apply failure and any pending recovery
else Local apply succeeded
UI->>UI: Queue refresh for affected runtime owners
UI->>Service: Finish the applied plan off the UI thread
alt Download only or local cleanup pending
Service-->>UI: Finish without remote writes
else Upload or merge
loop While publication is needed and no error occurs
Service->>Service: Stage the encrypted replica locally
Service->>Remote: Publish the staged replica
Remote-->>Service: Acknowledgement or upload error
end
opt No publication needed or all publications confirmed
Service->>Remote: Prune eligible superseded publications
Remote-->>Service: Deletion acknowledgement or error
end
Service-->>UI: Report remote outcome and pending cleanup separately from local apply
end
end
end
end
end
```
Download-only sync does not publish. If publication fails after local apply, the staged publication remains eligible for retry; the successful local apply is a separate result.
### Plugin Enable
Enabling a package validates host compatibility and records consent for the installed version's requested capabilities. Process and Wasm runtimes receive scoped host APIs; language resources and session helpers follow separate activation paths.
```mermaid
sequenceDiagram
actor User
participant UI as Plugin Manager and workspace bridge
participant Owner as Workspace plugin entity
participant Registry as Plugin registry
participant Runtime as Process or Wasm runtime supervisor
participant Session as Remote desktop workspace
User->>UI: Enable an installed plugin
UI->>Owner: Request enable
Owner->>Registry: Validate host compatibility and save versioned consent
alt Enable rejected
Registry-->>Owner: Return reason
Owner-->>UI: Report enable error
else Enable accepted
Registry-->>Owner: Reload plugin state and contributions
opt Ready language pack
Owner->>Owner: Refresh editor grammar sources
end
Owner-->>UI: Return enable success
opt Remote desktop provider set changed
UI->>Session: Sync eligible provider descriptors
end
UI->>Owner: Bootstrap eligible Process or Wasm runtimes
opt Eligible runtime, immediately or on demand
Owner->>Runtime: Activate with scoped host API
Runtime-->>Owner: Deliver activation result separately
end
end
opt A viewer later needs an eligible provider
Session->>Session: Start and own its helper process
end
opt Replace or remove a remote desktop provider
User->>UI: Request package change
UI->>Session: Retire affected helper processes
Session-->>UI: Return worker handles
UI->>Owner: Start package operation with worker handles
Owner->>Owner: Block new launches for the provider and wait for workers to exit
Owner->>Registry: Replace or remove the package files
end
```
RDP, VNC and SPICE use this helper-provider path; the plugin supervisor does not own their session processes.
---
## State Machines And Lifecycles
### Saved Connection Lifecycle
| State | Meaning | Next Common Actions |
|---|---|---|
| Draft | Form data exists but is not durable | Save, test, discard |
| Saved | Durable connection record exists | Connect, edit, export, delete |
| Edited | User changed fields but has not committed them | Save changes or revert |
| Imported | Record was created from an import flow | Review, save, connect |
| Exported | Record was included in an export operation | Continue using locally or share the export |
| Deleted | Durable record was removed | Existing live nodes may continue until closed |
### SSH Node Lifecycle
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Saved["Saved profile"]
Connecting["Connecting"]
Connected["Node Ready / transport Active"]
Failed["Node Error
connection attempt failed"]
Idle["Transport Idle
route bindings may remain"]
Stale["Transport LinkDown
root and affected descendants"]
Probe["Probe the existing transport during grace"]
Reconnect["Reconnect job
attempts tied to its job ID"]
Restore["Restore consumers on the replacement transport"]
Exhausted["Node Error
no more automatic attempts"]
Disconnect["Explicit node disconnect
cancel the subtree's work and release bindings"]
Closed["Node Disconnected
saved profile remains"]
Saved -->|"open node"| Connecting
Connecting -->|"transport ready"| Connected
Connecting -->|"authentication, trust or network failure"| Failed
Failed -->|"explicit retry if the node remains"| Connecting
Connected -->|"only idle owners remain"| Idle
Idle -->|"active consumer attaches"| Connected
Idle -->|"idle deadline is current, with no active consumer or keep-alive"| Closed
Connected -->|"transport loss"| Stale
Idle -->|"transport loss"| Stale
Stale -->|"automatic reconnect enabled for a non-discovery node"| Probe
Stale -->|"explicit reconnect; resolve the discovery target again if applicable"| Reconnect
Probe -->|"existing binding and transport still valid"| Connected
Probe -->|"expired or missing"| Reconnect
Reconnect -->|"transport rebuilt, ancestors first"| Restore
Restore -->|"report restoration outcomes separately"| Connected
Reconnect -->|"failed attempt and retry allowed"| Reconnect
Reconnect -->|"no retry left"| Exhausted
Exhausted -->|"explicit retry"| Reconnect
Connecting --> Disconnect
Connected --> Disconnect
Idle --> Disconnect
Stale --> Disconnect
Probe --> Disconnect
Reconnect --> Disconnect
Disconnect --> Closed
Closed -->|"open the node again"| Connecting
```
Idle is a transport-pool state: a node binding can keep the transport addressable, but a jump child or other active consumer prevents idle retirement. A grace probe can recover the existing transport; a rebuild restores consumers against the replacement. Discovery-backed reconnects can refresh their resolved target rather than enter the ordinary grace-probe path.
Implementation: [connection registry](../../../crates/oxideterm-ssh/src/connection_registry.rs), [runtime entity](../../../crates/oxideterm-gpui-app/src/workspace/runtime_entity.rs), [reconnect policy](../../../crates/oxideterm-gpui-app/src/workspace/tabs/nodes.rs).
| State | Meaning | User Impact |
|---|---|---|
| Saved only | Profile exists, no live connection | Can be connected later |
| Connecting | Transport is being opened | Dependent views wait or show progress |
| Connected | Node is live and usable | Terminal, SFTP, IDE, forwards, AI tools can target it |
| Idle | The transport has no active consumers; its node bindings can remain | Monitor can still show it |
| Stale | Last known connection is no longer trustworthy | Consumers should pause or refresh |
| Reconnecting | Retry policy is attempting recovery | Views should avoid destructive assumptions |
| Failed | Connection attempt or recovery failed | User action is required |
| Disconnected | Runtime object was closed | Views must detach or ask to reconnect |
### Terminal Lifecycle
| State | Meaning | User Impact |
|---|---|---|
| Created | Pane/tab exists | Startup may still be in progress |
| Starting | PTY or SSH channel is opening | Input may be delayed |
| Ready | Terminal can accept input | Normal interaction |
| Busy | Command is producing output | Terminal stays responsive but output volume may be high |
| Waiting for input | Process is prompting | AI observation and user controls can report this state |
| Closed | Channel or PTY is gone | View can show exit state or close |
### File Transfer Lifecycle
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Pending["Pending
attempt registered or live transfer resumed"]
Active["Active
worker moving data"]
Completed["Completed
worker reports success"]
Paused["Paused
live transfer control retained"]
Error["Error
attempt ended"]
Resume["New SFTP attempt
eligible saved progress; validate partial data"]
Restart["New copy request
restart an interrupted SCP transfer from zero"]
Cancelled["Cancelled
worker reports cancellation or session shuts down"]
Pending -->|"worker starts"| Active
Pending -->|"pause"| Paused
Active -->|"pause"| Paused
Paused -->|"resume existing control"| Pending
Active -->|"worker succeeds"| Completed
Pending -->|"setup failure or interruption"| Error
Active -->|"I/O failure or interruption"| Error
Paused -->|"interruption"| Error
Error -->|"manual resume or node recovery"| Resume
Error -->|"request a fresh SCP copy"| Restart
Resume --> Pending
Restart --> Pending
Pending -->|"cancel"| Cancelled
Active -->|"cancel"| Cancelled
Paused -->|"cancel"| Cancelled
```
Pause and resume act on the existing transfer control. An interruption can end the attempt even when it was paused; reconnection starts another attempt only for progress eligible for restart resume. User cancellation has a separate final state.
Implementation: [transfer_manager](../../../crates/oxideterm-sftp/src/transfer_manager.rs).
| State | Meaning | Recovery or next action |
|---|---|---|
| `Pending` | Registered or resumed; waiting for worker capacity | Start when the worker can proceed |
| `Active` | The worker is transferring data | Pause, cancel, complete or report an error |
| `Paused` | Live control has paused the worker | Resume changes the snapshot to `Pending`; the worker can become active again |
| `Completed` | Worker reported success | Inspect the resulting file or history |
| `Error` | Setup, I/O or node interruption stopped the attempt | Retry or reconnect using the recorded protocol and strategy |
| `Cancelled` | Cancellation completed | Inspect any partial output and cleanup result |
SFTP may restart from a saved offset when supported. SCP can resume a live paused channel, but after channel loss a new attempt starts from byte zero. Reconnect orchestration is outside this worker-state enum.
### Modem Transfer Lifecycle
| State | Meaning | User Impact |
|---|---|---|
| Detected | Terminal output matched a conservative protocol trigger | User may be prompted for a file or directory |
| Prompting | UI is waiting for local path selection | Protocol bytes are held by the transfer consumer where needed |
| Running | Worker is exchanging protocol frames with the PTY/channel | Progress, cancellation, and errors should be visible |
| Completed | Transfer finished and terminal state is released | File result is visible at the chosen path |
| Canceled | User canceled or the terminal closed | Protocol consumer must release terminal output |
| Failed | Protocol or I/O error occurred | User can retry with a clearer command/path |
### Forward Lifecycle
| State | Meaning | User Impact |
|---|---|---|
| Configured | Rule exists but no listener is active | Can be started |
| Starting | Listener or remote channel is being opened | Port may not be usable yet |
| Running | Forward is active | Traffic can pass |
| Suspended | Owning node is unavailable or policy paused it | Rule remains visible |
| Stopped | Listener is closed by user or app | Can be restarted |
| Failed | Bind, permission, or connection error occurred | User must change rule or recover node |
### WSL Graphics Session Lifecycle
| State | Meaning | User Impact |
|---|---|---|
| Available | Graphics support can be started | User can launch a visual session |
| Starting | Server/session process and VNC viewer are being prepared | Viewer may show progress |
| Active | VNC frames and input are flowing | User can interact with the visual surface |
| Disconnected | Viewer or backing session stopped | User can reconnect or launch again |
| Failed | Prerequisites, server startup, or viewer connection failed | User should inspect prerequisites or stop the session |
### IDE Buffer Lifecycle
| State | Meaning | User Impact |
|---|---|---|
| Clean | Buffer matches last loaded or saved content | Closing is safe |
| Dirty | User has unsaved edits | Closing or switching may prompt |
| Saving | Write is in progress | UI should avoid duplicate saves |
| Save failed | Write failed | Buffer remains dirty |
| Conflict | Remote state changed unexpectedly | User needs compare/overwrite/reload decision |
| Closed | Buffer is no longer visible | Remote file is unchanged unless saved |
### AI Tool Lifecycle
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Proposed["Native workspace tool proposed
check availability and parse arguments"]
Preflight["Preflight
check tool session and applicable live target"]
Policy["Evaluate tool policy"]
Approval["Waiting for approval when required"]
Target["Admit execution
revalidate applicable live owner, generation and capability"]
Running["Dispatch to the domain owner"]
Result["Structured success"]
Failure["Execution error"]
Rejected["Rejected or cancelled
no domain execution"]
Transcript["Return outcome to the active AI turn"]
Proposed -->|"available and well formed"| Preflight
Proposed -->|"tool unavailable or arguments invalid"| Rejected
Preflight -->|"passed"| Policy
Preflight -->|"failed or cancelled"| Rejected
Policy -->|"approval required"| Approval
Policy -->|"allowed without prompt"| Target
Policy -->|"denied"| Rejected
Approval -->|"approved"| Target
Approval -->|"declined or cancelled"| Rejected
Target -->|"admitted and authorized"| Running
Target -->|"session inactive or authority rejected"| Rejected
Running -->|"success"| Result
Running -->|"error"| Failure
Result --> Transcript
Failure --> Transcript
Rejected --> Transcript
```
The tool loop checks availability and arguments before policy. The workspace then validates any live handle at dispatch, after approval if required.
Implementation: [tool loop](../../../crates/oxideterm-ai/src/tool_loop/round.rs), [runtime authority](../../../crates/oxideterm-ai/src/runtime_context/authority.rs), [workspace dispatch](../../../crates/oxideterm-gpui-app/src/workspace/sidebar/ai/actions/tools/snapshot.rs).
| State | Meaning | User Impact |
|---|---|---|
| Proposed | Model requested a tool | No side effect yet |
| Policy checked | Tool was compared against policy and target state | May proceed, reject, or require approval |
| Validating target | Resolve the current owner, generation and required capability | Reject stale or revoked references before execution |
| Waiting approval | User decision is required | Execution is paused |
| Running | Tool is executing | Result should be streamed or summarized |
| Result | Tool completed | Transcript records structured output |
| Rejected | Policy or user denied it | Transcript records denial |
| Failed | Execution failed | Error is shown without leaking secrets |
### Sync And Plugin Lifecycles
| Area | States | Meaning |
|---|---|---|
| Cloud sync | Unconfigured, preparing, review/conflict, applying, publishing, pending cleanup/publication, completed, failed | Preparation, local apply and remote publication have separate outcomes; eligible automatic runs use the same domain checks |
| Plugin | Discovered, installed, enabled, failed, disabled, updated, removed | Plugin availability is separate from plugin runtime health |
---
## Ownership And Persistence Matrix
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Concept["Workspace object"]
Config["Durable configuration"]
Live["Live runtime state
node transport, listener, viewer, discovery results"]
Secret["Credential value"]
Buffer["Unsaved editor buffer"]
Connections["ConnectionStore
saved profiles"]
Settings["SettingsStore
discovery source configuration"]
Forwards["SavedForwardStore
persisted forward rules"]
Restore["Runtime owner reconnects, reopens or refreshes"]
Vault["OS credential store or encrypted portable keystore"]
Snapshot["In-memory IDE reconnect snapshot
eligible node-backed buffers"]
Recovery["Restore editor state after reconnect"]
Decision["Write changes to the project file"]
Concept --> Config
Concept --> Live
Concept --> Secret
Concept --> Buffer
Config --> Connections
Config --> Settings
Config --> Forwards
Live --> Restore
Secret -->|"if saved"| Vault
Buffer -->|"capture for node recovery"| Snapshot
Snapshot -->|"restore when eligible"| Recovery
Buffer -->|"on successful save"| Decision
```
| User Concept | Runtime Owner | Persisted Owner | Secret Owner | Survives App Close | Survives Reconnect | User Recovery |
|---|---|---|---|---|---|---|
| Saved connection | Session manager / connection store | Connection record | Keychain or secret-aware store | Yes | Yes | Edit, delete, import, export |
| SSH node | SSH router / registry | None as a live handle | SSH auth layer | No | Not as the same socket | Reconnect or open again |
| Terminal session | Terminal pane/runtime | Optional history/settings only | None by default | Usually no | Only if backing node recovers and channel is recreated | Reopen terminal |
| Terminal image placement | Terminal graphics state | None | None | No | Depends on session reset; placements follow their screen and grid lifecycle | Re-render from application output |
| Privilege credential | Settings privilege surface / terminal helper | Scope metadata only | Secret storage | Yes when saved | Yes through local or saved-node scope | Edit scope, re-enter secret, disable helper |
| Modem transfer | Terminal runtime / modem worker | Destination files only | None by default | No | Usually cancel and retry | Retry transfer or choose another path |
| SFTP session | SFTP runtime | None as a live handle | SSH auth layer | No | Reacquire after reconnect | Refresh or reconnect |
| Transfer | Transfer manager | Transfer history where configured | None by default | Partial/history only | Can retry if operation supports it | Retry, cancel, clean partial file |
| Forward rule | Forwarding surface/runtime | Forward configuration | SSH auth layer for remote side | Yes for rule | Listener must restart | Restart or edit ports |
| Host Tools snapshot | `HostToolsEntity` in `oxideterm-gpui-host-tools` | Live sample is not saved | SSH auth for node-backed tools; Redis has its own authentication | No | Refresh against the current target | Refresh, rerun action, or reconnect the node |
| Discovered target | `DiscoveryService` and the plugin provider | Settings store saves source configuration; the service holds discovered results in memory | Credential bindings of the discovery source | Source configuration only | Reopen against the current discovery catalog | Refresh the discovery source or reopen the target |
| Desktop session | RDP/VNC/SPICE helper or WSL Graphics runtime | Profile metadata may persist; live viewer does not | Protocol credentials and optional SSH gateway for RDP/VNC/SPICE; WSL distribution for WSL Graphics | No live viewer | Gateway can reconnect independently of the viewer | Reconnect the viewer or relaunch WSL Graphics |
| IDE workspace | IDE surface/runtime | Recent workspace/settings | SSH auth layer for remote side | Recent entry yes | Reopen or refresh after reconnect | Save, reload, resolve conflict |
| Editor buffer | IDE/editor state | The project file changes only on save | None by default | Unsaved content depends on recovery policy | Node IDE recovery can restore editor state without writing the project file | Save, reload, discard |
| AI conversation | AI sidebar/runtime | AI persistence | Provider key store | Yes when enabled | Not node-dependent unless tools target nodes | Continue, compact, delete |
| AI provider key | AI key store | Secret storage | Secret storage | Yes | Yes | Re-enter or unlock |
| Plugin setting | Plugin settings store | Plugin settings file/store | Separate plugin secret store for credentials | Yes | Usually yes | Reset, disable plugin |
| Plugin secret | Plugin lifecycle secret boundary | Secret storage | Secret storage | Yes | Yes | Re-enter, revoke, disable |
| Cloud sync config | Sync runtime/settings | Settings/cloud-sync state | Secret storage for credentials | Yes | Network-dependent | Re-authenticate or disable |
| Portable runtime | Portable runtime crate | Portable metadata/payload | Portable key material | Yes | Not connection-dependent | Unlock, restore, recreate |
| Support bundle | Backup/support flow | Generated artifact | Must exclude raw secrets | Artifact exists until removed | Not applicable | Regenerate after fixing scope |
---
## Event And Notification Model
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Node["SSH registry and NodeRouter events"]
Reconnect["Reconnect worker results"]
Runtime["WorkspaceRuntimeEntity
node mailbox and worker queue"]
RuntimeUi["Workspace runtime effects and connection monitor"]
Sampler["Host Tools GPU sampler updates"]
Resource["Host Tools reliable results
including container actions and Redis snapshots or actions"]
Host["HostToolsEntity
separate sampler and reliable-result queues"]
HostUi["Host Tools page and action results"]
Discovery["DiscoveryService change notification"]
DiscoveryBridge["Workspace reads current catalog and status"]
DiscoveryUi["Discovery settings, session tree and open command palette"]
Mcp["PublicMcpBackground delivery"]
McpUi["Workspace bridge"]
McpRequest["Handle requests that need a window"]
McpNotice["Notify when a pending approval exists"]
Node --> Runtime
Reconnect --> Runtime
Runtime --> RuntimeUi
Sampler --> Host
Resource --> Host
Host --> HostUi
Discovery --> DiscoveryBridge
DiscoveryBridge --> DiscoveryUi
Mcp --> McpUi
McpUi -->|"window request"| McpRequest
McpUi -->|"state changed"| McpNotice
```
Each lane has its own delivery and cleanup. Notifications come from the consumer that handles the event, such as the workspace bridge handling a pending Public MCP approval.
Implementation: [node runtime entity](../../../crates/oxideterm-gpui-app/src/workspace/runtime_entity.rs), [Host Tools delivery](../../../crates/oxideterm-gpui-host-tools/src/delivery.rs), [discovery workspace bridge](../../../crates/oxideterm-gpui-app/src/workspace/discovery.rs), and [Public MCP workspace bridge](../../../crates/oxideterm-gpui-app/src/workspace/public_mcp.rs).
### Event Sources
The app receives events such as:
- SSH node status changes.
- Terminal readiness and process state.
- Terminal privilege prompt state and modem transfer progress.
- Remote desktop and WSL Graphics connection, frame, and disconnect events.
- Host tool sampling status, resource snapshots, and action results.
- SFTP transfer progress and conflicts.
- Forward start, stop, suspend, and failure.
- IDE save, conflict, and reload outcomes.
- Plugin install, enable, disable, settings, and host API failures.
- Discovery catalog refreshes and availability changes.
- Cloud sync preview, apply, conflict, and backup results.
- AI tool proposals, approvals, execution results, and policy rejections.
- Public MCP requests and approval state changes.
### Notification Rules
Notifications should be actionable and scoped:
- A notification should point to the page that can resolve it.
- It should not contain raw credentials, request headers, tokens, or terminal buffer dumps.
- Repeated events should coalesce when they describe the same underlying condition.
- Terminal input should not be blocked by unrelated background notifications.
- Support bundle suggestions should explain what will be included and what is excluded.
### Refresh Versus Events
Events are the primary way to keep active pages current. Explicit refresh remains necessary when:
- A page was inactive during many state changes.
- The app recovered from sleep or network changes.
- A plugin or external tool changed durable state.
- A domain reports that its cached view may be stale.
The UI should not become the source of truth for connection health, transfer state, or persisted settings. It renders state owned by the relevant domain.
### Staleness Rules
Staleness means "the app cannot prove this state is current." It does not automatically mean data is deleted or corrupted.
- A stale node should stop accepting new high-risk operations until refreshed or reconnected.
- A stale file listing should offer refresh before destructive actions.
- A stale forward should show suspended or failed state rather than pretending traffic is flowing.
- A stale AI target should require target re-selection or tool rejection.
### Wakeups, Budgets, And Stale Results
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Producer["Background producer"]
Queue["ActiveDeliverySender
enqueue before marking a wake"]
Wake["ActiveDeliveryWake
coalesce notifications, not results"]
Receiver["Foreground consumer
take the pending flag and check for stop"]
Drain["drain_channel
stop at count or time budget, or empty or disconnected channel"]
Validate["Consumer checks the result's identity"]
Apply["Apply a current result
notify the affected view if needed"]
Discard["Discard a stale completion"]
Backlog["Possible backlog
mark the wake again if continuing"]
Stop["Owner teardown
stop owned work and signal delivery"]
Exit["End delivery according to the owner's loop"]
Producer --> Queue
Queue --> Wake
Wake --> Receiver
Receiver -->|"pending work"| Drain
Receiver -->|"stop and no work to drain"| Exit
Drain -->|"for each queued result"| Validate
Validate -->|"current"| Apply
Validate -->|"stale"| Discard
Drain -->|"budget reached"| Backlog
Drain -->|"stop requested and batch processing is done"| Exit
Backlog --> Wake
Stop -->|"set stop flag and wake consumer"| Wake
```
A bounded drain limits dequeue work per UI wakeup. Wakeup coalescing leaves queued values intact; the consumer decides whether each value still belongs to the active request or target. For example, Host Tools keeps the latest GPU snapshot for the selected connection in each batch and drains action results separately.
Implementation: [shared delivery primitives](../../../crates/oxideterm-workspace/src/delivery.rs) and [Host Tools delivery](../../../crates/oxideterm-gpui-host-tools/src/delivery.rs).
---
## Failure Model
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
Symptom["Observed symptom"]
Locate["Inspect the owning surface and operation stage"]
Config["SSH trust or authentication error"]
Provider["Desktop provider missing or capability unavailable"]
Node["SSH transport lost"]
Data["IDE save conflict or unsaved changes"]
View["File listing out of date"]
Sync["Cloud Sync replica upload failed after local apply"]
Review["Verify fingerprint or check the authentication settings"]
EnableProvider["Check provider eligibility or choose a supported option"]
Reconnect["Reconnect the node and check individual restore outcomes"]
Resolve["Resolve conflict before saving; retain or discard edits explicitly"]
Refresh["Refresh the current endpoint and directory"]
Retry["Retry publication using the staged replica"]
Verify["Verify the actual operation result"]
Symptom --> Locate
Locate --> Config
Locate --> Provider
Locate --> Node
Locate --> Data
Locate --> View
Locate --> Sync
Config --> Review
Provider --> EnableProvider
Node --> Reconnect
Data --> Resolve
View --> Refresh
Sync --> Retry
Review --> Verify
EnableProvider --> Verify
Reconnect --> Verify
Resolve --> Verify
Refresh --> Verify
Retry --> Verify
```
| Symptom | First Surface To Check | Subsystem | Likely Cause | Recovery Action |
|---|---|---|---|---|
| Terminal tab closed but host still appears connected | Connection Monitor | Tabs and node runtime | A tab is a view; the node can outlive it | Close the node from Connection Monitor if it is no longer needed |
| Terminal opens but does not accept input | Terminal tab | Terminal runtime | PTY/channel is still starting or failed readiness | Wait for readiness, reopen terminal, or reconnect the node |
| Terminal output is delayed during large operations | Terminal tab and Notification Center | Data plane contention | A heavy background task may be competing for resources | Pause transfers/sync or wait for the task to complete |
| TUI preview leaves a stale block after exit | Terminal tab | Terminal graphics/image placement | Full-screen app did not fully clear image placement or alternate-screen state | Clear screen, reopen the terminal, or file a terminal rendering bug with the captured command |
| Saved terminal background does not appear | Terminal or runtime page | Terminal background rendering | Background setting is not enabled for that surface or the image library selection is stale | Re-select the image, check enabled tab types, or reload the surface |
| Privilege password helper does not trigger | Terminal tab and Privilege settings | Terminal helper | Prompt was not detected or the active session has no matching credential scope | Check active terminal scope, prompt matcher, and saved credential ownership |
| Wrong privilege password is submitted | Terminal tab and Privilege settings | Secret scope resolution | Credential was scoped to the wrong local/SSH owner | Stop the command, edit the credential scope, and retry after prompt returns |
| Modem transfer opens unexpectedly | Terminal tab | Modem protocol detector | Output looked like a protocol prelude without enough context | Cancel helper, continue terminal output, and report the trigger sample |
| Modem transfer stalls | Transfer prompt or notification | Modem transfer engine | Peer stopped responding, path prompt was canceled, or protocol negotiation failed | Cancel or retry with an explicit `rz`/`sz` command and a stable local path |
| SSH connection fails before password prompt | New Connection or Sessions | SSH transport | Host, port, proxy, or DNS is incorrect | Edit connection settings and test again |
| Host-key prompt appears unexpectedly | Host-key dialog | SSH trust boundary | Remote host key changed or first connection is untrusted | Verify the fingerprint before accepting |
| Keyboard-interactive auth repeats | New Connection dialog | SSH auth | Server requested additional answers or rejected credentials | Re-enter answers, update saved credentials, or check server auth policy |
| Node shows reconnecting for a long time | Connection Monitor | Reconnect orchestrator | Network is unavailable or retry policy is still active | Wait, cancel reconnect, or edit connection details |
| Host Tools page is empty or stale | Host Tools panel | `HostToolsEntity` and host probes | Wrong target selected, tool unavailable, or SSH node is stale | Select the intended host and refresh; reconnect a stale SSH target |
| Container or Redis action fails | Host Tools action dialog | Container engine or Redis endpoint | Engine or endpoint changed, authentication or permissions failed, or the operation was rejected | Check the selected engine or endpoint, refresh, then review the action error before retrying |
| Node is connected but SFTP cannot open | SFTP page | SFTP session | Server lacks SFTP support or session acquisition failed | Reconnect, check server subsystem, or use terminal fallback |
| Remote file list is empty or outdated | SFTP page | SFTP listing/cache | Path changed, permission denied, or cached view is stale | Refresh path, navigate upward, or check permissions |
| SFTP upload stalls | Transfer list | Transfer manager | Network interruption, remote disk pressure, or suspended node | Resume/retry, reconnect node, or cancel partial transfer |
| Directory transfer is slow | Transfer list | SFTP transfer strategy | Many small files or archive helper fallback | Let the transfer complete or split the directory |
| Preview refuses a file | Preview dialog | SFTP preview | File is too large, binary, unsupported, or permission denied | Download/open externally or use terminal tools |
| Forward is suspended | Forwarding and Connection Monitor | Forwarding runtime | Owning node is stale or disconnected | Reconnect node or stop the forward |
| Forward fails to start | Forwarding page | Forwarding runtime | Local port is already used, permission denied, or remote bind failed | Change port, close conflicting process, or edit direction |
| Traffic does not pass through a running forward | Forwarding and terminal/network tool | Forwarding runtime | Remote endpoint is unavailable or rule targets the wrong host/port | Test endpoint from the remote host and edit rule |
| Remote desktop viewer is blank or disconnected | Remote desktop viewer | Remote desktop session or WSL Graphics runtime | Endpoint is unreachable or the backing session stopped | Check the route and server, then reconnect; for WSL Graphics, check the distribution and backing session |
| RDP, VNC or SPICE cannot open with the selected option | Connection form or remote desktop viewer | Marketplace protocol helper | Plugin is missing or disabled, or its helper lacks the requested capability | Enable or update the matching plugin, or choose connection options that the provider supports |
| IDE workspace opens but tree is missing files | IDE workspace | IDE FS | Root path is wrong, permissions block listing, or cache is stale | Refresh tree or open another root |
| IDE save fails | IDE workspace and Connection Monitor | IDE write path | Node disconnected, permission denied, conflict, or remote file changed | Reconnect, resolve conflict, or save to another path |
| Unsaved editor changes remain after reconnect | IDE workspace | Editor buffer | Reconnect restores node access, not implicit file writes | Save explicitly after reconnect |
| AI wants to run on a saved host | AI approval and Sessions | AI target selection | Saved profile is not a live shell target | Connect the host first or choose another active target |
| AI tool is rejected | AI sidebar | AI policy | Tool is dangerous, missing approval, or target is not allowed | Approve when prompted, narrow target, or use a safer request |
| AI context omits recent terminal output | AI sidebar | Context window | Token budget or redaction removed data | Attach the needed context explicitly or ask for a narrower task |
| AI provider call fails | AI settings and AI sidebar | Provider transport | Missing key, invalid model, quota, or network failure | Update provider settings and retry |
| Plugin setting changed but page did not update | Plugin manager and affected page | Plugin lifecycle | Page needs refresh or plugin event did not re-render the view | Refresh page, disable/enable plugin, or restart app |
| Plugin fails to enable | Plugin manager | Plugin registry/lifecycle | Manifest invalid, permission denied, missing dependency, or secret unavailable | Review plugin details, update settings, or remove plugin |
| Cloud sync conflict appears | Cloud Sync | Sync planner | Local and remote durable state changed independently | Review preview, choose local/remote resolution, then apply |
| Backup generation fails | Cloud Sync or backup dialog | Backup runtime | Destination unavailable, permission denied, or secret redaction failure | Choose another destination or reduce selected data |
| Portable runtime cannot unlock | Portable settings | Portable runtime | Wrong passphrase, missing key material, or corrupted payload | Re-enter passphrase, restore backup, or recreate portable data |
| CLI report differs from app view | CLI and app page | Shared state boundary | CLI reads persisted state while app also has live runtime state | Refresh app state or compare with Connection Monitor |
| Support bundle lacks expected data | Support bundle dialog | Output boundary | Secret redaction or selected scope excluded it | Regenerate with the right scope, still excluding raw secrets |
---
## Native Crate Map
The map groups responsibilities and shows how the native desktop host connects them. Short crate names omit the `oxideterm-` prefix except for `vte` and `alacritty_terminal`; the protocol helpers are packages in the plugin marketplace, outside the native app.
```mermaid
%%{init: {"layout": "dagre", "flowchart": {"nodeSpacing": 45, "rankSpacing": 75, "curve": "basis"}}}%%
flowchart TB
App["oxideterm-gpui-app
workspace composition and bridges"]
SharedUI["gpui-shell / gpui-ui / gpui-platform
workspace / theme"]
FeatureViews["gpui-connections / gpui-settings-view / gpui-cloud-sync"]
TerminalUI["gpui-terminal / gpui-terminal-view"]
Terminal["terminal / terminal-emulator / terminal-model
vte / alacritty_terminal"]
Remote["ssh / topology / session-adapter
sftp / ftp / forwarding"]
FileViews["gpui-sftp / gpui-file-manager / gpui-forwards"]
HostTools["gpui-host-tools / connection-monitor
containers and Redis"]
Discovery["discovery
plugin-backed target catalog"]
Editor["gpui-ide / gpui-editor / gpui-markdown
ide-core / ide-fs / editor-*"]
Graphics["gpui-remote-desktop
viewer, relative pointer capture and worker ownership"]
DesktopProtocol["remote-desktop
helper protocol and process adapter"]
Helpers["Marketplace RDP / VNC / SPICE helpers"]
Audio["pcm-audio
host playback, capture and macOS audio routing"]
Wsl["wsl-graphics"]
AI["gpui-ai / ai / ai-tasks / skills
acp-host-tools"]
Mcp["public-mcp / public-mcp-host
external protocol and host bridge"]
Plugin["plugin-manifest / plugin-registry / plugin-protocol
plugin-host-api / plugin-wasm-runtime"]
Durable["connections / settings / secret-store
cloud-sync / portable-runtime"]
CLI["oxideterm-cli"]
App --> SharedUI
App --> FeatureViews
FeatureViews --> Durable
App --> TerminalUI
TerminalUI --> Terminal
App --> Remote
App --> FileViews
FileViews --> Remote
App --> HostTools
App --> Discovery
App --> Editor
Editor -->|"node-backed IDE file access"| Remote
App --> Graphics
Graphics --> DesktopProtocol
DesktopProtocol <-->|"binary stdio: requests, frames and events"| Helpers
Graphics --> Audio
App --> Wsl
App --> AI
App --> Mcp
App --> Plugin
App --> Durable
CLI --> Durable
CLI -->|"loopback MCP bridge"| Mcp
```
| Area | Crates |
|---|---|
| Desktop shell and workspace glue | `oxideterm-gpui-app`, `oxideterm-gpui-shell`, `oxideterm-workspace` |
| Shared GPUI components and platform helpers | `oxideterm-gpui-ui`, `oxideterm-gpui-platform`, `oxideterm-theme` |
| Terminal rendering and terminal domain | `oxideterm-gpui-terminal`, `oxideterm-gpui-terminal-view`, `oxideterm-terminal`, `oxideterm-terminal-*` |
| Command delivery and reusable quick commands | `oxideterm-gpui-command-sender`, `oxideterm-gpui-quick-commands`, `oxideterm-quick-commands` |
| Terminal parsing, grid and history | Workspace forks of `vte` and `alacritty_terminal`; `oxideterm-terminal-emulator` builds snapshots from `oxideterm-terminal-model` rows and cells |
| BLE terminal transport | `oxideterm-ble`, `oxideterm-terminal/src/session/ble.rs` |
| Terminal modem transfers | `oxideterm-modem-transfer`, terminal modem worker integration |
| SSH, node routing, reconnect | `oxideterm-ssh`, `oxideterm-topology`, `oxideterm-session-adapter` |
| Host Tools and connection monitoring | `oxideterm-gpui-host-tools` owns the panels and results; `oxideterm-connection-monitor` probes and models Docker, Podman, WSL, nerdctl and Redis resources |
| File views and transfers | `oxideterm-gpui-file-manager`, `oxideterm-gpui-sftp`, `oxideterm-local-files`, `oxideterm-sftp`, `oxideterm-ftp` |
| Saved connections | `oxideterm-connections`, `oxideterm-gpui-connections` |
| Dynamic discovery | `oxideterm-discovery` runs the provider catalog; desktop bridges results to `oxideterm-gpui-connections`, `oxideterm-gpui-settings-view` and the command palette |
| Forwarding | `oxideterm-forwarding`, `oxideterm-gpui-forwards` |
| Graphics and remote desktop sessions | `oxideterm-gpui-remote-desktop` is the viewer, `oxideterm-remote-desktop` manages protocol workers and marketplace helpers, `oxideterm-pcm-audio` handles local PCM playback and capture, and `oxideterm-wsl-graphics` owns WSL graphics |
| IDE and editor | `oxideterm-gpui-ide` owns the surface and file transfer controls; `oxideterm-ide-fs` supplies file operations. Editor crates: `oxideterm-gpui-editor`, `oxideterm-ide-core`, `oxideterm-editor-*` |
| Knowledge workspace and Markdown | `oxideterm-ai` (RAG storage and search), `oxideterm-gpui-ai/src/knowledge` (workspace view), `oxideterm-gpui-markdown`, `oxideterm-gpui-editor` |
| Settings and privilege credentials | `oxideterm-settings`, `oxideterm-settings-model`, `oxideterm-gpui-settings-view`, secret-aware app boundary |
| AI, RAG, MCP clients, reasoning, and tool policy | `oxideterm-ai`, `oxideterm-ai-tasks`, `oxideterm-skills`, `oxideterm-gpui-ai` sidebar |
| ACP agent sessions and host tools | `oxideterm-acp-host-tools`, `workspace/acp_workspace.rs`, `workspace/acp_plugins.rs`; Codex and Claude Code adapters are independent packages in the plugin repository |
| Public MCP for external clients | `oxideterm-public-mcp` provides transport, client authorization and approval policy; `oxideterm-public-mcp-host` dispatches domain work and forwards window requests to the desktop bridge |
| Plugins | `oxideterm-plugin-manifest`, `oxideterm-plugin-registry`, `oxideterm-plugin-protocol`, `oxideterm-plugin-host-api`, `oxideterm-plugin-wasm-runtime`, app plugin entities |
| Cloud Sync v3 and portable runtime | `oxideterm-cloud-sync/src/sync_v3/`, `oxideterm-gpui-cloud-sync`, `oxideterm-portable-runtime` |
| Audit, notifications and update | `oxideterm-audit`, `oxideterm-gpui-audit`, `oxideterm-notification-center`, `oxideterm-update` |
| CLI companion | `oxideterm-cli` |