feat: sign in to Copilot, ChatGPT, and Mistral Vibe

Three provider kinds have a browser sign-in, but the add-provider
dialog only accepted a pasted key. A per-account login record now runs
the adapter's InteractiveLogin on the server, reports the instruction,
URL, and code to the dialog, and stores the credential before the
browser sees completion. The credential never reaches the client.

The dialog gets a sign-in stage for flow kinds, with a link, a
copyable code, and retry after failure. Closing the dialog cancels the
flow. ChatGPT's callback lands on the server's loopback port, and the
instruction names the port to forward.
This commit is contained in:
vhaudiquet committed 2026-11-28 18:06:21 +01:00
1 parent 369075a842
commit f5087220da
12 files changed
+927 -23

No files matched your search

Generated
+3
View File
@@ -3695,6 +3695,9 @@ dependencies = [
"rhema-core",
"rhema-host-agent",
"rhema-provider",
"rhema-provider-chatgpt",
"rhema-provider-copilot",
"rhema-provider-mistral",
"rhema-provider-registry",
"rhema-sandbox",
"rhema-sandbox-ssh",
+3
View File
@@ -28,6 +28,9 @@ rhema-bash = { path = "../rhema/crates/rhema-bash" }
rhema-core = { path = "../rhema/crates/rhema-core" }
rhema-host-agent = { path = "../rhema/crates/rhema-host-agent" }
rhema-provider = { path = "../rhema/crates/rhema-provider" }
rhema-provider-chatgpt = { path = "../rhema/crates/rhema-provider-chatgpt" }
rhema-provider-copilot = { path = "../rhema/crates/rhema-provider-copilot" }
rhema-provider-mistral = { path = "../rhema/crates/rhema-provider-mistral" }
rhema-provider-registry = { path = "../rhema/crates/rhema-provider-registry" }
rhema-sandbox = { path = "../rhema/crates/rhema-sandbox" }
rhema-sandbox-ssh = { path = "../rhema/crates/rhema-sandbox-ssh" }
+5 -3
View File
@@ -102,9 +102,11 @@ issue certificates.
## First room
1. **Settings → Providers.** Add a provider kind and key. The key is
sealed with the server's master key before it touches SQLite. A new
provider stores no model; the room picks one.
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.
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
+26 -3
View File
@@ -526,7 +526,29 @@ private range in the config when every user is on the same network.
Provider keys and sandbox private keys are encrypted at rest with a key
from the environment or a 0600 file. The server refuses to start without
it. No route, log line, or event carries a key.
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
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
never receives the credential. When the adapter completes, the server
seals the credential and inserts the provider row before the browser
sees the completion, so a missed poll cannot lose a token. Closing the
dialog cancels the flow. Records expire after 15 minutes, and only
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.
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.
## 9. Storage
@@ -669,8 +691,9 @@ This repository, as committed:
provider switch.
- 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. Adding a provider asks for its kind and key;
the room chooses the model.
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.
- 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.
+8
View File
@@ -40,6 +40,14 @@ pub fn router(state: Shared) -> Router {
"/provider-configs",
get(settings::list_providers).post(settings::create_provider),
)
.route(
"/provider-configs/login",
post(settings::start_provider_login),
)
.route(
"/provider-configs/login/{id}",
get(settings::provider_login_status).delete(settings::cancel_provider_login),
)
.route("/provider-configs/{id}", delete(settings::delete_provider))
.route(
"/provider-configs/{id}/models",
+152 -5
View File
@@ -6,7 +6,8 @@ use std::time::Duration;
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use rhema_sandbox::Sandbox;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -27,10 +28,17 @@ const KINDS: &[&str] = &[
"zai",
"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"];
/// The caller's provider configurations.
pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
let conn = state.db.conn();
@@ -48,7 +56,11 @@ pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppR
})
})?;
let configs = rows.collect::<Result<Vec<_>, _>>()?;
Ok(Json(json!({ "providers": configs, "kinds": KINDS })))
Ok(Json(json!({
"providers": configs,
"kinds": KINDS,
"flow_kinds": FLOW_KINDS,
})))
}
#[derive(Deserialize)]
@@ -90,10 +102,36 @@ pub async fn create_provider(
if body.kind == "llama-cpp" && base_url.is_none() {
return Err(AppError::bad_request("llama.cpp needs a server url"));
}
if matches!(body.kind.as_str(), "copilot" | "chatgpt") && base_url.is_some() {
return Err(AppError::bad_request("this provider has no base url"));
}
if body.kind != "llama-cpp" && body.api_key.trim().is_empty() {
return Err(AppError::bad_request("an api key is required"));
}
let sealed = state.secrets.seal_str(body.api_key.trim())?;
let id = insert_provider(
&state,
&user.user.id,
name,
&body.kind,
&model,
base_url.as_deref(),
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.
fn insert_provider(
state: &Shared,
account_id: &str,
name: &str,
kind: &str,
model: &str,
base_url: Option<&str>,
api_key: &str,
) -> AppResult<String> {
let sealed = state.secrets.seal_str(api_key)?;
let id = random_id(12);
state.db.conn().execute(
"INSERT INTO provider_configs (id, account_id, name, kind, model, base_url,
@@ -101,18 +139,110 @@ pub async fn create_provider(
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
rusqlite::params![
id,
user.user.id,
account_id,
name,
body.kind,
kind,
model,
base_url,
sealed,
crate::util::now_ms()
],
)?;
Ok(id)
}
/// The adapter behind a flow kind. `None` means the kind takes a pasted
/// key; [`FLOW_KINDS`] is the list the browser uses to choose a stage.
fn login_flow(kind: &str) -> Option<Box<dyn rhema_provider::InteractiveLogin>> {
match kind {
"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(
rhema_provider_chatgpt::ChatGptLogin::new().with_open_browser(false),
)),
"mistral-vibe" => Some(Box::new(rhema_provider_mistral::MistralVibeLogin::new())),
_ => None,
}
}
#[derive(Deserialize)]
pub struct StartProviderLogin {
pub name: String,
pub kind: String,
}
/// Starts a browser sign-in for a flow kind. The provider row appears
/// only when the flow completes; the browser polls the returned id for
/// instructions and the final provider id.
pub async fn start_provider_login(
user: AuthUser,
State(state): State<Shared>,
Json(body): Json<StartProviderLogin>,
) -> AppResult<Json<Value>> {
if user.user.kind != "user" {
return Err(AppError::forbidden("create an account to add a provider"));
}
let name = body.name.trim();
if name.is_empty() || name.chars().count() > 60 {
return Err(AppError::bad_request("name must be 1 to 60 characters"));
}
let Some(flow) = login_flow(&body.kind) else {
return Err(AppError::bad_request(
"this provider does not have a sign-in flow",
));
};
let complete_state = state.clone();
let account_id = user.user.id.clone();
let provider_name = name.to_owned();
let provider_kind = body.kind.clone();
let complete: crate::login::Complete = Box::new(move |token: &str| {
if token.trim().is_empty() {
return Err("the sign-in returned no credential".to_owned());
}
insert_provider(
&complete_state,
&account_id,
&provider_name,
&provider_kind,
"",
None,
token.trim(),
)
.map_err(|err| err.message)
});
let id = state.logins.start(&user.user.id, flow, complete);
Ok(Json(json!({ "id": id })))
}
/// The flow's last update, for its owner only.
pub async fn provider_login_status(
user: AuthUser,
State(state): State<Shared>,
Path(id): Path<String>,
) -> AppResult<Response> {
let snapshot = state
.logins
.snapshot(&user.user.id, &id)
.ok_or_else(|| AppError::not_found("sign-in not found"))?;
let mut response = Json(snapshot).into_response();
response
.headers_mut()
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
Ok(response)
}
/// Cancels a flow and forgets its record. A completed flow's provider
/// row stays; only the sign-in record goes.
pub async fn cancel_provider_login(
user: AuthUser,
State(state): State<Shared>,
Path(id): Path<String>,
) -> AppResult<Json<Value>> {
state.logins.cancel(&user.user.id, &id);
Ok(Json(json!({ "ok": true })))
}
/// The provider's live model catalog. The registry builds the same
/// adapter a turn uses and asks it for the rows a coding agent can
/// drive; the model-facts decorator fills price, context, and vision
@@ -392,3 +522,20 @@ pub async fn test_target(
Err(err) => Ok(Json(json!({ "ok": false, "detail": err.to_string() }))),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_flow_kind_has_an_adapter() {
for kind in FLOW_KINDS {
assert!(login_flow(kind).is_some(), "{kind} has no login flow");
}
}
#[test]
fn a_keyed_kind_has_no_login_flow() {
assert!(login_flow("anthropic").is_none());
}
}
+397
View File
@@ -0,0 +1,397 @@
//! Provider sign-in flows running on the server.
//!
//! A flow is an `InteractiveLogin` from a provider adapter plus a
//! per-account record of what it last told the browser. The browser
//! polls the record, never the provider, and the completed credential
//! goes straight into the secret box through the caller's closure.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use rhema_provider::{InteractiveLogin, LoginInstruction, LoginSink, LoginUpdate};
use serde::Serialize;
use tokio::task::JoinHandle;
/// How long a flow record survives. The adapters time out after ten
/// minutes; this leaves room to read a result before the sweep.
const FLOW_TTL_MS: i64 = 15 * 60 * 1000;
/// The account's running and finished sign-in flows.
#[derive(Default)]
pub struct Logins {
flows: Mutex<HashMap<String, Arc<LoginFlow>>>,
}
/// What a client sees when it polls one flow.
#[derive(Debug, Clone, Serialize)]
pub struct LoginSnapshot {
pub status: LoginPhase,
#[serde(skip_serializing_if = "Option::is_none")]
pub instruction: Option<LoginStep>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_id: Option<String>,
}
/// The phase a flow is in. The terminal phases never leave once set.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LoginPhase {
#[default]
Starting,
Instruct,
Waiting,
Completed,
Failed,
}
impl LoginPhase {
fn terminal(self) -> bool {
matches!(self, Self::Completed | Self::Failed)
}
}
/// The instruction in a form the browser can render.
#[derive(Debug, Clone, Serialize)]
pub struct LoginStep {
pub text: String,
pub url: Option<String>,
pub code: Option<String>,
}
/// The caller's completion hook: seal and store the credential, and
/// return the new provider id, or the reason it could not.
pub type Complete = Box<dyn FnOnce(&str) -> Result<String, String> + Send>;
/// One flow and the last update it reported.
struct LoginFlow {
account_id: String,
created_at: i64,
inner: Mutex<Inner>,
task: Mutex<Option<JoinHandle<()>>>,
}
#[derive(Default)]
struct Inner {
phase: LoginPhase,
instruction: Option<LoginStep>,
message: Option<String>,
provider_id: Option<String>,
}
impl LoginFlow {
fn new(account_id: String) -> Self {
Self {
account_id,
created_at: crate::util::now_ms(),
inner: Mutex::new(Inner::default()),
task: Mutex::new(None),
}
}
fn snapshot(&self) -> LoginSnapshot {
let inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
LoginSnapshot {
status: inner.phase,
instruction: inner.instruction.clone(),
message: inner.message.clone(),
provider_id: inner.provider_id.clone(),
}
}
fn set_task(&self, handle: JoinHandle<()>) {
*self.task.lock().unwrap_or_else(|err| err.into_inner()) = Some(handle);
}
fn terminal(&self) -> bool {
self.inner
.lock()
.unwrap_or_else(|err| err.into_inner())
.phase
.terminal()
}
fn instruct(&self, step: LoginStep) {
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
if inner.phase.terminal() {
return;
}
inner.phase = LoginPhase::Instruct;
inner.instruction = Some(step);
inner.message = None;
}
fn waiting(&self, text: String) {
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
if inner.phase.terminal() {
return;
}
inner.phase = LoginPhase::Waiting;
inner.message = Some(text);
}
fn completed(&self, provider_id: String) {
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
if inner.phase.terminal() {
return;
}
inner.phase = LoginPhase::Completed;
inner.message = None;
inner.provider_id = Some(provider_id);
}
fn failed(&self, message: String) {
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
if inner.phase.terminal() {
return;
}
inner.phase = LoginPhase::Failed;
inner.message = Some(message);
}
/// A flow that returns without a terminal update leaves a record
/// stuck in `waiting`; this closes it.
fn finish_if_running(&self) {
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
if inner.phase.terminal() {
return;
}
inner.phase = LoginPhase::Failed;
inner.message = Some("the sign-in ended without a result".to_owned());
}
fn cancel(&self, message: &str) {
// Mark the record first: a completion that lands while the task
// unwinds sees a terminal phase and skips the credential.
self.failed(message.to_owned());
if let Some(task) = self
.task
.lock()
.unwrap_or_else(|err| err.into_inner())
.take()
{
task.abort();
}
}
}
/// The sink that writes a flow's updates into its record, and stores
/// the credential when the adapter completes.
struct FlowSink {
flow: Arc<LoginFlow>,
complete: Option<Complete>,
}
impl LoginSink for FlowSink {
fn update(&mut self, update: LoginUpdate) {
match update {
LoginUpdate::Instruct(LoginInstruction { text, url, code }) => {
self.flow.instruct(LoginStep { text, url, code });
}
LoginUpdate::Waiting(text) => self.flow.waiting(text),
LoginUpdate::Failed(message) => self.flow.failed(message),
LoginUpdate::Completed(token) => {
let Some(complete) = self.complete.take() else {
return;
};
// A canceled flow was removed from the map; the adapter
// may still report completion before its task unwinds.
if self.flow.terminal() {
return;
}
match complete(&token) {
Ok(provider_id) => self.flow.completed(provider_id),
Err(message) => self.flow.failed(message),
}
}
}
}
}
impl Logins {
/// Starts `flow` for `account_id`. `complete` runs once, on the
/// flow's credential, and its result is what the browser sees.
pub fn start(
&self,
account_id: &str,
flow: Box<dyn InteractiveLogin>,
complete: Complete,
) -> String {
self.sweep();
let id = crate::util::random_id(12);
let record = Arc::new(LoginFlow::new(account_id.to_owned()));
self.flows
.lock()
.unwrap_or_else(|err| err.into_inner())
.insert(id.clone(), record.clone());
let task_record = record.clone();
let handle = tokio::spawn(async move {
let mut sink = FlowSink {
flow: task_record.clone(),
complete: Some(complete),
};
flow.run(&mut sink).await;
task_record.finish_if_running();
});
record.set_task(handle);
id
}
/// The flow's last update, when it belongs to `account_id`.
pub fn snapshot(&self, account_id: &str, id: &str) -> Option<LoginSnapshot> {
let flow = self
.flows
.lock()
.unwrap_or_else(|err| err.into_inner())
.get(id)
.cloned()?;
(flow.account_id == account_id).then(|| flow.snapshot())
}
/// Ends and forgets a flow. Only its owner can do it.
pub fn cancel(&self, account_id: &str, id: &str) -> bool {
let flow = self
.flows
.lock()
.unwrap_or_else(|err| err.into_inner())
.get(id)
.cloned();
let Some(flow) = flow else {
return false;
};
if flow.account_id != account_id {
return false;
}
self.flows
.lock()
.unwrap_or_else(|err| err.into_inner())
.remove(id);
flow.cancel("the sign-in was canceled");
true
}
/// Drops records that outlived the adapters' own timeouts.
fn sweep(&self) {
let now = crate::util::now_ms();
let stale: Vec<(String, Arc<LoginFlow>)> = self
.flows
.lock()
.unwrap_or_else(|err| err.into_inner())
.iter()
.filter(|(_, flow)| now - flow.created_at > FLOW_TTL_MS)
.map(|(id, flow)| (id.clone(), flow.clone()))
.collect();
if stale.is_empty() {
return;
}
let mut flows = self.flows.lock().unwrap_or_else(|err| err.into_inner());
for (id, flow) in stale {
flows.remove(&id);
flow.cancel("the sign-in expired");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn step() -> LoginStep {
LoginStep {
text: "open the page".to_owned(),
url: Some("https://example.com/device".to_owned()),
code: Some("ABCD-1234".to_owned()),
}
}
#[test]
fn waiting_keeps_the_instruction_visible() {
let flow = LoginFlow::new("acct".to_owned());
flow.instruct(step());
flow.waiting("waiting for the browser".to_owned());
let snapshot = flow.snapshot();
assert_eq!(snapshot.status, LoginPhase::Waiting);
assert_eq!(
snapshot.instruction.expect("instruction").code.as_deref(),
Some("ABCD-1234")
);
assert_eq!(snapshot.message.as_deref(), Some("waiting for the browser"));
}
#[test]
fn a_terminal_phase_never_moves_again() {
let flow = LoginFlow::new("acct".to_owned());
flow.completed("provider".to_owned());
flow.failed("too late".to_owned());
flow.waiting("too late".to_owned());
let snapshot = flow.snapshot();
assert_eq!(snapshot.status, LoginPhase::Completed);
assert_eq!(snapshot.provider_id.as_deref(), Some("provider"));
assert_eq!(snapshot.message, None);
}
#[test]
fn a_flow_that_returns_early_is_closed() {
let flow = LoginFlow::new("acct".to_owned());
flow.instruct(step());
flow.finish_if_running();
let snapshot = flow.snapshot();
assert_eq!(snapshot.status, LoginPhase::Failed);
assert_eq!(
snapshot.message.as_deref(),
Some("the sign-in ended without a result")
);
}
#[tokio::test]
async fn another_account_cannot_read_or_cancel_the_flow() {
let logins = Logins::default();
let flow: Box<dyn InteractiveLogin> = Box::new(Immediate);
let id = logins.start("owner", flow, Box::new(|_| Ok("provider".to_owned())));
assert!(logins.snapshot("other", &id).is_none());
assert!(!logins.cancel("other", &id));
assert!(logins.snapshot("owner", &id).is_some());
}
struct Immediate;
#[async_trait::async_trait]
impl InteractiveLogin for Immediate {
async fn run(&self, _sink: &mut dyn LoginSink) {}
}
struct Completes;
#[async_trait::async_trait]
impl InteractiveLogin for Completes {
async fn run(&self, sink: &mut dyn LoginSink) {
sink.update(LoginUpdate::Completed("the-token".to_owned()));
}
}
#[tokio::test]
async fn the_completion_hook_stores_the_credential_and_names_the_provider() {
let logins = Logins::default();
let id = logins.start(
"owner",
Box::new(Completes),
Box::new(|token| {
assert_eq!(token, "the-token");
Ok("provider".to_owned())
}),
);
for _ in 0..10 {
if logins
.snapshot("owner", &id)
.is_some_and(|snapshot| snapshot.status == LoginPhase::Completed)
{
break;
}
tokio::task::yield_now().await;
}
let snapshot = logins.snapshot("owner", &id).expect("snapshot");
assert_eq!(snapshot.status, LoginPhase::Completed);
assert_eq!(snapshot.provider_id.as_deref(), Some("provider"));
}
}
+2
View File
@@ -4,6 +4,7 @@ mod config;
mod crypto;
mod db;
mod error;
mod login;
mod models;
mod presence;
mod preview;
@@ -45,6 +46,7 @@ async fn main() -> anyhow::Result<()> {
rooms: Default::default(),
previews: Default::default(),
presence: Default::default(),
logins: Default::default(),
});
let app = api::router(state).layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind(&config.listen).await?;
+1
View File
@@ -127,6 +127,7 @@ pub struct AppState {
pub rooms: RoomRunner,
pub previews: PreviewTunnels,
pub presence: crate::presence::Presence,
pub logins: crate::login::Logins,
}
/// The state behind an `Arc`.
+38
View File
@@ -464,6 +464,44 @@ button {
line-height: var(--lh-body);
}
.signin {
display: flex;
flex-direction: column;
gap: var(--sp-4);
}
.signin .dialog-actions {
margin-top: 0;
}
.signin-actions {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
}
.signin-link:hover {
text-decoration: none;
}
.signin-code {
display: flex;
flex-direction: column;
gap: var(--sp-1);
}
.signin-code-value {
align-self: flex-start;
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--r-control);
background: var(--surface-2);
font-family: var(--font-mono);
font-size: var(--fs-code);
letter-spacing: 0.08em;
white-space: pre;
}
.form-note {
color: var(--muted);
font-size: var(--fs-meta);
+272 -12
View File
@@ -1,15 +1,17 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { Check, Copy, Plus, Trash2 } from 'lucide-vue-next'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { Check, Copy, ExternalLink, Plus, Trash2 } from 'lucide-vue-next'
import type {
CreateSandboxBody,
CreateSandboxResponse,
CreateProviderBody,
IdResponse,
LoginFlowStatus,
ProviderConfig,
ProviderListResponse,
SandboxListResponse,
SandboxTarget,
StartLoginResponse,
TestSandboxResponse,
} from '~/types'
import { apiErrorMessage } from '~/utils/errors'
@@ -19,8 +21,24 @@ useHead({ title: 'Settings · Rhema Together' })
const api = useApi()
const KIND_LABELS: Record<string, string> = {
anthropic: 'Anthropic',
openai: 'OpenAI',
openrouter: 'OpenRouter',
google: 'Google Gemini',
deepseek: 'DeepSeek',
zai: 'Z.ai',
mistral: 'Mistral API',
'mistral-vibe': 'Mistral Vibe',
copilot: 'GitHub Copilot',
chatgpt: 'ChatGPT',
opencode: 'OpenCode',
'llama-cpp': 'llama.cpp',
}
const providers = ref<ProviderConfig[]>([])
const kinds = ref<string[]>(['anthropic', 'openai', 'openrouter', 'google', 'deepseek', 'zai', 'mistral', 'mistral-vibe', 'opencode', 'llama-cpp'])
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 targets = ref<SandboxTarget[]>([])
const loading = ref(true)
const loadError = ref('')
@@ -32,6 +50,48 @@ const providerKey = ref('')
const providerBusy = ref(false)
const providerError = ref('')
const llama = computed(() => providerKind.value === 'llama-cpp')
const flowKind = computed(() => flowKinds.value.includes(providerKind.value))
const kindName = computed(() => KIND_LABELS[providerKind.value] ?? providerKind.value)
const loginId = ref<string | null>(null)
const loginStatus = ref<LoginFlowStatus | null>(null)
const loginPollFailures = ref(0)
const copiedLoginCode = ref(false)
let loginTimer: ReturnType<typeof setTimeout> | null = null
let loginCopyTimer: ReturnType<typeof setTimeout> | null = null
let loginGeneration = 0
const providerDialogTitle = computed(() =>
loginId.value ? `Sign in to ${providerName.value.trim() || kindName.value}` : 'Add provider',
)
const providerDialogDescription = computed(() => {
if (loginId.value) {
if (loginStatus.value?.status === 'failed') return 'The sign-in did not finish. Try again or go back.'
return 'Finish the sign-in in your browser. This dialog updates on its own.'
}
if (flowKind.value) return 'Sign in with the provider. The credential stays sealed on the server.'
if (llama.value) return 'The server address is stored for this account.'
return 'The key stays sealed on the server and is never shown again.'
})
const loginUrl = computed(() => {
const url = loginStatus.value?.instruction?.url
return url && /^https?:\/\//i.test(url) ? url : null
})
const loginCode = computed(() => loginStatus.value?.instruction?.code ?? null)
const flowInstruction = computed(() => {
const instruction = loginStatus.value?.instruction
if (!instruction) return ''
switch (providerKind.value) {
case 'copilot':
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)
}
})
const sandboxName = ref('')
const sandboxHost = ref('')
@@ -63,6 +123,7 @@ async function loadLists() {
])
providers.value = providerList.providers
if (providerList.kinds.length > 0) kinds.value = providerList.kinds
if (providerList.flow_kinds.length > 0) flowKinds.value = providerList.flow_kinds
targets.value = targetList.targets
} catch (err) {
loadError.value = apiErrorMessage(err)
@@ -73,17 +134,171 @@ async function loadLists() {
onMounted(loadLists)
onBeforeUnmount(() => {
loginGeneration += 1
stopLoginPolling()
if (loginCopyTimer !== null) clearTimeout(loginCopyTimer)
const id = loginId.value
if (id) void api.del(`/provider-configs/login/${id}`).catch(() => {})
})
function openProviderDialog() {
providerError.value = ''
loginStatus.value = null
loginId.value = null
loginPollFailures.value = 0
copiedLoginCode.value = false
providerDialog.value = true
}
function closeProviderDialog() {
cancelLogin()
providerDialog.value = false
providerKey.value = ''
providerError.value = ''
}
function kindLabel(kind: string) {
return KIND_LABELS[kind] ?? kind
}
function sentence(text: string) {
return text ? text.charAt(0).toUpperCase() + text.slice(1) : text
}
function stopLoginPolling() {
if (loginTimer !== null) {
clearTimeout(loginTimer)
loginTimer = null
}
}
function cancelLogin() {
loginGeneration += 1
providerBusy.value = false
stopLoginPolling()
const id = loginId.value
loginId.value = null
loginStatus.value = null
loginPollFailures.value = 0
copiedLoginCode.value = false
if (loginCopyTimer !== null) {
clearTimeout(loginCopyTimer)
loginCopyTimer = null
}
if (id) void api.del(`/provider-configs/login/${id}`).catch(() => {})
}
function scheduleLoginPoll() {
stopLoginPolling()
loginTimer = window.setTimeout(() => {
void pollLogin()
}, 2000)
}
async function pollLogin() {
const id = loginId.value
if (!id) return
const generation = loginGeneration
try {
const status = await api.get<LoginFlowStatus>(`/provider-configs/login/${id}`)
if (loginId.value !== id || generation !== loginGeneration) return
loginPollFailures.value = 0
loginStatus.value = status
if (status.status === 'completed') {
stopLoginPolling()
loginId.value = null
loginStatus.value = null
providerName.value = ''
providerBaseUrl.value = ''
providerKey.value = ''
providerError.value = ''
if (id) void api.del(`/provider-configs/login/${id}`).catch(() => {})
providerDialog.value = false
await loadLists()
} else if (status.status === 'failed') {
stopLoginPolling()
} else {
scheduleLoginPoll()
}
} catch (err) {
if (loginId.value !== id || generation !== loginGeneration) return
loginPollFailures.value += 1
if (loginPollFailures.value >= 3) {
stopLoginPolling()
loginStatus.value = { status: 'failed', message: apiErrorMessage(err) }
} else {
scheduleLoginPoll()
}
}
}
async function startProviderLogin() {
if (providerBusy.value) return
const generation = ++loginGeneration
providerBusy.value = true
providerError.value = ''
stopLoginPolling()
const previous = loginId.value
loginId.value = null
loginStatus.value = null
loginPollFailures.value = 0
copiedLoginCode.value = false
if (previous) {
try {
await api.del(`/provider-configs/login/${previous}`)
} catch {
// The sweep drops an old record anyway; the new flow still starts.
}
}
if (generation !== loginGeneration) return
try {
const started = await api.post<StartLoginResponse>('/provider-configs/login', {
name: providerName.value.trim(),
kind: providerKind.value,
})
if (generation !== loginGeneration) {
void api.del(`/provider-configs/login/${started.id}`).catch(() => {})
return
}
loginId.value = started.id
loginStatus.value = { status: 'starting' }
scheduleLoginPoll()
} catch (err) {
if (generation === loginGeneration) providerError.value = apiErrorMessage(err)
} finally {
if (generation === loginGeneration) providerBusy.value = false
}
}
function backToProviderForm() {
cancelLogin()
providerError.value = ''
}
async function copyLoginCode() {
if (!loginCode.value) return
try {
await navigator.clipboard.writeText(loginCode.value)
providerError.value = ''
copiedLoginCode.value = true
if (loginCopyTimer !== null) clearTimeout(loginCopyTimer)
loginCopyTimer = window.setTimeout(() => {
copiedLoginCode.value = false
}, 1800)
} catch {
providerError.value = 'The clipboard is not available. Select the code and copy it by hand.'
}
}
async function submitProvider() {
if (flowKind.value) {
await startProviderLogin()
return
}
await addProvider()
}
function openSandboxDialog() {
sandboxError.value = ''
sandboxDialog.value = true
@@ -222,7 +437,7 @@ async function copyKey(target: SandboxTarget) {
Add provider
</button>
</div>
<p class="hint">A provider holds a backend and key. Each room picks a model from its provider.</p>
<p class="hint">A provider holds a backend and how to reach it. Each room picks a model from its provider.</p>
<div v-if="!loading && providers.length === 0" class="empty">No providers yet. Use Add provider to connect one.</div>
@@ -231,7 +446,7 @@ async function copyKey(target: SandboxTarget) {
<div class="settings-row-main">
<div class="settings-row-title">{{ provider.name }}</div>
<div class="settings-row-detail">
{{ provider.kind }}<template v-if="provider.base_url">, {{ provider.base_url }}</template>
{{ kindLabel(provider.kind) }}<template v-if="provider.base_url">, {{ provider.base_url }}</template>
</div>
</div>
<div class="settings-row-actions">
@@ -262,11 +477,11 @@ async function copyKey(target: SandboxTarget) {
<BaseDialog
v-if="providerDialog"
title="Add provider"
description="The key stays sealed on the server and is never shown again."
:title="providerDialogTitle"
:description="providerDialogDescription"
@close="closeProviderDialog"
>
<form class="form" @submit.prevent="addProvider">
<form v-if="!loginId" class="form" @submit.prevent="submitProvider">
<div class="form-grid">
<div class="field">
<label class="field-label" for="provider-name">Name</label>
@@ -275,12 +490,12 @@ async function copyKey(target: SandboxTarget) {
<div class="field">
<label class="field-label" for="provider-kind">Kind</label>
<select id="provider-kind" v-model="providerKind" class="select">
<option v-for="kind in kinds" :key="kind" :value="kind">{{ kind }}</option>
<option v-for="kind in kinds" :key="kind" :value="kind">{{ kindLabel(kind) }}</option>
</select>
</div>
</div>
<div class="field">
<div v-if="!flowKind" class="field">
<label class="field-label" for="provider-base">
{{ llama ? 'Server URL' : 'Base URL' }}
<span v-if="!llama" class="field-optional">optional</span>
@@ -297,7 +512,7 @@ async function copyKey(target: SandboxTarget) {
<span v-if="llama" class="hint">The address of the llama.cpp server.</span>
</div>
<div v-if="!llama" class="field">
<div v-if="!flowKind && !llama" class="field">
<label class="field-label" for="provider-key">API key</label>
<input
id="provider-key"
@@ -316,10 +531,55 @@ async function copyKey(target: SandboxTarget) {
<div class="dialog-actions">
<button type="button" class="btn" :disabled="providerBusy" @click="closeProviderDialog">Cancel</button>
<button type="submit" class="btn btn-primary" :disabled="providerBusy">
{{ providerBusy ? 'Adding' : 'Add provider' }}
{{ providerBusy ? (flowKind ? 'Starting' : 'Adding') : flowKind ? 'Sign in' : 'Add provider' }}
</button>
</div>
</form>
<div v-else class="signin" aria-live="polite">
<p v-if="!loginStatus || loginStatus.status === 'starting'" class="form-note">Starting sign-in.</p>
<template v-else>
<template v-if="loginStatus.status === 'instruct' || loginStatus.status === 'waiting'">
<p v-if="flowInstruction" class="form-note">{{ flowInstruction }}</p>
<div v-if="loginUrl || loginCode" class="signin-actions">
<a
v-if="loginUrl"
class="btn btn-primary signin-link"
:href="loginUrl"
target="_blank"
rel="noopener noreferrer"
>
Open sign-in page
<ExternalLink :size="14" aria-hidden="true" />
</a>
<button v-if="loginCode" type="button" class="btn" @click="copyLoginCode">
<component :is="copiedLoginCode ? Check : Copy" :size="14" aria-hidden="true" />
{{ copiedLoginCode ? 'Copied' : 'Copy code' }}
</button>
</div>
<div v-if="loginCode" class="signin-code">
<span class="field-label">Code</span>
<code class="signin-code-value">{{ loginCode }}</code>
</div>
<p v-if="loginStatus.message" class="form-note">{{ sentence(loginStatus.message) }}</p>
<p v-else class="form-note">Waiting for you to finish in the browser.</p>
</template>
<p v-else-if="loginStatus.status === 'failed'" class="form-error" role="alert">
{{ sentence(loginStatus.message ?? 'The sign-in failed.') }}
</p>
<p v-if="providerError" class="form-error" role="alert">{{ providerError }}</p>
</template>
<div class="dialog-actions">
<template v-if="loginStatus?.status === 'failed'">
<button type="button" class="btn" @click="backToProviderForm">Back</button>
<button type="button" class="btn btn-primary" :disabled="providerBusy" @click="startProviderLogin">
Try again
</button>
</template>
<button v-else type="button" class="btn" @click="closeProviderDialog">Cancel</button>
</div>
</div>
</BaseDialog>
</section>
+20
View File
@@ -144,6 +144,26 @@ export interface ProviderConfig {
export interface ProviderListResponse {
providers: ProviderConfig[]
kinds: string[]
flow_kinds: string[]
}
export interface LoginInstruction {
text: string
url: string | null
code: string | null
}
export type LoginFlowPhase = 'starting' | 'instruct' | 'waiting' | 'completed' | 'failed'
export interface LoginFlowStatus {
status: LoginFlowPhase
instruction?: LoginInstruction
message?: string
provider_id?: string
}
export interface StartLoginResponse {
id: string
}
export interface ModelPricing {