feat: build a resizable native developer workspace with console and network inspection
Verify Tessera GUI / verify (push) Failing after 7m12s

This commit is contained in:
2026-10-20 16:42:12 +08:00
parent 5f202e8347
commit d641f62116
12 changed files with 2042 additions and 301 deletions
+161 -12
View File
@@ -1,6 +1,8 @@
use std::{
io::Read,
ops::{Deref, DerefMut},
panic::{AssertUnwindSafe, catch_unwind},
sync::Mutex,
sync::{
Arc, RwLock,
mpsc::{SyncSender, TrySendError, sync_channel},
@@ -12,14 +14,20 @@ use anyhow::{Context as _, Result};
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
use winit::event_loop::EventLoopProxy;
use crate::{app::AppEvent, document::NamespaceState, endor_host};
use crate::{
activity::{Activity, ActivityLog},
app::AppEvent,
document::NamespaceState,
endor_host,
};
pub const API_ADDRESS: &str = "127.0.0.1:4737";
const MAX_CODE_SIZE: u64 = endor_host::MAX_SOURCE_BYTES as u64;
type Notify = Arc<dyn Fn() + Send + Sync>;
struct BuildRequest {
request: Request,
request: ObservedRequest,
evaluate: bool,
source: String,
namespace: String,
submission: u64,
@@ -28,21 +36,45 @@ struct BuildRequest {
pub fn start(
namespace: Arc<RwLock<NamespaceState>>,
proxy: EventLoopProxy<AppEvent>,
) -> Result<()> {
) -> Result<Activity> {
let server = Server::http(API_ADDRESS)
.map_err(|error| anyhow::anyhow!(error))
.with_context(|| format!("bind Tessera API to {API_ADDRESS}"))?;
let notify: Notify = Arc::new(move || {
let _ = proxy.send_event(AppEvent::DocumentUpdated);
});
start_server(Arc::new(server), namespace, notify)?;
Ok(())
let activity = Arc::new(Mutex::new(ActivityLog::default()));
start_server_observed(
Arc::new(server),
namespace,
notify.clone(),
activity.clone(),
notify,
)?;
Ok(activity)
}
#[cfg(test)]
fn start_server(
server: Arc<Server>,
namespace: Arc<RwLock<NamespaceState>>,
notify: Notify,
) -> Result<thread::JoinHandle<()>> {
start_server_observed(
server,
namespace,
notify,
Arc::new(Mutex::new(ActivityLog::default())),
Arc::new(|| {}),
)
}
fn start_server_observed(
server: Arc<Server>,
namespace: Arc<RwLock<NamespaceState>>,
notify: Notify,
activity: Activity,
observer_notify: Notify,
) -> Result<thread::JoinHandle<()>> {
let (sender, receiver) = sync_channel::<BuildRequest>(8);
let worker_namespace = namespace.clone();
@@ -60,18 +92,104 @@ fn start_server(
.name("tessera-agent-api".to_owned())
.spawn(move || {
for request in server.incoming_requests() {
handle(request, &namespace, &notify, &sender);
handle(
request,
&namespace,
&notify,
&sender,
&activity,
&observer_notify,
);
}
})
.context("start Tessera agent API thread")
}
// Capture only allowlisted headers: credentials and cookies never enter the inspector.
struct ObservedRequest {
inner: Request,
activity: Activity,
id: u64,
notify: Notify,
}
impl ObservedRequest {
fn new(inner: Request, activity: Activity, notify: Notify) -> Self {
let headers = inner
.headers()
.iter()
.filter(|h| h.field.equiv("Content-Type") || h.field.equiv("Content-Length"))
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n");
let origin = if inner
.headers()
.iter()
.any(|h| h.field.equiv("X-Tessera-Origin") && h.value.as_str() == "console")
{
"Console"
} else {
"HTTP"
}
.to_owned();
let id = activity.lock().unwrap().begin(
inner.method().to_string(),
inner.url().to_owned(),
origin,
headers,
);
notify();
Self {
inner,
activity,
id,
notify,
}
}
fn record_body(&self, body: &str) {
self.activity.lock().unwrap().body(self.id, body);
(self.notify)();
}
fn respond(self, response: Response<std::io::Cursor<Vec<u8>>>) -> std::io::Result<()> {
let status = response.status_code();
let headers = response.headers().to_vec();
let length = response.data_length();
let reader = response.into_reader();
self.activity.lock().unwrap().finish(
self.id,
status.0,
&String::from_utf8_lossy(reader.get_ref()),
headers
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n"),
);
(self.notify)();
self.inner
.respond(Response::new(status, headers, reader, length, None))
}
}
impl Deref for ObservedRequest {
type Target = Request;
fn deref(&self) -> &Request {
&self.inner
}
}
impl DerefMut for ObservedRequest {
fn deref_mut(&mut self) -> &mut Request {
&mut self.inner
}
}
fn handle(
request: Request,
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
sender: &SyncSender<BuildRequest>,
activity: &Activity,
observer_notify: &Notify,
) {
let request = ObservedRequest::new(request, activity.clone(), observer_notify.clone());
let method = request.method().clone();
let path = request
.url()
@@ -80,10 +198,16 @@ fn handle(
.unwrap_or(request.url())
.to_owned();
if method == Method::Put
let evaluation = path
.strip_suffix("/evaluate")
.and_then(|prefix| prefix.strip_prefix("/v1/namespaces/"));
if (method == Method::Put || method == Method::Post)
&& let Some(addressed) = namespace_from_path(&path)
.filter(|_| method == Method::Put)
.or(evaluation
.filter(|name| method == Method::Post && !name.is_empty() && !name.contains('/')))
{
submit(request, addressed, namespace, sender);
submit(request, addressed, namespace, sender, evaluation.is_some());
return;
}
let response = if method == Method::Get && path == "/agent" {
@@ -162,10 +286,11 @@ fn code_request(
}
fn submit(
mut request: Request,
mut request: ObservedRequest,
addressed: &str,
namespace: &Arc<RwLock<NamespaceState>>,
sender: &SyncSender<BuildRequest>,
evaluate: bool,
) {
let source = match read_code(&mut request) {
Ok(source) => source,
@@ -174,6 +299,7 @@ fn submit(
return;
}
};
request.record_body(&source);
let Ok(mut current) = namespace.write() else {
let _ = request.respond(error_response(
StatusCode(500),
@@ -194,6 +320,7 @@ fn submit(
};
let job = BuildRequest {
request,
evaluate,
source,
namespace: addressed.into(),
submission,
@@ -201,7 +328,11 @@ fn submit(
match sender.try_send(job) {
// A rejected queue entry never invalidates accepted work. The worker
// uses this same lock when committing, so publication is atomic.
Ok(()) => current.submission = submission,
Ok(()) => {
if !evaluate {
current.submission = submission;
}
}
Err(TrySendError::Full(job)) => {
let _ = job
.request
@@ -221,6 +352,16 @@ fn build(
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
) -> Response<std::io::Cursor<Vec<u8>>> {
if job.evaluate {
return match catch_unwind(AssertUnwindSafe(|| endor_host::evaluate(&job.source))) {
Ok(Ok(value)) => json(
StatusCode(200),
serde_json::json!({"ok":true,"value":value,"execution":"isolated-expression","persistent":false}),
),
Ok(Err(error)) => compile_error(error),
Err(_) => error_response(StatusCode(500), "expression execution failed internally"),
};
}
match namespace.read() {
Ok(current) if current.submission != job.submission => return superseded(job.submission),
Err(_) => return error_response(StatusCode(500), "namespace lock is poisoned"),
@@ -315,6 +456,14 @@ Send PUT bodies as `text/plain; charset=utf-8`.
```endor
{example}```
## Isolated expression evaluation
`POST http://{address}/v1/namespaces/{name}/evaluate` accepts one Endor expression
as text/plain and returns its value. It uses a fresh VM without ui or prior bindings,
does not publish a page or change the revision, and shares the bounded worker queue.
Persistent REPL sessions are not available. The Console is an activity transcript,
not a persistent VM; history is never replayed. PUT remains a complete source replacement.
## UI host object
Positional arguments only:
@@ -400,12 +549,12 @@ fn text(status: StatusCode, value: &str, content_type: &str) -> Response<std::io
add_header(
&mut response,
"Access-Control-Allow-Methods",
"GET, PUT, DELETE, OPTIONS",
"GET, PUT, POST, DELETE, OPTIONS",
);
add_header(
&mut response,
"Access-Control-Allow-Headers",
"Content-Type",
"Content-Type, X-Tessera-Origin",
);
response
}