Compare commits

...
6 Commits
Author SHA1 Message Date
vhaudiquet 64d7f359f5 feat(api): retire ChatGPT plan sign-in by default
A room's provider serves every member, while a ChatGPT plan belongs to
one account, so sharing it breaks OpenAI's terms. Together now hides
the chatgpt kind, refuses to store a new one, and fails a room that
still points at it with a message that names the API-key route.

Existing provider rows stay in the database. The room settings dialog
keeps the room's current provider visible even when its kind is
retired, so the room shows what it is pinned to instead of silently
losing it. Creating or updating a room to that provider is refused.

`RHEMA_TOGETHER_I_WANT_CHATGPT_BAN=1` lifts the block for a single-user
local test. The value has to be exactly `1`; any other value leaves the
block in place.
2026-12-03 16:10:14 +01:00
vhaudiquet 62fa380ec0 web: show a running turn only after replay catches up
The room marked the SSE stream live when the response headers arrived, before it read the durable backlog. A replayed turn_start therefore showed "Rhema is working..." until its turn_end arrived at the end of the replay, even for a turn that had finished.

The feed now closes its replay with a live-only ready frame, and the client marks the stream live on that frame. A backlog over the 2000-row cap sends lag instead, so a skipped turn_end cannot leave the room running either.
2026-12-03 13:49:32 +01:00
vhaudiquet a40a7a6b36 room: close turns a restart left open
A turn writes turn_start before it runs and turn_end only after the
work settles. A restart in between leaves the log with one open turn,
and the client replays it as running, so the room shows
"Rhema is working..." over no task.

At startup, close every start without an end with an interrupted
turn_end, which the log already renders as "rhema stopped".
2026-12-03 12:45:17 +01:00
vhaudiquet c67d8af42d api: let the openai provider pin chat or responses
The openai kind already accepts a base URL, and the registry already
takes an explicit API choice, but the app always passed none. An
OpenAI-compatible server therefore had to answer chat completions.

The add-provider dialog now shows an API type for the openai kind:
automatic, chat completions, or responses. Automatic keeps the old
route rule, Responses at OpenAI itself and chat completions at a base
URL; an explicit choice pins either. A separate provider kind would
store the same fields and need the same adapter wiring.
2026-12-02 19:23:28 +01:00
vhaudiquet 1289f5f0c2 room: add a per-room thinking effort
Every turn sent ThinkingEffort::Default, so a room could not ask
for more or less reasoning. The owner now picks default, low, medium,
or high in room settings. An existing database gains the column with
a default of 'default', which sends no effort parameter and leaves
the provider's choice alone.
2026-12-02 19:20:28 +01:00
kosmos 0a3c7b7b45 room: steer mid-turn chat to the next step boundary
A message posted without a mention while the agent worked waited for the
next turn, so the model read it only once the work the line was about was
finished. The spec's turn rules already promised the mid-turn half ("the
next step of the running turn"); the runner implemented the turn-boundary
half only.

The turn now hands the framework's steering hook a source over the room's
`absorbed_seq` cursor. The driver drains it between two steps and appends
one User-role message per drain, so the line lands in the history without
the step in flight dying. The drain stops at the first line it cannot
carry, a mention (the drop path owns that one) or a message with images (a
line of text cannot hold them), and leaves the cursor there, so the
boundary pass appends them in the log's order.

The row has one writer. `drain` carries the cursor in memory only, and
`commit` writes it after `save_session` succeeds, which is the order the
boundary pass already uses: append, checkpoint, advance. The boundary pass
hands its own cursor to the turn in the config the turn reads, so the
first drain never reads back what that pass just appended. A line retired
too early would be gone, one that comes back is deduped within the turn.

A mention still drops the turn: that is the only way to stop a running
command, and this change does not touch it.

Co-authored-by: Kosmos <kosmos@vhaudiquet.fr>
2026-12-02 17:02:49 +00:00
16 changed files with 936 additions and 95 deletions

No files matched your search

+5 -1
View File
@@ -82,7 +82,11 @@ web/app/ Nuxt 4 SPA (no SSR)
before its last message. `message` is `ReplaySafety::Unsafe`.
- Turns are serialized per room. A new mention while a turn runs drops
the turn future (turn-level steering) and starts a new turn over the
committed session. Do not drop the room task.
committed session. A message without a mention never drops anything:
`runner::RoomSteering` hands it to the framework's steering hook, which
appends it at the next step boundary; the turn advances `absorbed_seq`
once that session is saved, so the next boundary pass cannot repeat it.
Do not drop the room task.
- The preview host label is `r<room>-p<port>-<expiry>-<hmac>.<preview
host>` for a port, or `r<room>-s<hash>-<expiry>-<hmac>.<preview host>`
for a static target. The HMAC covers the target and expiry with a key
+7 -4
View File
@@ -104,10 +104,13 @@ issue certificates.
## First room
1. **Settings → Providers.** Add a provider kind and its key, address,
or sign-in. For GitHub Copilot, ChatGPT, and Mistral Vibe the dialog
runs the provider's sign-in. The credential is sealed with the
server's master key before it touches SQLite. A new provider stores
no model; the room picks one.
or sign-in. For GitHub Copilot and Mistral Vibe the dialog runs the
provider's sign-in. Together does not offer ChatGPT plan sign-in;
use the openai kind with an API key instead. Set
`RHEMA_TOGETHER_I_WANT_CHATGPT_BAN=1` to lift the block for a
single-user local test; a shared room still breaks OpenAI's terms.
The credential is sealed with the server's master key before it
touches SQLite. A new provider stores no model; the room picks one.
2. **Settings → Sandboxes.** Add a target. Leave the private key empty
and the server generates an ed25519 pair and shows the public key.
Append that line to `~/.ssh/authorized_keys` on the target. Set the
+48 -11
View File
@@ -57,6 +57,7 @@ A room holds:
| sandbox_target | the owner's ssh target |
| provider_config | whose model key pays |
| model | model id chosen for this room |
| thinking_effort | reasoning level the turn sends: default, low, medium, high |
| max_turn_steps | runaway guard, default 48 |
| created_at, archived_at | |
@@ -190,6 +191,21 @@ an `absorbed_seq` cursor, so nothing is appended twice. The cursor
advances on every append, whatever the path, so the boundary pass and
the interrupt path cannot both write the same line.
The mid-turn half of that is the framework's steering hook
(`HostAgentConfig::steering`), not a step-level drop: the turn's
`RoomSteering` source hands the driver one User-role line per drain at a
step boundary, so a member can correct the agent while it works without
the step in flight dying. It stops at the first line it cannot carry, a
mention (the drop path owns that one) or a message with images (a line
of text cannot hold them), and leaves the cursor there, so the boundary
pass appends them in the log's order. The source only reads that
cursor. The turn writes it after the session holding the drained lines
is saved, the order the boundary pass already uses: append, checkpoint,
advance. A crash before the checkpoint repeats a line at worst, and the
framework's per-turn dedupe drops the repeat. What steering still cannot
do is stop a running command: only the mention drop does that, and only
between steps.
A burst of mentions that lands before the first drop completes all goes
into the same restart, in order, one message each. Nothing is folded.
@@ -362,6 +378,9 @@ shows `Rhema is working...` until `turn_end`. When the turn ends, the log
gets one collapsed line: `rhema finished · 3 steps`. Expanding it shows the
draft text, thinking, tool calls, and usage. Nothing from the model stream
is visible by default. The summary line is per turn, not per message.
An open turn does not outlive the process: at startup the server appends
an interrupted `turn_end` for any `turn_start` without one, so a restart
cannot leave the status line working over no task.
### Preview
@@ -509,6 +528,12 @@ Every stream is resumable by sequence number. A reconnect asks for
`since=<last seq>` and gets the gap, then live frames. The hub's
record-under-one-lock trick is the shape to copy: no gap, no overlap.
The replay ends with a live-only `ready` frame. A backlog larger than
the 2000-row cap sends `lag` instead, and the client resumes from its
last processed sequence. The room shows `Rhema is working...` only after
`ready`, so replaying a turn that already ended does not claim it is
still running.
## 8. Auth and trust
### Accounts
@@ -575,7 +600,7 @@ it. No route, log line, or event carries a stored key.
### Provider sign-in
GitHub Copilot, ChatGPT, and Mistral Vibe do not ask for a key. The
GitHub Copilot and Mistral Vibe do not ask for a key. The
server runs the adapter's `InteractiveLogin` and keeps a per-account
record of its last update. The browser asks the server to start the
flow, polls the record, and renders the instruction, URL, and code. It
@@ -587,10 +612,14 @@ their owner can read or cancel them. They live in memory, so a restart
drops a sign-in in progress. No provider row exists until the adapter
completes.
ChatGPT's callback returns to loopback port 1455, or 1457 when 1455 is
taken. The machine that runs the browser must forward that port to the
server before opening the URL. Copilot's device code and Mistral Vibe's
console sign-in need no inbound port.
Together does not offer ChatGPT plan sign-in by default. A ChatGPT
subscription is personal, and a room's provider serves every member,
so a shared room uses an API-key kind such as `openai`. Existing
`chatgpt` provider rows stay in the database but fail with a clear
message, and neither a new room nor a room settings change can point
at that kind. Setting `RHEMA_TOGETHER_I_WANT_CHATGPT_BAN=1` lifts the
block for a single-user local test; it does not make a shared room
compliant.
A sign-in URL can carry a short-lived device or PKCE token. The server
does not log it, and it is not the stored provider key.
@@ -602,14 +631,17 @@ One SQLite file in WAL mode.
```
accounts(id, handle, display_name, email, password_hash, created_at)
auth_sessions(token_hash, account_id, created_at, expires_at, last_seen)
provider_configs(id, account_id, name, kind, model, base_url, key_ciphertext)
provider_configs(id, account_id, name, kind, model, base_url, api,
key_ciphertext)
-- model is an optional default kept for existing rows; rooms carry
-- the model that turns use
-- api is chat or responses for the openai kind; unset follows the
-- route: Responses at OpenAI, chat completions at a base URL
sandbox_targets(id, account_id, name, host, user, port, key_ciphertext,
workspace_root, host_key, created_at)
rooms(id, name, owner_id, workspace, cwd, sandbox_target_id,
provider_config_id, model, max_turn_steps, absorbed_seq,
created_at, archived_at)
provider_config_id, model, thinking_effort, max_turn_steps,
absorbed_seq, created_at, archived_at)
members(room_id, id, account_id, display_name, role, color, guest_token_hash,
joined_at)
invites(token_hash, room_id, role, created_by, expires_at, max_uses, uses)
@@ -663,7 +695,10 @@ Backups: the SQLite file (attachments included) and the secret key.
Small and additive, in the framework's own terms:
1. `HostAgent::step` plus the turn setup around it, so a frontend can own
the loop and drop one step. `rhema-code` steers at turn level: it
the loop and drop one step. The steering hook covers the common case
today: chat lands at a step boundary without a drop. A drop is still
what stops a long command, and it still costs the whole turn.
`rhema-code` steers at turn level: it
drops the whole turn future and starts a new turn with the nudge on
the same agent and session (`turn.rs`). That is enough for a
single-user TUI, where a turn boundary is a ledger row. A room wants
@@ -744,8 +779,10 @@ This repository, as committed:
- A model picker over the provider's live catalog, with context,
output, price, and vision from the adapter and models.dev. A custom
id is always accepted. The add-provider dialog asks for a kind and
key, or runs a sign-in for GitHub Copilot, ChatGPT, and Mistral Vibe.
The room chooses the model.
key, or runs a sign-in for GitHub Copilot and Mistral Vibe.
An OpenAI provider also takes a base URL and an explicit chat
completions or responses API, so one kind reaches OpenAI itself and
any compatible server. The room chooses the model.
- One conversation per room, a `@rhema` mention starts a turn, human
messages are stamped with their author's name, and only the `message`
tool puts agent text in the room.
+17
View File
@@ -186,6 +186,10 @@ pub async fn events(
})?;
rows.filter_map(Result::ok).collect()
};
let caught_up = backlog
.last()
.map(|envelope| envelope.seq >= max_seq as u64)
.unwrap_or(max_seq <= since);
let mut last = backlog
.last()
.map(|envelope| envelope.seq)
@@ -195,6 +199,19 @@ pub async fn events(
let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into());
yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data));
}
// The client uses this frame as the boundary between replay and
// the live feed. Until it arrives, a replayed `turn_start` is a
// turn that already ended, not one that is running now.
if caught_up {
let data = json!({ "seq": last, "kind": "ready", "data": {} }).to_string();
yield Ok(SseEvent::default().event("ready").data(data));
} else {
// The backlog hit its row cap. The client resumes from what
// it processed instead of skipping the rest silently.
let data = json!({ "seq": last, "kind": "lag", "data": {} }).to_string();
yield Ok(SseEvent::default().event("lag").data(data));
return;
}
let mut access = tokio::time::interval(Duration::from_secs(2));
loop {
tokio::select! {
+41 -9
View File
@@ -4,9 +4,11 @@ use axum::Json;
use axum::extract::{Path, State};
use axum::http::HeaderMap;
use axum_extra::extract::CookieJar;
use rhema_core::request::ThinkingEffort;
use serde::Deserialize;
use serde_json::{Value, json};
use crate::api::settings::retired_kind;
use crate::auth::{self, AuthUser, clean_display_name};
use crate::error::{AppError, AppResult};
use crate::models::{Member, Room, RoomSummary, User};
@@ -59,10 +61,11 @@ fn load_room(state: &Shared, id: &str) -> AppResult<Room> {
let vision = crate::util::room_model_vision(&conn, id);
conn.query_row(
"SELECT id, name, owner_id, provider_config_id, sandbox_target_id, workspace,
repo_url, model, max_turn_steps, created_at, archived_at
repo_url, model, thinking_effort, max_turn_steps, created_at, archived_at
FROM rooms WHERE id = ?1",
rusqlite::params![id],
|row| {
let effort: String = row.get("thinking_effort")?;
Ok(Room {
id: row.get("id")?,
name: row.get("name")?,
@@ -72,6 +75,7 @@ fn load_room(state: &Shared, id: &str) -> AppResult<Room> {
workspace: row.get("workspace")?,
repo_url: row.get("repo_url")?,
model: row.get("model")?,
thinking_effort: ThinkingEffort::parse(&effort).unwrap_or_default(),
max_turn_steps: row.get("max_turn_steps")?,
model_vision: vision,
created_at: row.get("created_at")?,
@@ -176,13 +180,19 @@ pub async fn create(
"room name must be 1 to 60 characters",
));
}
let (provider_model, provider_owner) = state
let (provider_model, provider_owner, provider_kind) = state
.db
.conn()
.query_row(
"SELECT model, account_id FROM provider_configs WHERE id = ?1",
"SELECT model, account_id, kind FROM provider_configs WHERE id = ?1",
rusqlite::params![body.provider_config_id],
|row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
|row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
))
},
)
.map_err(|_| AppError::bad_request("provider configuration not found"))?;
if provider_owner != user.user.id {
@@ -190,6 +200,9 @@ pub async fn create(
"that provider belongs to another account",
));
}
if let Some(message) = retired_kind(&provider_kind) {
return Err(AppError::bad_request(message));
}
let (workspace_root, target_owner) = state
.db
.conn()
@@ -298,9 +311,11 @@ pub struct UpdateRoom {
pub model: Option<String>,
#[serde(default)]
pub max_turn_steps: Option<u32>,
#[serde(default)]
pub thinking_effort: Option<String>,
}
/// Owner edits: name, provider, model, step budget.
/// Owner edits: name, provider, model, step budget, thinking effort.
pub async fn update(
user: AuthUser,
State(state): State<Shared>,
@@ -321,19 +336,27 @@ pub async fn update(
)?;
}
if let Some(provider_id) = body.provider_config_id.as_deref() {
let owner: Option<String> = state
let provider: Option<(String, String)> = state
.db
.conn()
.query_row(
"SELECT account_id FROM provider_configs WHERE id = ?1",
"SELECT account_id, kind FROM provider_configs WHERE id = ?1",
rusqlite::params![provider_id],
|row| row.get(0),
|row| Ok((row.get(0)?, row.get(1)?)),
)
.ok();
if owner.as_deref() != Some(user.user.id.as_str()) {
let Some((owner, kind)) = provider else {
return Err(AppError::forbidden(
"that provider belongs to another account",
));
};
if owner != user.user.id {
return Err(AppError::forbidden(
"that provider belongs to another account",
));
}
if let Some(message) = retired_kind(&kind) {
return Err(AppError::bad_request(message));
}
state.db.conn().execute(
"UPDATE rooms SET provider_config_id = ?1 WHERE id = ?2",
@@ -354,6 +377,15 @@ pub async fn update(
rusqlite::params![steps.clamp(1, 500) as i64, id],
)?;
}
if let Some(effort) = body.thinking_effort.as_deref() {
let effort = ThinkingEffort::parse(effort).ok_or_else(|| {
AppError::bad_request("thinking effort must be default, low, medium, or high")
})?;
state.db.conn().execute(
"UPDATE rooms SET thinking_effort = ?1 WHERE id = ?2",
rusqlite::params![effort.as_str(), id],
)?;
}
Ok(Json(json!({ "room": load_room(&state, &id)? })))
}
+184 -40
View File
@@ -28,21 +28,82 @@ const KINDS: &[&str] = &[
"mistral",
"mistral-vibe",
"copilot",
"chatgpt",
"opencode",
"llama-cpp",
];
/// Kinds whose credential comes from a browser sign-in instead of a
/// pasted key. The adapter owns the protocol; the server owns the
/// record the browser polls and stores the token it produces.
pub const FLOW_KINDS: &[&str] = &["copilot", "chatgpt", "mistral-vibe"];
/// Whether the operator lifted the ChatGPT block. Off by default:
/// Together serves one plan to every room member, which OpenAI's terms
/// do not allow for a shared room. A single-user local test can set
/// `RHEMA_TOGETHER_I_WANT_CHATGPT_BAN=1`; the name keeps the ban, so
/// the default reads as banned and `1` as lifted.
fn chatgpt_enabled() -> bool {
std::env::var("RHEMA_TOGETHER_I_WANT_CHATGPT_BAN")
.ok()
.as_deref()
.is_some_and(enabled_value)
}
fn enabled_value(value: &str) -> bool {
value == "1"
}
/// The provider kinds the add dialog offers. ChatGPT joins the list
/// only when the operator lifted its block.
fn kinds() -> Vec<&'static str> {
let mut kinds = KINDS.to_vec();
if chatgpt_enabled() {
kinds.push("chatgpt");
}
kinds
}
/// The kinds whose credential comes from a browser sign-in. The
/// adapter owns the protocol; the server owns the record the browser
/// polls and stores the token it produces.
pub const FLOW_KINDS: &[&str] = &["copilot", "mistral-vibe"];
/// The flow kinds the add dialog offers, with ChatGPT only when its
/// block is lifted.
fn flow_kinds() -> Vec<&'static str> {
let mut kinds = FLOW_KINDS.to_vec();
if chatgpt_enabled() {
kinds.push("chatgpt");
}
kinds
}
/// Whether `kind` may be stored. `KINDS` is the base list; ChatGPT is
/// accepted only with the operator's opt-in.
fn kind_allowed(kind: &str) -> bool {
kind_allowed_with(kind, chatgpt_enabled())
}
fn kind_allowed_with(kind: &str, chatgpt: bool) -> bool {
KINDS.contains(&kind) || (kind == "chatgpt" && chatgpt)
}
/// Kinds Together has retired. Existing rows stay so a room that
/// points at one fails with this message instead of losing its
/// configuration.
pub(crate) fn retired_kind(kind: &str) -> Option<&'static str> {
retired_kind_with(kind, chatgpt_enabled())
}
fn retired_kind_with(kind: &str, chatgpt: bool) -> Option<&'static str> {
match kind {
"chatgpt" if !chatgpt => Some(
"ChatGPT plan sign-in is not available in Together. Add an API-key provider and point the room at it, or set RHEMA_TOGETHER_I_WANT_CHATGPT_BAN=1 for a single-user local test.",
),
_ => None,
}
}
/// The caller's provider configurations.
pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
let conn = state.db.conn();
let mut stmt = conn.prepare(
"SELECT id, name, kind, model, base_url FROM provider_configs
"SELECT id, name, kind, model, base_url, api FROM provider_configs
WHERE account_id = ?1 ORDER BY created_at ASC",
)?;
let rows = stmt.query_map(rusqlite::params![user.user.id], |row| {
@@ -52,13 +113,14 @@ pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppR
kind: row.get(2)?,
model: row.get(3)?,
base_url: row.get(4)?,
api: row.get(5)?,
})
})?;
let configs = rows.collect::<Result<Vec<_>, _>>()?;
Ok(Json(json!({
"providers": configs,
"kinds": KINDS,
"flow_kinds": FLOW_KINDS,
"kinds": kinds(),
"flow_kinds": flow_kinds(),
})))
}
@@ -72,6 +134,9 @@ pub struct CreateProvider {
pub model: String,
#[serde(default)]
pub base_url: Option<String>,
/// `chat` or `responses`; only the openai kind reads it.
#[serde(default)]
pub api: Option<String>,
#[serde(default)]
pub api_key: String,
}
@@ -90,7 +155,7 @@ pub async fn create_provider(
if name.is_empty() || name.chars().count() > 60 {
return Err(AppError::bad_request("name must be 1 to 60 characters"));
}
if !KINDS.contains(&body.kind.as_str()) {
if !kind_allowed(&body.kind) {
return Err(AppError::bad_request("unknown provider kind"));
}
let model = body.model.trim().to_owned();
@@ -107,42 +172,74 @@ pub async fn create_provider(
if body.kind != "llama-cpp" && body.api_key.trim().is_empty() {
return Err(AppError::bad_request("an api key is required"));
}
let api = api_choice(&body.kind, body.api)?;
let id = insert_provider(
&state,
&user.user.id,
name,
&body.kind,
&model,
base_url.as_deref(),
body.api_key.trim(),
ProviderDraft {
name,
kind: &body.kind,
model: &model,
base_url: base_url.as_deref(),
api: api.as_deref(),
api_key: body.api_key.trim(),
},
)?;
Ok(Json(json!({ "id": id })))
}
/// Seals and stores one provider row. The callers validate the kind
/// and credential first; this only owns the encryption and the insert.
/// The stored API choice, normalized. Blank means automatic, which the
/// registry reads from the route. Only the openai kind has the choice.
fn api_choice(kind: &str, api: Option<String>) -> AppResult<Option<String>> {
let api = api
.map(|value| value.trim().to_ascii_lowercase())
.filter(|value| !value.is_empty());
let Some(api) = api else {
return Ok(None);
};
if !matches!(api.as_str(), "chat" | "responses") {
return Err(AppError::bad_request("api must be chat or responses"));
}
if kind != "openai" {
return Err(AppError::bad_request(
"the api choice only applies to the openai kind",
));
}
Ok(Some(api))
}
/// One provider row before it is sealed and stored. The callers
/// validate the kind and credential first.
struct ProviderDraft<'a> {
name: &'a str,
kind: &'a str,
model: &'a str,
base_url: Option<&'a str>,
api: Option<&'a str>,
api_key: &'a str,
}
/// Seals and stores one provider row; this only owns the encryption
/// and the insert.
fn insert_provider(
state: &Shared,
account_id: &str,
name: &str,
kind: &str,
model: &str,
base_url: Option<&str>,
api_key: &str,
draft: ProviderDraft<'_>,
) -> AppResult<String> {
let sealed = state.secrets.seal_str(api_key)?;
let sealed = state.secrets.seal_str(draft.api_key)?;
let id = random_id(12);
state.db.conn().execute(
"INSERT INTO provider_configs (id, account_id, name, kind, model, base_url,
"INSERT INTO provider_configs (id, account_id, name, kind, model, base_url, api,
api_key_ciphertext, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
rusqlite::params![
id,
account_id,
name,
kind,
model,
base_url,
draft.name,
draft.kind,
draft.model,
draft.base_url,
draft.api,
sealed,
crate::util::now_ms()
],
@@ -157,7 +254,7 @@ fn login_flow(kind: &str) -> Option<Box<dyn rhema_provider::InteractiveLogin>> {
"copilot" => Some(Box::new(rhema_provider_copilot::CopilotLogin::new())),
// The ChatGPT callback lands on the server's loopback port; a
// server cannot open the user's browser for them.
"chatgpt" => Some(Box::new(
"chatgpt" if chatgpt_enabled() => Some(Box::new(
rhema_provider_chatgpt::ChatGptLogin::new().with_open_browser(false),
)),
"mistral-vibe" => Some(Box::new(rhema_provider_mistral::MistralVibeLogin::new())),
@@ -202,11 +299,14 @@ pub async fn start_provider_login(
insert_provider(
&complete_state,
&account_id,
&provider_name,
&provider_kind,
"",
None,
token.trim(),
ProviderDraft {
name: &provider_name,
kind: &provider_kind,
model: "",
base_url: None,
api: None,
api_key: token.trim(),
},
)
.map_err(|err| err.message)
});
@@ -251,11 +351,11 @@ pub async fn list_provider_models(
State(state): State<Shared>,
Path(id): Path<String>,
) -> AppResult<Json<Value>> {
let (kind, model, base_url, ciphertext) = state
let (kind, model, base_url, api, ciphertext) = state
.db
.conn()
.query_row(
"SELECT kind, model, base_url, api_key_ciphertext FROM provider_configs
"SELECT kind, model, base_url, api, api_key_ciphertext FROM provider_configs
WHERE id = ?1 AND account_id = ?2",
rusqlite::params![id, user.user.id],
|row| {
@@ -263,7 +363,8 @@ pub async fn list_provider_models(
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, Option<String>>(2)?,
row.get::<_, String>(3)?,
row.get::<_, Option<String>>(3)?,
row.get::<_, String>(4)?,
))
},
)
@@ -271,13 +372,21 @@ pub async fn list_provider_models(
rusqlite::Error::QueryReturnedNoRows => AppError::not_found("provider not found"),
other => other.into(),
})?;
if let Some(message) = retired_kind(&kind) {
return Err(AppError::bad_request(message));
}
let key = state.secrets.open_str(&ciphertext)?;
let llama_url = (kind == "llama-cpp")
.then_some(base_url.as_deref())
.flatten();
let built =
rhema_provider_registry::build(&kind, Some(&key), llama_url, base_url.as_deref(), None)
.map_err(|err| AppError::bad_request(format!("provider: {err}")))?;
let built = rhema_provider_registry::build(
&kind,
Some(&key),
llama_url,
base_url.as_deref(),
api.as_deref(),
)
.map_err(|err| AppError::bad_request(format!("provider: {err}")))?;
let models = tokio::time::timeout(Duration::from_secs(30), built.listing.list_models())
.await
.map_err(|_| {
@@ -577,8 +686,43 @@ mod tests {
}
}
#[test]
fn chatgpt_is_retired_until_the_operator_opts_in() {
assert!(retired_kind_with("chatgpt", false).is_some());
assert!(retired_kind_with("chatgpt", true).is_none());
assert!(retired_kind_with("openai", false).is_none());
assert!(!KINDS.contains(&"chatgpt"));
assert!(!FLOW_KINDS.contains(&"chatgpt"));
assert!(!kind_allowed_with("chatgpt", false));
assert!(kind_allowed_with("chatgpt", true));
}
#[test]
fn only_one_lifts_the_block() {
assert!(enabled_value("1"));
assert!(!enabled_value("0"));
assert!(!enabled_value("true"));
assert!(!enabled_value(""));
}
#[test]
fn a_keyed_kind_has_no_login_flow() {
assert!(login_flow("anthropic").is_none());
}
#[test]
fn the_openai_api_choice_is_normalized() {
assert_eq!(api_choice("openai", None).unwrap(), None);
assert_eq!(api_choice("openai", Some(" ".into())).unwrap(), None);
assert_eq!(
api_choice("openai", Some(" Responses ".into())).unwrap(),
Some("responses".into())
);
assert_eq!(
api_choice("openai", Some("chat".into())).unwrap(),
Some("chat".into())
);
assert!(api_choice("openai", Some("completions".into())).is_err());
assert!(api_choice("anthropic", Some("chat".into())).is_err());
}
}
+70
View File
@@ -26,6 +26,15 @@ impl Db {
conn.pragma_update(None, "foreign_keys", "ON")?;
conn.busy_timeout(std::time::Duration::from_secs(5))?;
conn.execute_batch(SCHEMA)?;
// Columns added after the first release have no CREATE TABLE
// path on an existing file. Add them here, once.
ensure_column(
&conn,
"rooms",
"thinking_effort",
"TEXT NOT NULL DEFAULT 'default'",
)?;
ensure_column(&conn, "provider_configs", "api", "TEXT")?;
Ok(Self {
conn: Arc::new(Mutex::new(conn)),
})
@@ -47,6 +56,28 @@ impl Db {
}
}
/// Adds `column` to `table` when the file predates it. The declaration
/// carries its own default, so existing rows read as the old behavior.
fn ensure_column(
conn: &Connection,
table: &str,
column: &str,
declaration: &str,
) -> rusqlite::Result<()> {
let present: i64 = conn.query_row(
"SELECT COUNT(*) FROM pragma_table_info(?1) WHERE name = ?2",
rusqlite::params![table, column],
|row| row.get(0),
)?;
if present == 0 {
conn.execute(
&format!("ALTER TABLE {table} ADD COLUMN {column} {declaration}"),
[],
)?;
}
Ok(())
}
pub(crate) const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
@@ -85,6 +116,7 @@ CREATE TABLE IF NOT EXISTS provider_configs (
kind TEXT NOT NULL,
model TEXT NOT NULL,
base_url TEXT,
api TEXT,
api_key_ciphertext TEXT NOT NULL,
created_at INTEGER NOT NULL
) STRICT;
@@ -113,6 +145,7 @@ CREATE TABLE IF NOT EXISTS rooms (
repo_url TEXT,
model TEXT,
max_turn_steps INTEGER NOT NULL DEFAULT 48,
thinking_effort TEXT NOT NULL DEFAULT 'default',
session_json TEXT,
absorbed_seq INTEGER NOT NULL DEFAULT 0,
seeded INTEGER NOT NULL DEFAULT 0,
@@ -185,3 +218,40 @@ CREATE INDEX IF NOT EXISTS events_room_seq ON events(room_id, seq);
CREATE INDEX IF NOT EXISTS auth_sessions_account ON auth_sessions(account_id);
CREATE INDEX IF NOT EXISTS attachments_room ON attachments(room_id);
"#;
#[cfg(test)]
mod tests {
use super::ensure_column;
#[test]
fn a_late_column_is_added_once_with_its_default() {
let conn = rusqlite::Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE rooms (id TEXT PRIMARY KEY) STRICT;
INSERT INTO rooms (id) VALUES ('old');",
)
.unwrap();
ensure_column(
&conn,
"rooms",
"thinking_effort",
"TEXT NOT NULL DEFAULT 'default'",
)
.unwrap();
ensure_column(
&conn,
"rooms",
"thinking_effort",
"TEXT NOT NULL DEFAULT 'default'",
)
.unwrap();
let effort: String = conn
.query_row(
"SELECT thinking_effort FROM rooms WHERE id = 'old'",
[],
|row| row.get(0),
)
.unwrap();
assert_eq!(effort, "default");
}
}
+3
View File
@@ -54,6 +54,9 @@ async fn main() -> anyhow::Result<()> {
presence: Default::default(),
logins: Default::default(),
});
// A previous process may have stopped between a turn's start and its
// end. Close those turns before the feed can replay them as running.
room::runner::close_open_turns(&state);
let app = api::router(state).layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind(&config.listen).await?;
tracing::info!(listen = %config.listen, "rhema-together");
+6
View File
@@ -1,5 +1,6 @@
//! Rows and wire types shared by the API and the room.
use rhema_core::request::ThinkingEffort;
use serde::{Deserialize, Serialize};
/// One chat line. The sequence number orders it in the room log.
@@ -52,6 +53,8 @@ pub struct Room {
pub workspace: String,
pub repo_url: Option<String>,
pub model: Option<String>,
/// How much reasoning the room's model does; the turn sends it.
pub thinking_effort: ThinkingEffort,
pub max_turn_steps: i64,
/// Whether the room's effective model is known to accept images.
/// `None` is unknown, not no: facts arrive with a provider listing.
@@ -119,6 +122,9 @@ pub struct ProviderConfig {
pub kind: String,
pub model: String,
pub base_url: Option<String>,
/// `chat` or `responses` for the openai kind; `None` follows the
/// route: Responses at OpenAI, chat completions at a base URL.
pub api: Option<String>,
}
/// A sandbox target without its private key.
+33 -10
View File
@@ -9,10 +9,11 @@ use base64::Engine;
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::request::ThinkingEffort;
use rhema_core::{Overlay, Session, ToolResolver};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_host_agent::{HostAgent, HostAgentConfig, Steering};
use rhema_sandbox::WorkspaceSeed;
use rhema_sandbox::{Sandbox, ShellSandbox};
use crate::api::settings::retired_kind;
use crate::error::{AppError, AppResult};
use crate::state::Shared;
@@ -29,6 +30,11 @@ pub struct TurnConfig {
/// The model's stored vision fact; `None` is unknown, not no.
pub supports_vision: Option<bool>,
pub max_turn_steps: u32,
/// How much reasoning the model does; sent on every step.
pub thinking: ThinkingEffort,
/// The cursor the turn starts from. The boundary pass moves it to
/// the last line it appended, so the turn's steering source reads on
/// from there and never over what is already in the history.
pub absorbed_seq: i64,
pub seeded: bool,
pub owner_name: String,
@@ -41,6 +47,8 @@ pub struct TurnConfig {
pub struct ProviderRow {
pub kind: String,
pub base_url: Option<String>,
/// `chat` or `responses`; only the openai kind reads it.
pub api: Option<String>,
pub api_key_ciphertext: String,
}
@@ -61,7 +69,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
let row = conn
.query_row(
"SELECT name, provider_config_id, sandbox_target_id, workspace, repo_url, model,
max_turn_steps, absorbed_seq, seeded
max_turn_steps, absorbed_seq, seeded, thinking_effort
FROM rooms WHERE id = ?1 AND archived_at IS NULL",
rusqlite::params![room_id],
|row| {
@@ -75,6 +83,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
row.get::<_, i64>(6)?,
row.get::<_, i64>(7)?,
row.get::<_, i64>(8)?,
row.get::<_, String>(9)?,
))
},
)
@@ -89,23 +98,28 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
max_steps,
absorbed,
seeded,
effort,
) = row;
let provider_id =
provider_id.ok_or_else(|| AppError::bad_request("room has no provider configured"))?;
let target_id =
target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?;
let (kind, provider_model, base_url, key) = conn.query_row(
"SELECT kind, model, base_url, api_key_ciphertext FROM provider_configs WHERE id = ?1",
let (kind, provider_model, base_url, api, key) = conn.query_row(
"SELECT kind, model, base_url, api, api_key_ciphertext FROM provider_configs WHERE id = ?1",
rusqlite::params![provider_id],
|row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, Option<String>>(2)?,
row.get::<_, String>(3)?,
row.get::<_, Option<String>>(3)?,
row.get::<_, String>(4)?,
))
},
)?;
if let Some(message) = retired_kind(&kind) {
return Err(AppError::bad_request(message));
}
let target = conn.query_row(
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
FROM sandbox_targets WHERE id = ?1",
@@ -138,6 +152,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
return Err(AppError::bad_request("room has no model selected"));
}
let supports_vision = crate::util::model_supports_vision(&conn, &kind, &model);
let thinking = ThinkingEffort::parse(&effort).unwrap_or_default();
Ok(TurnConfig {
room_id: room_id.to_owned(),
room_name: name,
@@ -146,6 +161,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
model,
supports_vision,
max_turn_steps: max_steps.max(1) as u32,
thinking,
absorbed_seq: absorbed,
seeded: seeded != 0,
owner_name,
@@ -153,6 +169,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
provider: ProviderRow {
kind,
base_url,
api,
api_key_ciphertext: key,
},
target,
@@ -302,8 +319,14 @@ fn room_section(config: &TurnConfig) -> String {
)
}
/// Assembles the host agent over `session`.
pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> AppResult<HostAgent> {
/// Assembles the host agent over `session`, with `steering` as the turn
/// loop's step-boundary source (see `runner::RoomSteering`).
pub fn build_agent(
state: &Shared,
config: &TurnConfig,
session: Session,
steering: Arc<dyn Steering>,
) -> AppResult<HostAgent> {
let sandbox = build_sandbox(state, config)?;
let executor = Arc::new(ShellSandbox::new(Arc::new(sandbox)));
let shell = Arc::new(ShellTools::with_executor(
@@ -321,7 +344,7 @@ pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> App
Some(&api_key),
llama_url,
config.provider.base_url.as_deref(),
None,
config.provider.api.as_deref(),
)
.map_err(|err| AppError::bad_request(format!("provider: {err}")))?;
let message_tool: Arc<dyn ToolResolver> =
@@ -347,13 +370,13 @@ pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> App
subagent_providers: None,
session_id: Some(config.room_id.clone()),
max_turn_steps,
thinking: ThinkingEffort::Default,
thinking: config.thinking,
tools: Some(shell),
extra_resolver: Some(extra_tools),
shell_env: Default::default(),
transcript: Some(Default::default()),
summary_worker: None,
steering: None,
steering: Some(steering),
home: None,
environment: Some(rhema_host_agent::remote_notice(
"ssh",
+456 -9
View File
@@ -1,16 +1,22 @@
//! The per-room turn loop. One task per room, one turn at a time.
//!
//! Steering is turn level for now: a new mention drops the running turn
//! future and starts a fresh turn over the committed session, the shape
//! `rhema-code` uses. The step-level hook (`HostAgent::step`) is
//! deferred; see the spec's framework section.
//! A mention is turn level: it drops the running turn future and starts a
//! fresh turn over the committed session, the shape `rhema-code` uses. The
//! step-level hook (`HostAgent::step`) is deferred; see the spec's framework
//! section.
//!
//! Chat is step level, through the framework's steering hook: a message
//! posted without a mention while the agent works lands in the history at
//! the next step boundary instead of waiting for the next turn. See
//! [`RoomSteering`].
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use rhema_core::event::Event;
use rhema_core::{EventSink, Message, Role, Session, Usage};
use rhema_host_agent::Steering;
use serde_json::json;
use tokio::sync::mpsc::UnboundedReceiver;
@@ -34,7 +40,7 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver<Wake>) {
continue;
}
loop {
let config = match agent::load_turn_config(&state, &room) {
let mut config = match agent::load_turn_config(&state, &room) {
Ok(config) => config,
Err(err) => {
notice(&state, &room, "error", err.message);
@@ -81,11 +87,18 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver<Wake>) {
pending_mention = false;
break;
}
let last = pending.last().map(|message| message.seq).unwrap_or(0);
// The batch's cursor, in the row and in the config the turn
// reads, so the turn's steering source starts after what this
// pass just appended instead of reading it back.
let last = pending
.last()
.map(|message| message.seq as i64)
.unwrap_or(config.absorbed_seq);
let _ = state.db.conn().execute(
"UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2",
rusqlite::params![last as i64, room],
rusqlite::params![last, room],
);
config.absorbed_seq = last;
pending_mention = false;
let trigger = pending
.iter()
@@ -118,7 +131,12 @@ async fn run_turn(
rx: &mut UnboundedReceiver<Wake>,
pending_mention: &mut bool,
) {
let mut agent = match agent::build_agent(state, config, session) {
let steering = Arc::new(RoomSteering::new(
state.clone(),
room.to_owned(),
config.absorbed_seq,
));
let mut agent = match agent::build_agent(state, config, session, steering.clone()) {
Ok(agent) => agent,
Err(err) => {
notice(state, room, "error", err.message);
@@ -163,6 +181,8 @@ async fn run_turn(
let session = agent.session().clone();
if let Err(err) = agent::save_session(state, room, &session) {
notice(state, room, "error", err.message);
} else {
steering.commit();
}
let data = match outcome {
Some(Ok(output)) => {
@@ -198,6 +218,112 @@ async fn run_turn(
}
}
/// The steering source of one turn: chat that arrives while the agent
/// works, appended at the next step boundary.
///
/// Without it a message posted mid-turn waits for the next turn, so the
/// model never reads "no, on the other branch" until the work the line
/// is about is finished. The framework drains a [`Steering`] between two
/// steps and appends one User-role message per drain, so the line lands
/// in the history without destroying the step in flight (the step is
/// what the mention path drops, and only a mention does).
///
/// Two messages deliberately stay out of the drain, and the drain stops
/// at the first one it meets so the room log is appended in order:
///
/// - a mention, which the turn loop answers by dropping the turn. Two
/// handlers for one line would append it twice.
/// - a message with images, which a line of text cannot carry.
///
/// Neither is lost: the turn loop's boundary pass reads from the same
/// `absorbed_seq` cursor and appends whatever the drain left behind.
///
/// The source is a query over that cursor and never writes it. The turn
/// commits what it drained once the session holding those lines is
/// saved, so the row can lag behind the history but never lead it, which
/// is the framework's own contract for [`Steering::drain`]: a line that
/// comes back is a line the driver dedupes away, a line retired too early
/// is gone.
struct RoomSteering {
state: Shared,
room: String,
/// The row's cursor when the turn started, the boundary pass's last
/// append. The source never goes behind it: those lines are in the
/// history, and reading them again would append them twice.
seeded: i64,
/// The cursor after this turn's drains. Held here, not in the row:
/// only [`RoomSteering::commit`] writes it, once the session that
/// holds the lines is saved.
absorbed: AtomicI64,
}
impl RoomSteering {
fn new(state: Shared, room: String, seeded: i64) -> Self {
Self {
state,
room,
seeded,
absorbed: AtomicI64::new(seeded),
}
}
/// Writes the drained cursor to the room's row, the boundary pass's
/// order: append, checkpoint, advance. A crash before the checkpoint
/// leaves the row behind, so the next boundary pass re-announces a
/// line rather than losing it, and the framework's per-turn dedupe
/// keeps that repeat out of one turn's history.
fn commit(&self) {
let absorbed = self.absorbed.load(Ordering::SeqCst);
if absorbed == self.seeded {
return;
}
let written = self.state.db.conn().execute(
"UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2",
rusqlite::params![absorbed, self.room],
);
if let Err(err) = written {
notice(
&self.state,
&self.room,
"error",
format!("cannot advance the room's message cursor: {err}"),
);
}
}
}
impl Steering for RoomSteering {
fn drain(&self) -> Vec<String> {
let absorbed = self.absorbed.load(Ordering::SeqCst);
let Ok(messages) = pending_messages(&self.state, &self.room, absorbed) else {
return Vec::new();
};
let (lines, last) = steerable(&messages, absorbed);
if last != absorbed {
self.absorbed.store(last, Ordering::SeqCst);
}
lines
}
}
/// The lines one drain can carry, and the cursor after them: everything
/// in log order up to the first line it cannot carry, a mention (the drop
/// path owns that one) or a message with images (a line of text cannot
/// hold them). The caller leaves the rest to the next boundary pass, so
/// the room log is appended in its own order.
fn steerable(messages: &[RoomMessage], from: i64) -> (Vec<String>, i64) {
let mut lines = Vec::new();
let mut last = from;
for message in messages {
if message.mentions || !message.attachments.is_empty() {
break;
}
lines.push(format!("{}: {}", message.author_name, message.text));
last = message.seq as i64;
}
(lines, last)
}
fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult<Vec<RoomMessage>> {
let conn = state.db.conn();
let mut stmt = conn.prepare(
@@ -219,6 +345,75 @@ fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult<Vec<
Ok(messages)
}
/// Closes turns a previous process left open.
///
/// A turn writes `turn_start` before it runs and `turn_end` only after
/// the work settles. A restart in between leaves the room log one open
/// turn, and replay rebuilds it as running, so the status line says
/// "Rhema is working..." with no task behind it. Startup closes each
/// open turn with an interrupted `turn_end`, the same status a dropped
/// turn gets, so the log tells the truth.
pub fn close_open_turns(state: &Shared) {
let mut pending: HashMap<String, Vec<String>> = HashMap::new();
{
let conn = state.db.conn();
let mut stmt = match conn.prepare(
"SELECT room_id, kind, data FROM events
WHERE kind IN ('turn_start', 'turn_end')
ORDER BY room_id, seq",
) {
Ok(stmt) => stmt,
Err(err) => {
tracing::error!(error = %err, "cannot read turns to close");
return;
}
};
let rows = match stmt.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
))
}) {
Ok(rows) => rows,
Err(err) => {
tracing::error!(error = %err, "cannot read turns to close");
return;
}
};
for row in rows {
let Ok((room, kind, data)) = row else {
continue;
};
let turn_id = serde_json::from_str::<serde_json::Value>(&data)
.ok()
.and_then(|value| value.get("turn_id")?.as_str().map(str::to_owned));
let Some(turn_id) = turn_id else {
continue;
};
let open = pending.entry(room).or_default();
if kind == "turn_start" {
open.push(turn_id);
} else if let Some(index) = open.iter().rposition(|id| id == &turn_id) {
open.remove(index);
}
}
}
for (room, turns) in pending {
for turn_id in turns {
let data = json!({
"turn_id": turn_id,
"status": "interrupted",
"usage": null,
"steps": 0,
});
if let Err(err) = state.hub.durable(&state.db, &room, "turn_end", data) {
tracing::error!(error = %err, room = %room, "cannot close a turn left open");
}
}
}
}
fn notice(state: &Shared, room: &str, level: &str, text: impl Into<String>) {
let _ = state.hub.durable(
&state.db,
@@ -396,3 +591,255 @@ fn truncate(text: &str, max: usize) -> String {
}
format!("{}\n[truncated]", &text[..end])
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::models::Attachment;
fn line(seq: u64, text: &str, mentions: bool) -> RoomMessage {
RoomMessage {
seq,
id: format!("m{seq}"),
author_id: Some("a1".into()),
author_name: "ana".into(),
author_kind: "human".into(),
text: text.into(),
mentions,
created_at: 0,
attachments: Vec::new(),
}
}
fn image(seq: u64, text: &str) -> RoomMessage {
RoomMessage {
attachments: vec![Attachment {
id: format!("att{seq}"),
mime: "image/png".into(),
size: 40,
}],
..line(seq, text, false)
}
}
/// A state over a fresh database holding one account and one room.
fn room(absorbed: i64) -> (Shared, PathBuf) {
let dir = std::env::temp_dir().join(format!("rhema-steering-{}", random_id(10)));
let db = crate::db::Db::open(&dir.join("test.db")).expect("db");
let secrets =
crate::crypto::Secrets::load_or_create(&dir.join("test.key")).expect("secrets");
let state = Arc::new(crate::state::AppState {
config: crate::config::Config::default(),
db,
secrets,
hub: crate::state::Hub::default(),
rooms: Default::default(),
workers: Default::default(),
presence: Default::default(),
logins: Default::default(),
});
let conn = state.db.conn();
conn.execute(
"INSERT INTO accounts (id, handle, display_name, created_at)
VALUES ('a1', 'ana', 'Ana', 1)",
[],
)
.expect("account");
conn.execute(
"INSERT INTO rooms (id, name, owner_id, workspace, absorbed_seq, created_at)
VALUES ('r1', 'Room', 'a1', 'ws', ?1, 1)",
rusqlite::params![absorbed],
)
.expect("room");
drop(conn);
(state, dir)
}
/// Posts one chat line the way the API does: the event's sequence is
/// the message's own, and the cursor reads that field.
fn post(state: &Shared, mut message: RoomMessage) -> i64 {
let seq = state.hub.next_seq(&state.db, "r1");
message.seq = seq;
let data = serde_json::to_value(&message).expect("json");
state
.hub
.insert(&state.db, "r1", seq, "message", &data)
.expect("event");
seq as i64
}
fn cursor(state: &Shared) -> i64 {
state
.db
.scalar("SELECT absorbed_seq FROM rooms WHERE id = 'r1'", [])
.expect("cursor")
}
#[test]
fn a_drain_stops_at_the_first_line_it_cannot_carry() {
let messages = [
line(4, "one", false),
image(5, "two"),
line(6, "three", false),
];
assert_eq!(steerable(&messages, 3), (vec!["ana: one".to_owned()], 4));
let messages = [
line(4, "one", false),
line(5, "@rhema two", true),
line(6, "three", false),
];
assert_eq!(steerable(&messages, 3), (vec!["ana: one".to_owned()], 4));
let (lines, cursor) = steerable(&[line(4, "@rhema two", true)], 3);
assert!(lines.is_empty());
assert_eq!(cursor, 3, "a drain that carries nothing moves nothing");
}
#[test]
fn a_drain_seeded_at_the_boundary_pass_reads_nothing_back() {
let (state, dir) = room(0);
post(&state, line(0, "check the other branch", false));
let boundary = post(&state, line(0, "@rhema go", true));
state
.db
.conn()
.execute(
"UPDATE rooms SET absorbed_seq = ?1 WHERE id = 'r1'",
rusqlite::params![boundary],
)
.expect("boundary cursor");
let steering = RoomSteering::new(state.clone(), "r1".into(), boundary);
assert!(
steering.drain().is_empty(),
"the batch the boundary pass appended is already in the history"
);
steering.commit();
assert_eq!(cursor(&state), boundary);
drop(steering);
drop(state);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_drain_holds_the_row_until_the_turn_commits() {
let (state, dir) = room(0);
let first = post(&state, line(0, "check the other branch", false));
let steering = RoomSteering::new(state.clone(), "r1".into(), 0);
assert_eq!(steering.drain(), ["ana: check the other branch"]);
assert_eq!(cursor(&state), 0, "the row waits for the checkpoint");
assert!(
steering.drain().is_empty(),
"a line the turn took does not come back"
);
steering.commit();
assert_eq!(cursor(&state), first);
drop(steering);
drop(state);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_mention_left_to_the_boundary_pass_is_not_committed() {
let (state, dir) = room(0);
post(&state, line(0, "@rhema go", true));
let steering = RoomSteering::new(state.clone(), "r1".into(), 0);
assert!(steering.drain().is_empty());
steering.commit();
assert_eq!(
cursor(&state),
0,
"a drain that took nothing commits nothing"
);
drop(steering);
drop(state);
let _ = std::fs::remove_dir_all(&dir);
}
fn turn_event(state: &Shared, kind: &str, turn_id: &str) {
state
.hub
.durable(&state.db, "r1", kind, json!({ "turn_id": turn_id }))
.expect("turn event");
}
fn turn_ends(state: &Shared) -> Vec<serde_json::Value> {
let conn = state.db.conn();
let mut stmt = conn
.prepare(
"SELECT data FROM events
WHERE room_id = 'r1' AND kind = 'turn_end' ORDER BY seq",
)
.expect("statement");
stmt.query_map([], |row| row.get::<_, String>(0))
.expect("rows")
.filter_map(Result::ok)
.filter_map(|data| serde_json::from_str(&data).ok())
.collect()
}
#[test]
fn a_turn_left_open_is_closed_as_interrupted() {
let (state, dir) = room(0);
turn_event(&state, "turn_start", "t1");
close_open_turns(&state);
let ends = turn_ends(&state);
assert_eq!(ends.len(), 1);
assert_eq!(ends[0]["turn_id"], "t1");
assert_eq!(ends[0]["status"], "interrupted");
close_open_turns(&state);
assert_eq!(
turn_ends(&state).len(),
1,
"a turn with its end in the log stays closed"
);
drop(state);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_finished_turn_is_left_alone() {
let (state, dir) = room(0);
turn_event(&state, "turn_start", "t1");
turn_event(&state, "turn_end", "t1");
close_open_turns(&state);
assert_eq!(
turn_ends(&state).len(),
1,
"a turn that ended before the restart needs no second end"
);
drop(state);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn only_the_turn_still_open_is_closed() {
let (state, dir) = room(0);
turn_event(&state, "turn_start", "t1");
turn_event(&state, "turn_end", "t1");
turn_event(&state, "turn_start", "t2");
close_open_turns(&state);
let ends = turn_ends(&state);
assert_eq!(ends.len(), 2);
assert_eq!(ends[1]["turn_id"], "t2");
assert_eq!(ends[1]["status"], "interrupted");
drop(state);
let _ = std::fs::remove_dir_all(&dir);
}
}
+2 -1
View File
@@ -67,7 +67,8 @@ onMounted(async () => {
api.get<ProviderListResponse>('/provider-configs'),
api.get<SandboxListResponse>('/sandbox-targets'),
])
providers.value = providerList.providers
const known = new Set(providerList.kinds)
providers.value = providerList.providers.filter((provider) => known.has(provider.kind))
targets.value = targetList.targets
providerId.value = providers.value[0]?.id ?? ''
targetId.value = targets.value[0]?.id ?? ''
+30 -2
View File
@@ -5,6 +5,7 @@ import type {
ProviderConfig,
ProviderListResponse,
Room,
ThinkingEffort,
UpdateRoomBody,
UpdateRoomResponse,
} from '~/types'
@@ -18,12 +19,14 @@ const emit = defineEmits<{ close: []; updated: [room: Room]; archived: [] }>()
const api = useApi()
const providers = ref<ProviderConfig[]>([])
const providerKinds = ref<string[]>([])
const loadingProviders = ref(true)
const providersError = ref('')
const name = ref(props.room.name)
const providerId = ref(props.room.provider_config_id ?? '')
const model = ref(props.room.model ?? '')
const thinkingEffort = ref<ThinkingEffort>(props.room.thinking_effort)
const maxSteps = ref<number | string>(props.room.max_turn_steps)
const pickerOpen = ref(false)
@@ -45,7 +48,13 @@ const canSave = computed(
onMounted(async () => {
try {
const list = await api.get<ProviderListResponse>('/provider-configs')
providers.value = list.providers
// Keep the room's current provider even when the server no longer
// offers its kind, so the select shows what the room is pinned to.
const known = new Set(list.kinds)
providerKinds.value = list.kinds
providers.value = list.providers.filter(
(provider) => known.has(provider.kind) || provider.id === providerId.value,
)
} catch (err) {
providersError.value = apiErrorMessage(err)
} finally {
@@ -69,9 +78,12 @@ async function save() {
error.value = ''
const body: UpdateRoomBody = {
name: name.value.trim(),
thinking_effort: thinkingEffort.value,
max_turn_steps: Math.min(500, Math.max(1, Math.round(Number(maxSteps.value) || 1))),
}
if (providerId.value) body.provider_config_id = providerId.value
if (providerId.value && providerId.value !== props.room.provider_config_id) {
body.provider_config_id = providerId.value
}
body.model = model.value.trim()
try {
const response = await api.patch<UpdateRoomResponse>(`/rooms/${props.room.id}`, body)
@@ -127,6 +139,9 @@ async function archive() {
<span v-else-if="providers.length === 0" class="hint">
No providers yet. <NuxtLink to="/settings">Add one in settings</NuxtLink>.
</span>
<span v-else-if="selectedProvider && !providerKinds.includes(selectedProvider.kind)" class="hint">
This provider is no longer available. Pick another before the room can run a turn.
</span>
</div>
<div class="field">
@@ -149,6 +164,19 @@ async function archive() {
<span class="hint">{{ effectiveModel ? 'The room uses this model for every turn.' : 'Pick a model before saving the room.' }}</span>
</div>
<div class="field">
<label class="field-label" for="room-settings-thinking">Thinking effort</label>
<select id="room-settings-thinking" v-model="thinkingEffort" class="select">
<option value="default">Provider default</option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</select>
<span class="hint">
How much reasoning the model does on each turn. Provider default sends no effort parameter.
</span>
</div>
<div class="field">
<label class="field-label" for="room-settings-steps">Max turn steps</label>
<input id="room-settings-steps" v-model.number="maxSteps" class="input" type="number" min="1" max="500" required>
+5 -2
View File
@@ -379,6 +379,11 @@ function processChunk(chunk: string) {
handleLag()
return
}
if (envelope.kind === 'ready') {
retryIndex = 0
streamState.value = 'live'
return
}
handleEnvelope(envelope)
scheduleStick()
} catch {
@@ -412,8 +417,6 @@ async function connectEvents() {
}
throw new Error('The live feed is unavailable.')
}
streamState.value = 'live'
retryIndex = 0
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
+23 -6
View File
@@ -23,7 +23,7 @@ const api = useApi()
const KIND_LABELS: Record<string, string> = {
anthropic: 'Anthropic',
openai: 'OpenAI',
openai: 'OpenAI / compatible',
openrouter: 'OpenRouter',
google: 'Google Gemini',
deepseek: 'DeepSeek',
@@ -37,8 +37,8 @@ const KIND_LABELS: Record<string, string> = {
}
const providers = ref<ProviderConfig[]>([])
const kinds = ref<string[]>(['anthropic', 'openai', 'openrouter', 'google', 'deepseek', 'zai', 'mistral', 'mistral-vibe', 'copilot', 'chatgpt', 'opencode', 'llama-cpp'])
const flowKinds = ref<string[]>(['copilot', 'chatgpt', 'mistral-vibe'])
const kinds = ref<string[]>(['anthropic', 'openai', 'openrouter', 'google', 'deepseek', 'zai', 'mistral', 'mistral-vibe', 'copilot', 'opencode', 'llama-cpp'])
const flowKinds = ref<string[]>(['copilot', 'mistral-vibe'])
const targets = ref<SandboxTarget[]>([])
const loading = ref(true)
const loadError = ref('')
@@ -46,10 +46,12 @@ const loadError = ref('')
const providerName = ref('')
const providerKind = ref('anthropic')
const providerBaseUrl = ref('')
const providerApi = ref('')
const providerKey = ref('')
const providerBusy = ref(false)
const providerError = ref('')
const llama = computed(() => providerKind.value === 'llama-cpp')
const openai = computed(() => providerKind.value === 'openai')
const flowKind = computed(() => flowKinds.value.includes(providerKind.value))
const kindName = computed(() => KIND_LABELS[providerKind.value] ?? providerKind.value)
@@ -86,8 +88,6 @@ const flowInstruction = computed(() => {
return 'Enter the code on GitHub to authorize Rhema.'
case 'mistral-vibe':
return 'Sign in with your Mistral account to authorize Rhema for your Vibe plan.'
case 'chatgpt':
return sentence(instruction.text)
default:
return sentence(instruction.text)
}
@@ -319,11 +319,13 @@ async function addProvider() {
kind: providerKind.value,
}
if (providerBaseUrl.value.trim()) body.base_url = providerBaseUrl.value.trim()
if (openai.value && providerApi.value) body.api = providerApi.value
if (!llama.value) body.api_key = providerKey.value
try {
await api.post<IdResponse>('/provider-configs', body)
providerName.value = ''
providerBaseUrl.value = ''
providerApi.value = ''
providerKey.value = ''
await loadLists()
providerDialog.value = false
@@ -446,7 +448,7 @@ async function copyKey(target: SandboxTarget) {
<div class="settings-row-main">
<div class="settings-row-title">{{ provider.name }}</div>
<div class="settings-row-detail">
{{ kindLabel(provider.kind) }}<template v-if="provider.base_url">, {{ provider.base_url }}</template>
{{ kindLabel(provider.kind) }}<template v-if="!kinds.includes(provider.kind)"> (no longer available)</template><template v-if="provider.api">, {{ provider.api }} API</template><template v-if="provider.base_url">, {{ provider.base_url }}</template>
</div>
</div>
<div class="settings-row-actions">
@@ -510,6 +512,21 @@ async function copyKey(target: SandboxTarget) {
:required="llama"
>
<span v-if="llama" class="hint">The address of the llama.cpp server.</span>
<span v-else-if="openai" class="hint">
Leave empty for OpenAI, or point at any OpenAI-compatible server.
</span>
</div>
<div v-if="openai" class="field">
<label class="field-label" for="provider-api">API type</label>
<select id="provider-api" v-model="providerApi" class="select">
<option value="">Automatic</option>
<option value="chat">Chat completions</option>
<option value="responses">Responses</option>
</select>
<span class="hint">
Automatic uses Responses at OpenAI and chat completions when a base URL points elsewhere.
</span>
</div>
<div v-if="!flowKind && !llama" class="field">
+6
View File
@@ -62,6 +62,8 @@ export interface RoomListResponse {
rooms: RoomSummary[]
}
export type ThinkingEffort = 'default' | 'low' | 'medium' | 'high'
export interface Room {
id: string
name: string
@@ -71,6 +73,7 @@ export interface Room {
workspace: string
repo_url: string | null
model: string | null
thinking_effort: ThinkingEffort
model_vision: boolean | null
max_turn_steps: number
created_at: number
@@ -123,6 +126,7 @@ export interface UpdateRoomBody {
provider_config_id?: string
model?: string
max_turn_steps?: number
thinking_effort?: ThinkingEffort
}
export interface UpdateRoomResponse {
@@ -155,6 +159,7 @@ export interface ProviderConfig {
kind: string
model: string
base_url: string | null
api: string | null
}
export interface ProviderListResponse {
@@ -211,6 +216,7 @@ export interface CreateProviderBody {
kind: string
model?: string
base_url?: string | null
api?: string | null
api_key?: string
}