docs(cli-rs): describe service and wire contracts directly

Keep discovery and replacement policy, event delivery order, PTY frame
layout and the no-retry rule for writes. Remove port ownership notes,
review labels and source coordinates from the service, API, ACP and
drive crates. No test is removed.
This commit is contained in:
Simon Klee
2026-11-18 20:36:59 +01:00
Unverified
parent 2fd3a4987a
commit 50cfcdc31a
72 changed files with 97 additions and 388 deletions
+2 -6
View File
@@ -1,9 +1,5 @@
//! The method table: parameter checks, dispatch to the service, and error mapping
//! (`packages/cli/src/acp/agent.ts`, and the ACP SDK's parameter parsing).
//!
//! Parameters are checked the way the SDK's generated schemas parse them: required fields must have
//! their type, and malformed MCP servers and additional directories are skipped. A failed check answers
//! `Invalid params` with zod's `format()` shape for the first failing field.
//! Invalid parameters report the first failing field in the ACP SDK's `format()` shape. Malformed MCP servers and
//! additional directories are skipped.
use std::future::{Future, ready};
use std::sync::Arc;
@@ -1,5 +1,3 @@
//! The client capabilities the agent acts on (`packages/cli/src/acp/capabilities.ts`).
use serde_json::Value;
pub const CHILD_SESSION_UPDATES: &str = "opencode/child-session-updates";
+1 -2
View File
@@ -1,5 +1,4 @@
//! Models, modes, and commands per directory, kept fresh from server events
//! (`packages/cli/src/acp/catalog.ts`).
//! Per-directory catalogs update on server events.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
-2
View File
@@ -1,5 +1,3 @@
//! Child-session updates (`packages/cli/src/acp/child.ts`).
use opencode_util::json_object;
use serde_json::{Value, json};
-2
View File
@@ -1,5 +1,3 @@
//! Server errors as ACP errors, session IDs, and event subscriptions (`packages/cli/src/acp/client.ts`).
use futures_util::stream::BoxStream;
use opencode_api::client::Client;
use opencode_api::error::Error;
@@ -1,5 +1,3 @@
//! Compaction progress as ACP updates (`packages/cli/src/acp/compaction.ts`).
use std::collections::HashMap;
use opencode_util::json_object;
@@ -1,5 +1,3 @@
//! Session config options: model, effort, and mode (`packages/cli/src/acp/config-option.ts`).
use opencode_api::generated::{ModelInfo, ModelRef, ProviderID};
use opencode_api::js::locale_compare;
use opencode_util::json_object;
+2 -6
View File
@@ -1,9 +1,5 @@
//! JSON-RPC over newline-delimited JSON (`packages/cli/src/acp/connection.ts`, and the parts of the ACP
//! SDK's `ndJsonStream` and `Connection` the agent relies on).
//!
//! The reader runs each message's synchronous part inline, so a `session/cancel` that follows a
//! `session/prompt` always finds the turn the prompt registered. Responses and notifications go through
//! one writer queue, so they reach the client in the order they were sent.
//! Newline-delimited JSON-RPC. The reader registers a prompt before dispatching the next cancellation. One writer
//! preserves response and notification order.
use std::collections::HashMap;
use std::ops::ControlFlow;
@@ -1,5 +1,3 @@
//! ACP content blocks to prompt parts and back (`packages/cli/src/acp/content.ts`).
use base64::Engine as _;
use opencode_util::json_object;
use serde_json::{Value, json};
@@ -288,7 +286,6 @@ mod tests {
#[test]
fn a_windows_file_resource_shows_forward_slashes() {
// `fileURLToPath` gives `C:\src\a.ts` on Windows, which `content.ts` turns to `/`; POSIX keeps the URL path.
let block = json!({ "type": "resource", "resource": { "uri": "file:///C:/src/a.ts#L12", "text": "body" } });
let label = if cfg!(windows) { "[C:/src/a.ts:12]\nbody" } else { "[/C:/src/a.ts:12]\nbody" };
assert_eq!(prompt_content_to_parts(&[block]), vec![text(label)]);
@@ -1,5 +1,4 @@
//! Additional directories: validation, permission grants, and their record in session metadata
//! (`packages/cli/src/acp/directories.ts`).
//! Additional directory grants are recorded in session metadata.
use opencode_api::client::Client;
use opencode_api::generated::{PermissionEffect, PermissionRule, SessionInfo, SessionMetadata, SessionUpdateInput};
@@ -1,5 +1,3 @@
//! Session forms as `elicitation/create` (`packages/cli/src/acp/elicitation.ts`).
use std::collections::HashSet;
use std::sync::LazyLock;
+2 -5
View File
@@ -1,5 +1,3 @@
//! ACP errors and their JSON-RPC form (`packages/cli/src/acp/error.ts`).
use opencode_util::json_object;
use serde_json::{Value, json};
@@ -61,8 +59,7 @@ pub enum NotReady {
Agents,
}
/// Every failure a handler can end with: the tagged errors of `error.ts`, a JSON-RPC error from the
/// client, the catalog errors, and defects.
/// Errors a request handler can return.
#[derive(Debug, Clone)]
pub enum Failure {
SessionNotFound {
@@ -140,7 +137,7 @@ impl Failure {
}
}
/// `toRequestError`, plus the handler's mapping of catalog errors and defects (`agent.ts`).
/// Maps a handler failure to a JSON-RPC error.
pub fn to_rpc(&self) -> RpcError {
match self {
Self::SessionNotFound { session_id } => RpcError::invalid_params(
+1 -6
View File
@@ -1,9 +1,4 @@
//! The ACP agent (C.11): `opencode acp`, the Agent Client Protocol over stdio JSON-RPC
//! (`packages/cli/src/acp`, `packages/cli/src/commands/handlers/acp.ts`).
//!
//! The agent starts a private TypeScript server, as TS `Standalone.start()` does, and talks to it over
//! HTTP. C.12 (`rs-acp-rest`) owns `tools`, `permission`, `elicitation`, `config_option`, `replay`,
//! `compaction`, and `directories`. `acp --login` runs `auth login` in the CLI crate.
//! `opencode acp` serves the Agent Client Protocol over stdio and starts a private HTTP server for the session.
pub mod agent;
pub mod capabilities;
+1 -2
View File
@@ -1,5 +1,4 @@
//! Permission asks as `session/request_permission`, and completed edits as diffs
//! (`packages/cli/src/acp/permission.ts`).
//! Permission requests and completed edit diffs for the ACP client.
mod unified;
@@ -628,7 +628,6 @@ mod tests {
#[test]
fn structured_ranges_match_jsdiff() {
// Written by script/gen/structured-patch.ts from jsdiff itself.
let cases: Vec<[String; 3]> = serde_json::from_str(include_str!("structured_patch.json")).unwrap();
for [old, new, ranges] in cases {
assert_eq!(structured_ranges(&old, &new), ranges, "{old:?} -> {new:?}");
-2
View File
@@ -1,5 +1,3 @@
//! An ACP prompt as an OpenCode submission (`packages/cli/src/acp/prompt.ts`).
use opencode_api::generated::CommandInfo;
use serde_json::Value;
+1 -2
View File
@@ -1,5 +1,4 @@
//! `session/load` history replay (`packages/cli/src/acp/replay.ts`). Messages stay JSON, as the server
//! sends them.
//! Replays stored messages on `session/load`.
use opencode_api::client::Client;
use opencode_api::generated::{MessageListInput, MessageListInputOrder};
@@ -1,5 +1,3 @@
//! The ACP methods (`packages/cli/src/acp/service.ts`).
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
+1 -2
View File
@@ -1,5 +1,4 @@
//! Sessions attached to this connection: their selection, MCP servers, and the commands and config
//! options pushed to the client (`packages/cli/src/acp/sessions.ts`).
//! Sessions attached to this connection and the selection, commands and configuration advertised to the client.
use std::collections::HashMap;
use std::future::Future;
+1 -4
View File
@@ -1,5 +1,3 @@
//! Tool calls as ACP `tool_call` and `tool_call_update` (`packages/cli/src/acp/tool.ts`).
pub mod patch;
use std::sync::LazyLock;
@@ -235,8 +233,7 @@ fn tool_content(content: &Value) -> Vec<Value> {
.collect()
}
/// `readDisplayText` (`packages/tui/src/mini/tool.ts`): the human-facing text of read's JSON page
/// envelope.
/// Extracts the human-readable text from a read tool's JSON page.
fn read_display_text(text: &str) -> Option<String> {
if !text.starts_with('{') {
return None;
@@ -1,5 +1,4 @@
//! The patch tool's format: `parse` and `derive` of `packages/util/src/patch.ts`. Parse errors carry no
//! detail here; the agent only needs to know that a patch did not parse.
//! Parse errors are opaque: the agent only needs to know whether the patch is valid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Hunk {
+1 -2
View File
@@ -1,5 +1,4 @@
//! Server events of one turn as ACP updates, asks, and the prompt response
//! (`packages/cli/src/acp/translate.ts`). Events stay JSON, as the server sends them.
//! Translates server events into ACP updates and the final prompt response.
use std::collections::{HashMap, HashSet};
+2 -10
View File
@@ -1,13 +1,5 @@
//! Prompt turns: submission, event streaming, asks, cancellation, and child sessions that outlive a
//! turn (`packages/cli/src/acp/turn.ts`).
//!
//! A turn runs as its own task, so a cancelled prompt request still settles and responds. Cancellation
//! lands only while the turn waits on the server (`execute`) and in the last check of `settle`, as the
//! TS turn's interruptible regions do.
//!
//! Children that are still open when a prompt responds are followed in the background, and so are the
//! parent turns their reports start. The session's next prompt stops that follower and inherits its
//! children.
//! Each prompt runs in its own task so it can settle and respond after cancellation. A background follower tracks
//! unfinished children and the parent turns their reports start. The next prompt inherits those children.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -1,5 +1,3 @@
//! `additional-directories.test.ts`.
use opencode_acp::paths::resolve_lexical;
use opencode_util::path::Flavor;
use serde_json::{Value, json};
@@ -1,5 +1,3 @@
//! `catalog.test.ts`.
use std::time::Duration;
use serde_json::{Value, json};
@@ -1,5 +1,3 @@
//! `compaction.test.ts`.
use std::sync::Arc;
use serde_json::{Value, json};
@@ -1,5 +1,3 @@
//! `config-option.test.ts`.
use opencode_acp::catalog::{Catalog, Mode};
use opencode_acp::config_option::{Selection, config_options, parse_model_selection};
use opencode_api::generated::{ModelInfo, ModelRef, ProviderID};
@@ -1,5 +1,3 @@
//! `elicitation.test.ts`.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -1,6 +1,3 @@
//! `error.test.ts`. The log lines the TS case also checks ("ACP catalog event stream failed",
//! "ACP selection event stream failed") go to the `log` facade here and are not captured.
use serde_json::json;
use crate::wire::{Server, WireOptions, delivered, events, start_session, text_delta};
@@ -1,5 +1,3 @@
//! The in-process ACP tests of `packages/cli/test/acp`, ported to the Rust agent.
mod additional_directories;
mod catalog;
mod compaction;
@@ -1,6 +1,3 @@
//! `permission.test.ts`. The log assertion of "withdraws permission requests settled elsewhere" is not
//! ported: logs go to the `log` facade.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -1,5 +1,3 @@
//! `prompt.test.ts`.
use std::sync::Arc;
use std::time::Duration;
@@ -1,5 +1,3 @@
//! `replay.test.ts`.
use serde_json::{Value, json};
use crate::wire::{WireOptions, assert_matches, assistant_message, file_diff, make_session, start_wire};
@@ -1,5 +1,3 @@
//! `session.test.ts`.
use serde_json::{Value, json};
use crate::wire::{RpcError, Wire, WireOptions, assert_matches, lock, make_session, start_wire};
@@ -1,5 +1,3 @@
//! `translate.test.ts`: the rows for the turn fold, the compaction rows, and the replay rows.
use opencode_acp::paths::resolve_from;
use opencode_acp::translate::{self, Output, StartKind, Terminal, TurnContext, TurnStart, TurnState};
use serde_json::{Value, json};
@@ -1,5 +1,3 @@
//! `turn.test.ts`.
use std::sync::Arc;
use serde_json::{Value, json};
+1 -3
View File
@@ -1,6 +1,4 @@
//! A fake OpenCode server and an in-process ACP client, ported from
//! `packages/cli/test/acp/wire-fixture.ts`. The server is a transport, so no socket is opened; the agent
//! runs over in-memory pipes.
//! In-process ACP client and server connected by in-memory pipes.
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+2 -6
View File
@@ -1,6 +1,4 @@
//! Request core: base URL, authentication, per-call headers, and declared errors. It follows the
//! `make` function of the TypeScript Promise client (`packages/client/src/promise/generated/client.ts:354-473`).
//! The generated methods (`generated/methods.rs`) build a [`Call`] and send it here.
//! Sends generated calls with the client's base URL, credentials and per-call headers.
use std::sync::Arc;
@@ -17,9 +15,7 @@ use crate::transport::{Request, Reqwest, Response, SseResponse, Transport};
/// The query parameter the server reads credentials from when a request cannot carry headers.
pub const AUTH_TOKEN_QUERY: &str = "auth_token";
/// How the client authenticates. The server accepts `Basic` credentials in the `authorization` header or,
/// base64-encoded the same way, in the `auth_token` query parameter
/// (`packages/server/src/middleware/authorization.ts:33-40`).
/// HTTP Basic credentials can travel in the `authorization` header or the `auth_token` query parameter.
#[derive(Clone, PartialEq, Eq)]
pub enum Auth {
/// `authorization: Basic base64(username:password)`.
+2 -5
View File
@@ -1,8 +1,5 @@
//! Client MCP socket (E.13b, row A05): a port of `packages/client/src/mcp.ts`.
//!
//! The client serves tools to the opencode server: it opens a WebSocket to `/api/experimental/client-mcp` and
//! answers MCP JSON-RPC over it, one message per text frame, so the server is the MCP client. [`connect`] keeps the
//! socket open and reconnects with backoff until the [`Connection`] closes or drops.
//! Serves MCP tools to the OpenCode server, one JSON-RPC message per WebSocket text frame. [`connect`] reconnects
//! with backoff until the connection closes or drops.
use std::sync::Arc;
use std::time::Duration;
+1 -2
View File
@@ -1,5 +1,4 @@
//! Client errors, mirroring the reasons of the TypeScript `ClientError`
//! (`packages/client/src/promise/generated/client-error.ts`), plus declared error bodies.
//! Transport failures and declared server errors.
use serde_json::Value;
+4 -20
View File
@@ -1,16 +1,6 @@
//! Event subscription and the connection loop (F.3).
//!
//! Both are generic over the event type, so the generated event union plugs in through [`Event`].
//!
//! - [`SharedEvents`] ports `packages/client/src/shared-events.ts`: subscribers share one upstream
//! stream, filter by type (`server.connected` always passes), a late subscriber gets the latest
//! `server.connected`, and a subscriber that falls 4,096 events behind fails alone.
//! - [`connect`] ports `createClientConnection` (`packages/client/src/solid/connection.ts`): the stream
//! must start with `server.connected` within 2 s, any received bytes count as activity, 45 s of
//! silence and 1 s of grace replace the stream (deviation `parity/deviations/A09-stall-grace.md`), a disconnect reconnects after 1 s, and events reach the consumer in
//! 10 ms batches with adjacent deltas merged. The batch queue is bounded: when it is full the loop
//! drops the stream and reconnects, and the consumer resynchronizes on the next `server.connected`
//! (deviation `parity/deviations/A09-bounded-queue.md`).
//! Subscribers share one upstream and receive the latest `server.connected` even when filtered. A lagging subscriber
//! fails independently. On overflow the connection drops the stream rather than silently losing deltas; consumers
//! resynchronize on the next `server.connected`.
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
@@ -806,8 +796,6 @@ mod tests {
item.expect("an event").expect("not an error")
}
// Ports of packages/client/test/shared-events.test.ts.
#[tokio::test]
async fn creation_subscription_and_idle_subscriptions_are_lazy() {
let fake = Fake::default();
@@ -1090,8 +1078,6 @@ mod tests {
assert_eq!(count.load(Ordering::SeqCst), 2);
}
// Ports of packages/client/test/solid-connection.test.ts, plus the A09 batching and queue rules.
fn options(idle: u64) -> Options {
Options { flush_interval: Duration::ZERO, idle_timeout: Duration::from_millis(idle), ..Options::default() }
}
@@ -1151,8 +1137,7 @@ mod tests {
assert_eq!(events.len(), 1);
}
// R4-1: after a Ctrl+Z the idle deadline has passed when the process resumes, and the runtime can
// see the timer before the socket's buffered events. Those events must not be dropped.
// A process resuming from suspension may have both an expired idle timer and buffered socket events.
#[tokio::test(start_paused = true)]
async fn events_buffered_while_stopped_survive_an_elapsed_idle_deadline() {
let fake = Fake::default();
@@ -1222,7 +1207,6 @@ mod tests {
}
}
// rs-ms1-accept problem 1: a reader panic ended the loop, and with it every later event.
#[tokio::test(start_paused = true)]
async fn a_reader_that_fails_or_panics_once_reconnects_and_keeps_delivering() {
#[derive(Clone)]
+3 -8
View File
@@ -1,8 +1,5 @@
//! Identifiers, ported from `packages/schema/src/identifier.ts` (F.3).
//!
//! An identifier is 12 hex digits of `timestamp * 0x1000 + counter` (bitwise inverted for descending
//! order) followed by 14 random base-62 characters. The counter restarts whenever the millisecond
//! changes, so identifiers minted in one process sort by creation within a millisecond too.
//! Identifiers start with 12 hex digits of `timestamp * 0x1000 + counter`, inverted for descending order, followed by
//! 14 random base-62 characters. The counter orders IDs minted within one millisecond.
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -73,9 +70,7 @@ mod tests {
prefix: String,
}
/// P-ORACLE: `parity/oracle/F.3-identifier.ts` records the time prefixes TypeScript mints for a
/// call sequence; the same sequence must give the same prefixes here. One test owns the global
/// counter so parallel tests cannot interleave with the sequence.
/// One test owns the global counter so parallel calls cannot interleave with the recorded sequence.
#[test]
fn matches_the_typescript_identifier_oracle() {
let cases: Vec<Case> =
+1 -5
View File
@@ -1,8 +1,4 @@
//! In-memory transport that serves recorded responses and events (`docs/testing.md`).
//!
//! [`Memory`] answers each request from the first [`Route`] that matches, streams `/api/event` from
//! [`Memory::emit`], and logs every request. P-APP builds it from a recording; other tests can use it as a
//! small fixture server.
//! In-memory HTTP transport. The first matching route answers; `/api/event` streams events from [`Memory::emit`].
use std::collections::{BTreeMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
+2 -6
View File
@@ -1,9 +1,5 @@
//! Persistent PTY socket (E.13a, row A04): a port of `packages/client/src/solid/pty.ts`.
//!
//! The server sends JSON control messages as text and terminal output as binary messages. The client sends binary
//! interaction frames: a type byte (0 for a size-only frame that claims control, 1 for input), the columns and rows as
//! big-endian `u16`, then the input bytes. [`connect`] asks for a ticket over HTTP and opens the socket through a
//! [`Connector`], so tests can serve a fake socket.
//! Persistent PTY control messages are text; output is binary. Interaction frames start with a type byte (0 claims
//! control, 1 sends input), big-endian `u16` columns and rows, then input bytes.
use serde_json::Value;
use url::Url;
+1 -3
View File
@@ -1,6 +1,4 @@
//! Query string encoding, bracket-encoded like `appendQuery`
//! (`packages/client/src/promise/generated/client.ts:2795-2810`). The encoders are `opencode-api-types`'s, which the
//! request builders use too.
//! Bracket-encoded query parameters shared with generated request builders.
pub use opencode_api_types::call::{append, encode};
pub use opencode_api_types::js::js_string;
+4 -16
View File
@@ -1,10 +1,5 @@
//! Server-sent events reader (F.3).
//!
//! A port of the SSE reader of the generated TypeScript client
//! (`packages/client/src/promise/generated/client.ts:417-473`): blocks end at a blank line, `data:` lines
//! join with newlines, CRLF and CR normalize to LF, comments and other fields are ignored, and the
//! buffered text may not exceed 16 MiB (counted in UTF-16 code units, as JavaScript counts
//! `string.length`). Each received chunk, keepalive comments included, reports activity.
//! SSE `data:` lines join with newlines; blank lines end a block. The 16 MiB buffer limit counts UTF-16 code units.
//! Every chunk, including a keepalive, signals activity.
use std::collections::VecDeque;
use std::fmt;
@@ -28,12 +23,7 @@ pub enum Error {
EventTooLarge,
}
/// Decodes a stream of body chunks into `data:` payloads.
///
/// It buffers raw bytes and splits lines on the LF, CRLF and CR bytes, which never occur inside a
/// UTF-8 sequence, so only complete lines are decoded and a code point split across chunks waits for
/// the rest of its line. Decoding a complete line with replacement gives the same text as the
/// TypeScript streaming `TextDecoder`.
/// Buffers bytes until a complete line is available, so a UTF-8 code point split across chunks is decoded only once.
#[derive(Default)]
pub struct Decoder {
/// Bytes of the unterminated last line.
@@ -323,8 +313,7 @@ mod tests {
payloads.into()
}
// solid-connection.test.ts "a reconnect does not ask the volatile event stream to replay": the reader
// keeps no `id:` field, so nothing can send a Last-Event-ID.
// Volatile streams must not request replay via Last-Event-ID.
#[test]
fn ignores_fields_other_than_data() {
let mut decoder = Decoder::new();
@@ -348,7 +337,6 @@ mod tests {
assert_eq!(payloads, vec!["a\nb"]);
}
// rs-ms1-accept problem 1: a chunk that ended in a multibyte character panicked on the next chunk.
#[test]
fn a_buffer_ending_in_a_multibyte_character_takes_the_next_chunk() {
let mut decoder = Decoder::new();
+1 -3
View File
@@ -86,8 +86,7 @@ pub trait Transport: Send + Sync {
}
}
/// The checked response of a server-sent events endpoint: status and content type are verified, and
/// the body has not been read. F.3 parses it into events of type `T`.
/// An unread event stream whose status and content type have been checked.
pub struct SseResponse<T> {
pub response: Response,
event: PhantomData<fn() -> T>,
@@ -107,7 +106,6 @@ impl<T: DeserializeOwned + Send> SseResponse<T> {
}
}
/// Lets F.3's connection loop and shared subscription carry the generated event type.
impl crate::events::Event for V2Event {
fn kind(&self) -> &str {
self.tag()
+2 -6
View File
@@ -1,9 +1,5 @@
//! WebSocket helper with tickets (F.3).
//!
//! Builds socket URLs the way the TypeScript clients do (`packages/client/src/solid/pty.ts:69-77`,
//! `packages/client/src/mcp.ts:166-174`) and opens them with tokio-tungstenite. A ticket socket, such as
//! the persistent PTY, authenticates with a `ticket` query parameter that the caller first requests over
//! HTTP with `x-opencode-ticket: 1`; other sockets send the `authorization` header in the handshake.
//! A ticket socket authenticates with a query parameter obtained over HTTP with `x-opencode-ticket: 1`. Other sockets
//! use `authorization` in the handshake.
use std::future::Future;
use std::pin::Pin;
-1
View File
@@ -154,7 +154,6 @@ async fn content_type_and_empty_bodies_are_checked() {
let error = client(&script).session_active().await.unwrap_err();
assert!(matches!(error, Error::MalformedResponse(_)), "{error:?}");
// A schema mismatch names its position (parity/deviations/A01-decode-error-position.md).
let script = Script::new(200, "application/json", r#"{"data":{"ses_1":{"type":7}}}"#);
let error = client(&script).session_active().await.unwrap_err();
assert_eq!(
-2
View File
@@ -172,8 +172,6 @@ async fn live_reads_decode() {
report.check("session.context", client.session_context(&input).await, |_| String::new());
}
// The session log of the newest sessions from the start, without following: durable events and the
// `log.synced` marker, none of them unknown (carbon-1).
let (mut durable, mut synced, mut unknown) = (0, 0, 0);
for session in sessions.iter().take(sessions_wanted) {
let input = ExperimentalSessionLogInput { session_id: session.id.clone(), after: Some(0), follow: Some(false) };
+1 -2
View File
@@ -1,5 +1,4 @@
//! P-ORACLE: the generated client builds the same requests as the TypeScript Promise client.
//! `parity/oracle/F.2-requests.ts` records the TypeScript side into `parity/fixtures/F.2/requests.json`.
//! Compares generated requests with those of the TypeScript Promise client.
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
@@ -1,13 +1,7 @@
//! Regression tests for the `carbon` review of F.2 (`reviews/rs-api-codegen.review-carbon.md`). Each failed
//! before `rs-api-fixes`: carbon-1 and 2 did not compile against the old types (or decoded into the wrong
//! variant), and carbon-4 and 5 failed their assertions. carbon-3 (one type for the event and REST twins of a
//! schema) is a property of the generated types, not of behavior, and has no test.
use opencode_api::error::{DeclaredError, TaggedError};
use opencode_api::generated::*;
use serde_json::json;
/// carbon-1: `log.synced` in the session log is its own variant, not a durable event of unknown type.
#[test]
fn session_log_routes_log_synced_and_durable_events() {
let synced: SessionLogItem =
@@ -20,7 +14,6 @@ fn session_log_routes_log_synced_and_durable_events() {
assert!(matches!(unknown, SessionLogItem::Unknown(_)), "{unknown:?}");
}
/// carbon-2: `Schema.NonEmptyArray(T)` is `Vec<T>`, so form fields and tool content are typed.
#[test]
fn non_empty_arrays_keep_their_item_type() {
let form: FormInfo = serde_json::from_value(json!({
@@ -40,7 +33,6 @@ fn non_empty_arrays_keep_their_item_type() {
assert!(matches!(&content[1], ToolContent::File(file) if file.mime == "image/png"));
}
/// carbon-4: an LSP server entry that sets `disabled` decodes as a server, with its command.
#[test]
fn lsp_server_entry_with_disabled_keeps_its_command() {
let entry: ConfigEntryDocumentInfoLspObjectValue =
@@ -54,7 +46,6 @@ fn lsp_server_entry_with_disabled_keeps_its_command() {
assert!(matches!(disabled, ConfigEntryDocumentInfoLspObjectValue::Object(_)), "{disabled:?}");
}
/// carbon-5: `DeclaredError::decode` checks the tag, as the TypeScript `is<Error>` guards do.
#[test]
fn declared_error_decode_checks_the_tag() {
let error = DeclaredError::new(
+1 -1
View File
@@ -1,4 +1,4 @@
//! `ui.capture` and `ui.matches` from captured cells, as `actions.ts` reads Core's render buffer.
//! Reads capture and match results from rendered cells.
use opentui::native::Capture;
use serde_json::{Value, json};
+1 -5
View File
@@ -1,10 +1,7 @@
//! The terminal bytes Core's mock input sends for each action (`@opentui/core/testing` `createMockKeys` with
//! `kittyKeyboard: true`, as the TS simulation renderer sets it, and `createMockMouse`). The endpoint feeds them to
//! the app's input parser, so both clients parse the same bytes.
//! Encodes simulated keyboard and mouse input as terminal bytes so actions exercise the real input parser.
use serde::Deserialize;
/// `KeyCodes` in `mock-keys.ts`.
const KEY_CODES: &[(&str, &str)] = &[
("RETURN", "\r"),
("LINEFEED", "\n"),
@@ -32,7 +29,6 @@ const KEY_CODES: &[(&str, &str)] = &[
("F12", "\x1b[24~"),
];
/// `kittyKeyCodeMap` in `mock-keys.ts`.
const KITTY_CODES: &[(&str, u32)] = &[
("escape", 27),
("tab", 9),
+2 -4
View File
@@ -1,7 +1,5 @@
//! The simulation UI endpoint, `OPENCODE_DRIVE` (H.4): a WebSocket server that drives a headless app as
//! `packages/simulation/src/frontend` drives the TS TUI. Requests run on the UI thread, one at a time; each action
//! feeds the bytes Core's mock input would send to the app's input parser, then paints a frame, as `actions.ts`
//! calls `renderOnce`. Mapping: OpenTUI's `packages/rust/crates/opentui/docs/headless.md`.
//! `OPENCODE_DRIVE` serves a headless app over WebSocket. Each action runs on the UI thread and paints one frame
//! before the next request.
pub mod capture;
pub mod keys;
+3 -3
View File
@@ -1,4 +1,4 @@
//! The drive manifest, as `packages/simulation/src/manifest.ts` resolves it from `OPENCODE_DRIVE`.
//! Resolves the drive manifest from `OPENCODE_DRIVE`.
use opencode_util::path::Flavor;
use serde::Deserialize;
@@ -19,7 +19,7 @@ pub struct Manifest {
}
impl Manifest {
/// The defaults for `OPENCODE_DRIVE=1` (`manifest.ts` `defaults`).
/// Endpoints for `OPENCODE_DRIVE=1`.
pub fn defaults() -> Self {
Self {
ui: "ws://127.0.0.1:40900".into(),
@@ -138,7 +138,7 @@ fn decode(contents: &str) -> Result<Manifest, String> {
Ok(Manifest { ui: raw.endpoints.ui, backend: raw.endpoints.backend, viewport, recording })
}
/// A `ws://127.0.0.1:<port>` endpoint's address, as `manifest.ts` `Endpoint` accepts it.
/// Accepts only a loopback WebSocket endpoint.
fn endpoint(value: &str) -> Option<SocketAddr> {
let url = opencode_api_types::js::parse_url(value).ok()?;
let port = url.port().filter(|port| *port >= 1)?;
+2 -5
View File
@@ -1,14 +1,11 @@
//! The UI half of the simulation protocol (`packages/protocol/src/simulation.ts`): JSON-RPC 2.0 requests over a
//! WebSocket, decoded as `Frontend.Request` decodes them, and the handshake.
//! Simulation handshake and JSON-RPC requests over WebSocket.
use crate::keys::{Direction, KeyModifiers, Mouse};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
/// The capabilities this endpoint implements, in `Frontend.Capabilities` order. `ui.focus`, `ui.click`,
/// `ui.state`, and `ui.snapshot` name renderable numbers, which the Rust TUI has none of (plan 7.3), and the endpoint
/// does not record (`ui.recording.*`).
/// Capabilities are advertised in protocol order. Renderable IDs and recording are unsupported.
pub const CAPABILITIES: &[&str] =
&["ui.type", "ui.press", "ui.enter", "ui.arrow", "ui.mouse", "ui.resize", "ui.matches", "ui.capture"];
+10 -31
View File
@@ -1,12 +1,5 @@
//! `--server`, standalone, registered service, or ensure (F.6).
//!
//! Ports `ServerConnection.resolve` (`packages/cli/src/services/server-connection.ts:25-64`) with
//! two changes (plan 6.6, decision O-21): a service is found through [`discover`], which tries more
//! than one registration, and a service of another version is used with a warning in the log. The
//! exception is `mismatch: "replace"` ([`Options::replace`], O-167), which the TUI and `mini` ask for
//! as TS's do: a service of another version registered in the client's own channel is restarted on
//! the TypeScript binary the client resolved. When none is found, [`ensure`] starts the TypeScript
//! service (`docs/architecture.md`).
//! Resolves an explicit server, standalone process, or shared service. Only the client's own channel is eligible for
//! version replacement.
use opencode_api::error::Error as ApiError;
use opencode_api::transport::Transport;
@@ -26,7 +19,6 @@ use crate::ts_command::TsCommand;
pub use crate::ensure::Reason;
/// How long `--server` waits for `/api/info` (`server-connection.ts:40`).
pub const SERVER_TIMEOUT: Duration = Duration::from_secs(5);
/// What the command line asked for.
@@ -39,9 +31,8 @@ pub struct Options {
/// Use a standalone server instead of starting the service when none runs (`autostart: false`,
/// which `run` uses so a one-off run leaves no service behind).
pub standalone_fallback: bool,
/// `mismatch: "replace"` (O-167): a service of another version than `client_version`, registered in the client's
/// own channel, is restarted on the resolved TypeScript binary, as TS's TUI and `mini` restart it. Otherwise any
/// version is used (`"ignore"`, the other commands').
/// Restart a mismatched service in the client's own channel using the resolved TypeScript binary. Otherwise
/// accept any version.
pub replace: bool,
/// Runs once before the service is started or restarted, for "Starting background server..." and "Restarting
/// background server (version mismatch)...".
@@ -51,7 +42,7 @@ pub struct Options {
/// The environment `resolve` reads.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Env {
/// `OPENCODE_PASSWORD`, else `OPENCODE_SERVER_PASSWORD` (`packages/cli/src/env.ts:10-13`).
/// Falls back to `OPENCODE_SERVER_PASSWORD` when `OPENCODE_PASSWORD` is unset.
pub password: Option<String>,
/// `OPENCODE_CHANNEL`.
pub channel: Option<String>,
@@ -114,8 +105,7 @@ pub struct Connection {
/// The version the server reported.
pub version: String,
pub source: Source,
/// The mismatch warning for `--server`, already written to stderr. A mismatch with a
/// discovered service is only logged (decision O-22), unless [`Options::replace`] restarted it (O-167).
/// A warning already printed for an explicit server. A discovered service's version mismatch is only logged.
pub warning: Option<String>,
}
@@ -226,9 +216,7 @@ pub async fn resolve(
})
}
/// Finds the registered service again, for a client that lost it (`managedService.reconnect`,
/// `packages/cli/src/services/server-connection.ts:66-75`): discovered, waited for, or started
/// quietly when none is registered.
/// Rediscovers the registered service after disconnecting, starting one quietly if necessary.
pub async fn reconnect(transport: Arc<dyn Transport>, paths: &Paths, env: &Env) -> Result<discover::Found, Error> {
match discover::discover_with(transport.as_ref(), paths, env.channel.as_deref(), &discover::Owner::new(env.ts()))
.await
@@ -247,9 +235,7 @@ pub async fn reconnect(transport: Arc<dyn Transport>, paths: &Paths, env: &Env)
}
}
// `ensure` when discovery found no ready service: waits for a pending one, reports a failed one,
// and starts the service in `file` only when no live service is registered. It never starts a
// service beside one that is starting or not answering (O-21).
// Never start a second service beside one that is starting or unresponsive.
async fn ensure_missing(
transport: Arc<dyn Transport>,
paths: &Paths,
@@ -267,11 +253,8 @@ async fn ensure_missing(
run_ensure(transport, paths, env, config, missing.pending.unwrap_or(file), None, on_start).await
}
// Whether a service is restarted (O-167): its version is not the client's, and the TypeScript binary the client
// resolved would start another version than it runs. That second test is the Rust client's own: TS restarts on its own
// binary, which is the client's version by construction, as the bundled one is. A binary that says nothing in time is
// tried; one of the service's version (`OPENCODE_TS_BIN` or `opencode` on `PATH` behind a development build) would only
// start the same version again, on every start.
// A development client and its server binary can have different versions. Replacing a service with the same server
// version would restart it on every launch. Try the binary if its version probe times out.
async fn restarts(env: &Env, found: &discover::Found, client_version: &str) -> bool {
let running = found.service.version.as_deref();
if running == Some(client_version) {
@@ -332,7 +315,6 @@ async fn server_version(transport: Arc<dyn Transport>, endpoint: &Endpoint) -> R
}
}
// `connectError` (`server-connection.ts:99-114`).
fn connect_error(endpoint: &Endpoint, error: &ApiError) -> Error {
let url = &endpoint.url;
if error.reason() == "UnauthorizedError" {
@@ -414,7 +396,6 @@ mod tests {
#[tokio::test]
async fn server_flag_connects_with_the_password_and_warns_on_a_mismatch() {
let env = Env::from_vars(|name| (name == "OPENCODE_SERVER_PASSWORD").then(|| "pw".to_owned()));
// Expected (O-167): `--server` only warns, also for a client that restarts a discovered service.
let replacing = Options { replace: true, ..options(Some(URL)) };
let (result, server) = run(Server::default().reply(INFO, Reply::json(200, HEALTH)), env, replacing).await;
let connection = result.unwrap();
@@ -484,8 +465,6 @@ mod tests {
connection.source,
Source::Service { channel: "oc-x".to_owned(), file: paths.state.join("service-oc-x.json"), pid: 9 }
);
// Versions differ (2.0.0 against 1.0.0), but a discovered service's mismatch is only
// logged (O-22).
assert_eq!(connection.warning, None);
let endpoint = Endpoint::new(URL, None);
assert!(mismatch(&endpoint, "2.0.0", &options(None)).is_some());
@@ -1,9 +1,5 @@
//! Contender pool (F.9).
//!
//! Ports `contenderPool` (`packages/client/src/service-contender.ts:57-136`): the startup attempts of
//! one `ensure` call. It keeps at most two alive, remembers the first startup failure, and backs off
//! when attempts exit cleanly because another one won. The clock is an argument, so tests need
//! neither processes nor sleeps.
//! Limits concurrent service startup attempts to two. A clean exit means another contender won; back off but retain
//! the first startup error.
use std::time::{Duration, Instant};
@@ -172,7 +168,6 @@ mod tests {
use std::cell::Cell;
use std::rc::Rc;
// The cases of `packages/client/test/service-contender-pool.test.ts`, on fake attempts.
#[derive(Clone)]
struct Fake {
pid: u32,
+5 -17
View File
@@ -1,11 +1,5 @@
//! Delegation of commands to the TypeScript binary (D.1).
//!
//! `serve`, `uninstall`, and `plugin *` depend on the server, the installer, npm, and `Host.resolve`, which
//! exist only in TypeScript (user Q4). `upgrade` is not delegated: it upgrades nothing (deviation D01-upgrade).
//! The Rust client runs the TypeScript `opencode` ([`TsCommand`]) with the same arguments, stdio, and exit
//! code. Remote access (`service set remote true`, `pair --remote`) needs the OpenTunnel SDK, so
//! [`enable_remote`] runs the TypeScript command that creates the tunnel, and [`tunnel_hostname`] reads what the
//! SDK stored.
//! Commands delegated to `opencode` inherit the arguments, stdio and exit status. Remote access uses the TypeScript
//! command because it owns the OpenTunnel SDK.
use std::ffi::OsString;
use std::io;
@@ -64,19 +58,13 @@ pub fn spawn(command: &TsCommand, args: impl IntoIterator<Item = OsString>) -> R
build(command, args).spawn().map_err(|source| start_error(command, source))
}
/// Turns remote access on through `opencode service set remote true`: it creates the device's
/// OpenTunnel tunnel in the foreground (printing "Setting up remote access; this can take a
/// minute..." the first time), stops the service, and writes the route to the service config
/// (`packages/cli/src/services/service-config.ts:261-270`). Returns the started child; on failure it
/// prints its own error before it exits.
/// Starts `opencode service set remote true` in the foreground. The child creates the tunnel, stops the service and
/// saves the route.
pub fn enable_remote(command: &TsCommand) -> Result<Child, StartError> {
spawn(command, ["service", "set", "remote", "true"].map(OsString::from))
}
/// The remote hostname of `route`, `<route>.<tunnel hostname>`, or `None` until the tunnel's
/// certificate is ready. Ports `RemoteTunnel.hostname` (`services/remote-tunnel.ts:67-71`) over the
/// SDK's XDG storage: `<XDG_DATA_HOME>/opentunnel/default/tunnel.json`, valid only with the token,
/// key, certificate, and chain beside it.
/// Returns the route hostname once the OpenTunnel token, key, certificate and chain are present.
pub fn tunnel_hostname(paths: &Paths, route: &str) -> io::Result<Option<String>> {
let data_home = paths.data.parent().unwrap_or(&paths.data);
let root = data_home.join("opentunnel").join("default");
+4 -18
View File
@@ -1,17 +1,6 @@
//! Registration discovery (F.6).
//!
//! The TypeScript client reads the registration of its build channel and probes it
//! (`discover`, `packages/client/src/effect/service.ts:25-31`). The Rust client has no build
//! channel, and the installed `opencode` may be a preview channel with its own file, so it tries
//! several registrations in order (decision O-21):
//!
//! 1. the registration of `OPENCODE_CHANNEL`, when set;
//! 2. the registration of the client's own channel ([`channel::DEFAULT`]);
//! 3. every other `service*.json` in the state directory: the one whose server runs the TypeScript
//! binary this client delegates to ([`Owner`], decision O-51), else the newest.
//!
//! The first ready, compatible service wins. Discovery only reads: it never migrates, replaces, or
//! stops a service.
//! Looks first in `OPENCODE_CHANNEL`, then the client's default channel, then other registrations. Among scanned
//! services, prefer one owned by the resolved `opencode` binary; otherwise prefer the newest. Discovery never
//! modifies a registration or stops a service.
use std::path::{Path, PathBuf};
@@ -83,10 +72,7 @@ pub async fn discover_with(
Ok(owner.pick(ready).await)
}
/// The TypeScript binary this client delegates to (D.1). When several scanned services answer,
/// discovery takes the newest that this binary runs, so the Rust client uses the same server as
/// the user's `opencode` (O-51). The process executable decides (Linux `/proc/<pid>/exe`); when no
/// service runs it, the version the binary prints does.
/// Identifies the server binary by executable path, falling back to its reported version when no process matches.
pub struct Owner {
command: TsCommand,
process_executable: Box<dyn Fn(u32) -> Option<PathBuf> + Send + Sync>,
+5 -15
View File
@@ -1,10 +1,5 @@
//! Ensure a background service runs (F.9).
//!
//! Ports `ensure` (`packages/client/src/effect/service.ts:45-127`) with the policy of
//! `docs/architecture.md`: reuse a service that answers, whatever its version unless a version is required;
//! wait for one that is starting; start TypeScript contenders only when none is registered or the
//! registered process is gone; never stop a running service this call did not start, except one of
//! another version than [`Options::version`] requires (O-167), which it replaces as TS does.
//! Reuses a ready service and waits for a starting one. Start contenders only if no live process owns the
//! registration.
use std::ffi::OsString;
use std::path::PathBuf;
@@ -23,7 +18,6 @@ use crate::spawn::Contender;
use crate::stop::{self, Poll};
use crate::ts_command::TsCommand;
/// `EnsureTiming` (`packages/client/src/service-timing.ts`).
#[derive(Clone, Copy, Debug)]
pub struct Timing {
pub poll: Duration,
@@ -58,10 +52,8 @@ pub struct Options {
pub command: Vec<OsString>,
/// Added to the inherited environment (the service config's `env`).
pub env: Vec<(String, String)>,
/// The version a service registered in `file` before this call must have (`EnsureOptions.version`, exact): one of
/// another version is stopped, handing its terminals over when it is ready, and replaced (O-167). A service this
/// call started is used whatever its version, so a TS binary of another version than required is not replaced in
/// a loop. `None` uses any version.
/// Required version of a pre-existing service. Accept any version started by this call to avoid a replacement
/// loop.
pub version: Option<String>,
pub timing: Timing,
}
@@ -221,9 +213,7 @@ impl Run<'_> {
Ok(())
}
// A service of another version than required (`decision._tag === "replace"`, `service.ts:98-104`): announced,
// stopped with its terminals handed over when it is ready, and evicted, so the next round starts the replacement.
// A failed stop is ignored, as TS ignores it; the next round finds the service again and tries again.
// A ready service hands off terminals before replacement. If stopping fails, the next round discovers it again.
async fn replace(&mut self, service: &LocalService, handoff: bool) {
self.announce_reason(Reason::VersionMismatch { previous: service.version.clone() });
if !handoff {
+3 -13
View File
@@ -1,14 +1,5 @@
//! A client that follows a managed service across restarts.
//!
//! A restarted background service may register a new port or password. The TypeScript TUI then
//! runs `service.reconnect` (an ensure) after each event-stream disconnect and swaps its client's
//! URL and headers (`packages/tui/src/context/client.tsx:33-41`). Every part of the Rust TUI holds
//! a clone of one [`Client`], so the swap happens below it, in the transport: requests to the
//! origin the client was built for go to the current service with its current password. A request
//! that fails to connect or is refused with 401 finds the service again, through
//! [`connect::reconnect`], before it returns its error. The request is not retried, so a request
//! that may have reached the old service is never sent twice. The event stream retries itself and
//! finds the service through [`Transport::reconnect`], between attempts.
//! Follows a managed service across port and password changes. A failed connection or 401 triggers rediscovery for
//! future requests; replaying the failed request could duplicate a write.
use std::sync::{Arc, RwLock};
@@ -54,7 +45,6 @@ struct Follow {
env: Env,
}
/// Where requests go now.
struct Route {
url: url::Url,
auth: Option<Auth>,
@@ -131,7 +121,7 @@ impl Follow {
route.generation
}
// Finds the service again, unless another request did since `generation`. True when it is found.
// Rediscovers the service unless another request has already advanced `generation`.
async fn resolve(&self, generation: u64) -> bool {
let _resolving = self.resolving.lock().await;
if self.route.read().expect("route lock").generation != generation {
@@ -1,9 +1,5 @@
//! PTY handoff (F.9).
//!
//! Ports `packages/client/src/pty-handoff.ts`. Before a service stops for a restart, its persistent
//! terminals are published in a sidecar, `<registration>.pty-handoff`, so the next service adopts
//! them through `OPENCODE_PTY_HANDOFF`. Every step is best effort: a failure stops the service
//! without a handoff.
//! Before restart, persistent terminals are published in `<registration>.pty-handoff` for adoption with
//! `OPENCODE_PTY_HANDOFF`. A failed handoff does not prevent shutdown.
use opencode_api::transport::Transport;
use opencode_local::registration::Registration;
+2 -12
View File
@@ -1,7 +1,4 @@
//! `/api/info` probe and classification (F.6).
//!
//! Ports `packages/client/src/service-probe.ts`: ask a registered service for its health, classify
//! the answer, and decide what a client does with it.
//! Classifies a registered service by its response to `/api/info`.
use std::sync::Arc;
use std::time::Duration;
@@ -11,8 +8,6 @@ use opencode_api::error::Error;
use opencode_api::transport::{Request, Transport};
use opencode_local::registration::Registration;
/// How long one probe waits (`defaultEnsureTiming.requestTimeout`,
/// `packages/client/src/service-timing.ts:18`).
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(2);
/// A server URL and its credentials. `Debug` hides the password.
@@ -81,7 +76,6 @@ pub enum Decision {
/// A version requirement: none, or a predicate on the service version (`DiscoverOptions.version`).
pub type Requirement<'a> = Option<&'a dyn Fn(&str) -> bool>;
/// Whether `version` meets `required` (`packages/client/src/service-version.ts`).
pub fn matches_version(version: Option<&str>, required: Requirement<'_>) -> bool {
match (required, version) {
(None, _) => true,
@@ -93,7 +87,6 @@ pub fn matches_version(version: Option<&str>, required: Requirement<'_>) -> bool
const INCOMPATIBLE: &str =
"Background service uses an incompatible health protocol. Update this client or explicitly restart the service.";
/// Decides what to do with a service that answered (`packages/client/src/service-probe.ts:22-32`).
pub fn decide(service: &LocalService, required: Requirement<'_>) -> Decision {
if !matches_version(service.version.as_deref(), required) {
return Decision::Replace { handoff: service.state == State::Ready };
@@ -108,9 +101,7 @@ pub fn decide(service: &LocalService, required: Requirement<'_>) -> Decision {
}
}
/// Asks a registered service for its health and classifies the answer
/// (`probeResult`, `packages/client/src/service-probe.ts:49-90`). Any failure to get a usable
/// answer is "no service"; so is an answer from another process (pid) or version than registered.
/// A missing response or a PID or version inconsistent with the registration counts as no service.
pub async fn probe(transport: &dyn Transport, registration: &Registration, timeout: Duration) -> Probe {
let endpoint = Endpoint::new(&registration.url, registration.password.clone());
match tokio::time::timeout(timeout, answer(transport, &endpoint)).await {
@@ -179,7 +170,6 @@ mod tests {
use super::*;
use crate::testing::{Reply, Server};
// The cases of `packages/client/test/service-decision.test.ts`.
fn service(version: Option<&str>, state: State, compatible: bool) -> LocalService {
LocalService {
registration: Registration {
+1 -4
View File
@@ -1,7 +1,4 @@
//! Spawning the TypeScript `opencode` (F.9).
//!
//! Ports `spawnServiceContender` (`packages/client/src/service-contender.ts:14-55`): a detached
//! process with stdin and stdout closed and a bounded tail of its stderr, which outlives this client.
//! Starts a detached `opencode` service with closed stdin and stdout and a bounded stderr tail.
use std::ffi::OsString;
use std::io::Read;
@@ -1,8 +1,4 @@
//! Standalone server (F.9).
//!
//! Ports `packages/cli/src/services/standalone.ts`: a private TypeScript server for this client
//! alone, with a random password. Its stdin is the ownership lease: the server exits on EOF, which
//! the OS delivers even when this client is killed.
//! A private server holds a stdin lease: EOF ends the server even if its client is killed.
use std::ffi::OsString;
use std::path::Path;
+1 -5
View File
@@ -1,8 +1,4 @@
//! Stopping the service (F.9).
//!
//! Ports `stop` and `terminate` (`packages/client/src/effect/service.ts:129-197`). Only the explicit
//! `service stop`, `restart`, and `set` commands stop a service; `ensure` never stops one it did not
//! start (plan 6.6), except one of another version than it requires (O-167).
//! Stops the registered service and waits for its process to exit.
use opencode_api::transport::Transport;
use opencode_local::registration::{self, Registration};
@@ -1,9 +1,5 @@
//! TypeScript binary resolution: `OPENCODE_TS_BIN`, else the bundled `opencode`, else `opencode` on `PATH` (F.9).
//!
//! The Rust client is not a server (user Q2). It starts the TypeScript `opencode` for the background
//! service and the standalone server, as the TypeScript client runs `selfCommand()`
//! (`packages/cli/src/services/service-config.ts:150`, `standalone.ts:18-20`). An install that bundles
//! the server puts it beside the client (`opencode_util::bundle`, bundle-server).
//! Resolves the server binary from `OPENCODE_TS_BIN`, the bundled `opencode` beside the client, or `PATH`, in that
//! order.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
@@ -1,6 +1,5 @@
//! Discovery prefers the service the TypeScript binary runs (O-51), proven with real processes:
//! two copies of `sleep` stand for `opencode` and an older `opencode2`, and a local server answers
//! `/api/info` for each with its pid. The `opencode2` registration is the newest.
//! Two executables stand in for separate service installations. The newest registration belongs to the other
//! installation.
#![cfg(target_os = "linux")]
use std::ffi::OsString;
@@ -1,13 +1,5 @@
//! Interop with the real TypeScript CLI, run from source: Rust `ensure` starts
//! `opencode serve --service`, and the TypeScript `opencode service status` in the same directories
//! sees it.
//!
//! Everything runs in a temporary `HOME`, `XDG_*`, and `OPENCODE_CONFIG_DIR`, on a free port. The
//! TypeScript CLI runs under `env -i`, so nothing of this machine's environment reaches it, and it
//! never sees the user's state directories or service. Every process is killed at the end.
//!
//! Needs `bun` and a TypeScript checkout with `node_modules`: `OPENCODE_TS_ROOT`, else this
//! repository. Without them the test passes with a note.
//! Rust starts an isolated service and the TypeScript CLI discovers it. Both use a temporary home and clean
//! environment.
#![cfg(unix)]
use std::path::{Path, PathBuf};
@@ -1,8 +1,4 @@
//! The cases of `packages/client/test/service.test.ts`, run against the same fake service
//! (`packages/client/test/fixture/service.ts` under `bun`) with the same accelerated timing. Cases
//! where TS replaces a service assert the Rust policy instead (docs/architecture.md): the service is used,
//! or left running. Every file lives in a temporary directory, and every process a test starts is
//! killed when its fixture drops. Without `bun` the tests pass with a note.
//! Service lifecycle tests share the TypeScript client's fake service and accelerated clock.
#![cfg(unix)]
use opencode_api::transport::{Reqwest, Transport};
@@ -37,7 +33,6 @@ fn bun() -> bool {
found
}
// `accelerate` (`packages/client/test/fixture/service-timing.ts`).
fn fast() -> Timing {
Timing {
poll: Duration::from_millis(20),
@@ -300,8 +295,6 @@ async fn reuses_a_registered_service() {
assert!(fixture.running(existing));
}
// Expected (O-167): with a version required, as TS's `replaces an incompatible registered service`: the service of
// another version is stopped and replaced, announced once as a version mismatch from its version.
#[tokio::test(flavor = "multi_thread")]
async fn replaces_a_service_of_another_version_when_a_version_is_required() {
needs_bun!();
@@ -319,8 +312,6 @@ async fn replaces_a_service_of_another_version_when_a_version_is_required() {
assert_eq!(reasons, [ensure::Reason::VersionMismatch { previous: Some("1.9.0".to_owned()) }]);
}
// Expected (O-167): a service of the required version is reused; one this call started is used whatever its version,
// so a TS binary of another version than required is not replaced in a loop.
#[tokio::test(flavor = "multi_thread")]
async fn a_required_version_reuses_its_service_and_takes_what_it_started() {
needs_bun!();
@@ -512,7 +503,7 @@ async fn stop_waits_for_the_original_process_while_preserving_a_newly_registered
assert!(fixture.running(successor));
}
// A stale registration whose pid now belongs to another process: `stop` must not signal it.
// A stale registration can point at an unrelated process. Never signal it.
#[tokio::test(flavor = "multi_thread")]
async fn stop_refuses_a_registered_pid_that_another_process_reused() {
let fixture = Fixture::new();
@@ -696,8 +687,7 @@ async fn finds_a_started_service_registered_under_another_channel() {
assert_eq!(status(&ensured.service.endpoint.url).await["pid"], ensured.service.registration.pid);
}
// A fake `OPENCODE_TS_BIN` of the channel `oc-y`: it logs its pid to `spawns` and serves `mode`
// under `service-oc-y.json`, beside the client's `service.json` (review carbon-2).
// This fake binary registers in `oc-y`, beside the client's default channel.
fn channel_build(fixture: &Fixture, mode: &str) -> (Options, PathBuf, PathBuf) {
let root = fixture.dir.path();
let other = root.join("service-oc-y.json");
@@ -840,8 +830,7 @@ impl Channel {
}
}
// A client of the channel `oc-x` whose TS binary prints `opencode v<binary>` for `--version` and serves `mode` (the
// fixture's) under `service-oc-x.json`, logging each start to `spawns`: the bundled binary of O-167.
// Records each start in `spawns` so the test can detect a replacement loop.
fn restarting(channel: &Channel, binary: &str, mode: &str) -> (Env, PathBuf) {
let root = channel.fixture.dir.path();
let spawns = root.join("spawns");
@@ -869,8 +858,6 @@ async fn resolve_replacing(channel: &Channel, env: &Env) -> Result<Connection, c
connect::resolve(transport(), &channel.paths, env, &options).await
}
// Expected (O-167, TS `default.ts` with `mismatch: "replace"`): the TUI's client restarts a service of another version
// in its channel on the TS binary it resolved, and attaches to the new one.
#[tokio::test(flavor = "multi_thread")]
async fn connect_restarts_a_service_of_another_version_and_attaches_to_the_new_one() {
needs_bun!();
@@ -887,9 +874,6 @@ async fn connect_restarts_a_service_of_another_version_and_attaches_to_the_new_o
assert_eq!(spawned(&spawns), 1);
}
// Expected (O-167): a service of the client's version is not touched; one of another version is used as before when
// the client does not ask to replace (`mismatch: "ignore"`, every command but the TUI and `mini`), when it is
// registered in another channel than the client's, or when the resolved binary would start its version again.
#[tokio::test(flavor = "multi_thread")]
async fn connect_restarts_nothing_else() {
needs_bun!();
@@ -914,8 +898,6 @@ async fn connect_restarts_nothing_else() {
assert_eq!(spawned(&spawns), 0);
}
// Expected (O-167, TS `ensure`): when the replacement fails to start, the old service is already stopped and the
// command fails with the start's error, as TS's does; the client attaches to nothing.
#[tokio::test(flavor = "multi_thread")]
async fn connect_fails_with_the_start_error_when_the_restart_fails() {
needs_bun!();