Land OKF aliases, view SSE, workbook nav, and explicit parent ctor.

Complete the core agent roadmap: soft KB hits via Task aliases, EventBus-backed view streaming, D4 writeback/workbook navigation, and I3 explicit-super without implicit auto-super.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-10 11:58:26 +08:00
1 parent d1ddb74235
commit 2a9fceb51c
26 files changed
+918 -54

No files matched your search

+258 -1
View File
@@ -474,6 +474,14 @@ section.block > h2 {
border-left: 3px solid #2563eb;
background: #f8fafc;
}
.output-card .wb-badges {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.wb-badge.wb-ok { background: #dcfce7; color: #166534; }
.wb-badge.wb-error { background: #fee2e2; color: #991b1b; }
.wb-badge.wb-trace { background: #e0e7ff; color: #3730a3; }
.output-card .output-body {
margin: 0.35rem 0 0;
padding: 0.5rem 0.65rem;
@@ -481,6 +489,89 @@ section.block > h2 {
white-space: pre-wrap;
color: #0f172a;
}
.wb-outline {
margin-top: 0.75rem;
padding-top: 0.75rem;
border-top: 1px solid var(--line);
}
.wb-outline-title {
font: 0.72rem/1.2 var(--sans);
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--muted);
margin-bottom: 0.35rem;
}
.plan-card {
margin: 0 0 0.85rem;
padding: 0.75rem 0.9rem;
border: 1px solid var(--line);
border-radius: var(--radius);
background: #f8fafc;
font: 0.88rem/1.45 var(--sans);
}
.plan-card .plan-meta {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 1rem;
margin: 0.35rem 0 0.55rem;
color: var(--muted);
font: 0.8rem/1.35 var(--mono);
}
.plan-card a { color: #1d4ed8; }
.stream-panel {
margin: 0 0 0.85rem;
border: 1px solid var(--line);
border-radius: var(--radius);
background: #0f172a;
color: #e2e8f0;
overflow: hidden;
}
.stream-head {
display: flex;
align-items: center;
gap: 0.65rem;
padding: 0.55rem 0.75rem;
background: #1e293b;
border-bottom: 1px solid #334155;
font: 0.8rem/1 var(--sans);
}
.stream-head button {
font: 0.78rem/1 var(--sans);
padding: 0.35rem 0.7rem;
border-radius: 6px;
border: 1px solid #475569;
background: #334155;
color: #f8fafc;
cursor: pointer;
}
.stream-head button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.stream-status {
margin-left: auto;
color: #94a3b8;
font: 0.72rem/1 var(--mono);
}
.stream-log {
margin: 0;
padding: 0.75rem 0.85rem;
min-height: 6rem;
max-height: 18rem;
overflow: auto;
font: 0.78rem/1.45 var(--mono);
white-space: pre-wrap;
word-break: break-word;
}
.stream-log .ev-mark {
color: #93c5fd;
}
.stream-log .ev-reason {
color: #c4b5fd;
}
.stream-log .ev-err {
color: #fca5a5;
}
.code-head {
display: flex;
flex-wrap: wrap;
@@ -763,14 +854,96 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}});
}});
}}
function initStreamPanel() {{
if (!window.MARQDO_VIEW_LIVE) return;
var log = document.getElementById("stream-log");
var status = document.getElementById("stream-status");
var runBtn = document.getElementById("stream-run");
if (!log || !window.EventSource) return;
var es = new EventSource("/api/events?path=" + encodeURIComponent(window.MARQDO_FILE_PATH || ""));
function appendLine(cls, text) {{
var span = document.createElement("span");
if (cls) span.className = cls;
span.textContent = text;
log.appendChild(span);
log.appendChild(document.createTextNode("\\n"));
log.scrollTop = log.scrollHeight;
}}
es.onopen = function () {{
if (status) status.textContent = "connected";
}};
es.onerror = function () {{
if (status) status.textContent = "reconnecting…";
}};
es.onmessage = function (msg) {{
try {{
var ev = JSON.parse(msg.data);
var t = ev.type || "?";
if (t === "reasoning") {{
appendLine("ev-reason", ev.text || "");
}} else if (t === "delta") {{
appendLine(null, ev.text || "");
}} else if (t === "error") {{
appendLine("ev-err", "error: " + (ev.message || ""));
}} else if (t === "round" || t === "decision" || t === "run_start" || t === "done") {{
var mark = t;
if (t === "round") mark += " #" + (ev.round != null ? ev.round : "");
if (t === "decision") mark += " " + (ev.decision || "");
if (t === "done" && ev.path) mark += " " + ev.path;
appendLine("ev-mark", "— " + mark + " —");
if (t === "done" && typeof ev.result === "string" && ev.result) {{
appendLine(null, ev.result.slice(0, 2000));
}}
if (ev.workbook) {{
appendLine("ev-mark", "workbook: " + ev.workbook);
}}
}} else {{
appendLine("ev-mark", JSON.stringify(ev));
}}
}} catch (e) {{
appendLine("ev-err", String(msg.data || e));
}}
}};
if (runBtn) {{
runBtn.addEventListener("click", function () {{
runBtn.disabled = true;
if (status) status.textContent = "running…";
log.textContent = "";
var stdinEl = document.getElementById("stdin");
fetch("/api/run", {{
method: "POST",
headers: {{ "Content-Type": "application/json" }},
body: JSON.stringify({{
path: window.MARQDO_FILE_PATH || "",
stdin: stdinEl ? stdinEl.value : ""
}})
}})
.then(function (r) {{ return r.json(); }})
.then(function (data) {{
if (!data.ok) {{
appendLine("ev-err", data.error || "run failed");
if (status) status.textContent = "error";
}}
}})
.catch(function (e) {{
appendLine("ev-err", String(e));
if (status) status.textContent = "error";
}})
.finally(function () {{ runBtn.disabled = false; }});
}});
}}
}}
if (document.readyState === "loading") {{
document.addEventListener("DOMContentLoaded", function () {{
initForeignCards();
initOutlineSearch();
initStreamPanel();
}});
}} else {{
initForeignCards();
initOutlineSearch();
initStreamPanel();
}}
function initOutlineSearch() {{
@@ -798,7 +971,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}});
}}
input.addEventListener("input", applyFilter);
tree.querySelectorAll("a[href^='#fn-']").forEach(function (a) {{
document.querySelectorAll("a[href^='#fn-'], a[href^='#wb-']").forEach(function (a) {{
a.addEventListener("click", function (ev) {{
var id = (a.getAttribute("href") || "").slice(1);
var el = id ? document.getElementById(id) : null;
@@ -1085,6 +1258,19 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
outline = outline_block,
)
};
let plan_card = plan_result_card(&vm.stdout, links);
let stream_panel = match links {
LinkMode::Live => r#"<div class="stream-panel">
<div class="stream-head">
<strong>Stream</strong>
<button type="button" id="stream-run">Run</button>
<span class="stream-status" id="stream-status">idle</span>
</div>
<pre class="stream-log" id="stream-log"></pre>
</div>"#
.to_string(),
LinkMode::Static { .. } => String::new(),
};
let main = format!(
r#"
<script>
@@ -1100,6 +1286,8 @@ window.MARQDO_FILE_PATH = {path_js};
<section class="block">
<h2>Execution</h2>
{stdin_panel}
{stream_panel}
{plan_card}
<div class="out {status}">{out}</div>
{plots}
</section>
@@ -1116,6 +1304,8 @@ window.MARQDO_FILE_PATH = {path_js};
rel = escape(rel),
structure_block = structure_block,
stdin_panel = stdin_panel,
stream_panel = stream_panel,
plan_card = plan_card,
out = out_text,
plots = plots_html,
source = escape(&vm.source),
@@ -1123,6 +1313,73 @@ window.MARQDO_FILE_PATH = {path_js};
layout(rel, &nav, &main)
}
/// Plan / agent result map → card with workbook link and cache/rounds.
fn plan_result_card(stdout: &str, links: &LinkMode) -> String {
let trimmed = stdout.trim();
if trimmed.is_empty() {
return String::new();
}
let candidate = trimmed
.lines()
.rev()
.find(|l| l.trim_start().starts_with('{'))
.unwrap_or(trimmed);
let Ok(v) = serde_json::from_str::<serde_json::Value>(candidate) else {
return String::new();
};
let workbook = v.get("workbook").and_then(|x| x.as_str());
let cache = v.get("cache").and_then(|x| x.as_str());
let rounds = v
.get("rounds")
.and_then(|x| x.as_u64())
.or_else(|| v.get("round").and_then(|x| x.as_u64()));
let status = v.get("status").and_then(|x| x.as_str());
if workbook.is_none() && cache.is_none() && rounds.is_none() {
return String::new();
}
let mut meta = Vec::new();
if let Some(s) = status {
meta.push(format!("status={}", escape(s)));
}
if let Some(c) = cache {
meta.push(format!("cache={}", escape(c)));
}
if let Some(r) = rounds {
meta.push(format!("rounds={r}"));
}
let link = match (workbook, links) {
(Some(wb), LinkMode::Live) => {
let href = format!("/file?path={}", urlencoding_path(wb));
format!(
r#"<a href="{href}">Open workbook</a> <code>{}</code>"#,
escape(wb)
)
}
(Some(wb), LinkMode::Static { .. }) => {
format!(r#"workbook <code>{}</code>"#, escape(wb))
}
_ => String::new(),
};
format!(
r#"<div class="plan-card"><strong>Plan result</strong><div class="plan-meta">{}</div>{}</div>"#,
meta.join(" · "),
link
)
}
fn urlencoding_path(s: &str) -> String {
let mut out = String::new();
for b in s.as_bytes() {
match *b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
out.push(*b as char);
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn escape_js_string(s: &str) -> String {
let mut out = String::from('"');
for c in s.chars() {
+158 -10
View File
@@ -10,9 +10,12 @@ mod render;
pub use output::{write_static, OutputOptions};
use std::fs;
use std::io::{self, Read};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::time::Duration;
use anyhow::{bail, Context, Result};
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
@@ -38,6 +41,7 @@ pub struct DebugOptions {
pub open_browser: bool,
}
#[derive(Clone)]
pub(crate) struct ViewRoot {
pub root: PathBuf,
pub only_file: Option<PathBuf>,
@@ -60,10 +64,14 @@ pub fn serve(opts: ViewOptions) -> Result<()> {
let _ = open_url(&url);
}
// Per-request threads so SSE long-poll and `/api/run` do not block each other.
for request in server.incoming_requests() {
if let Err(err) = handle(&root_info, request) {
eprintln!("view request error: {err:#}");
}
let root = root_info.clone();
std::thread::spawn(move || {
if let Err(err) = handle(&root, request) {
eprintln!("view request error: {err:#}");
}
});
}
Ok(())
}
@@ -156,12 +164,16 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
if method == Method::Post {
let (path_part, _) = split_url(&url);
if path_part == "/api/foreign-run" {
return api_foreign_run(root, request);
match path_part {
"/api/foreign-run" => return api_foreign_run(root, request),
"/api/run" => return api_run(root, request),
_ => {
let resp =
Response::from_string("method not allowed").with_status_code(StatusCode(405));
let _ = request.respond(resp);
return Ok(());
}
}
let resp = Response::from_string("method not allowed").with_status_code(StatusCode(405));
let _ = request.respond(resp);
return Ok(());
}
if method != Method::Get {
@@ -197,6 +209,7 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
let json = files_json(&root.files);
respond_json(request, json)
}
"/api/events" => api_events(request),
_ => {
let resp = Response::from_string("not found").with_status_code(StatusCode(404));
let _ = request.respond(resp);
@@ -291,9 +304,9 @@ pub(crate) fn build_file_view(
stdin_lines: &[String],
live: bool,
) -> Result<FileViewModel> {
let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
let mut source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
// Structure shows this file only — do not merge imported lib bodies into the tree.
let (structure, outline, input_prompts) = match crate::parse::parse_source(&source) {
let (mut structure, mut outline, input_prompts) = match crate::parse::parse_source(&source) {
Ok(module) => (
render_module_structure(&module, &source),
crate::view::render::render_function_outline(&module),
@@ -334,6 +347,17 @@ pub(crate) fn build_file_view(
),
}
};
// Re-read after run so writeback slots / workbook edits show in Structure.
if !awaiting_input {
if let Ok(next) = fs::read_to_string(abs) {
source = next;
if let Ok(module) = crate::parse::parse_source(&source) {
structure = render_module_structure(&module, &source);
outline = crate::view::render::render_function_outline(&module);
}
}
}
outline.push_str(&crate::view::render::render_writeback_outline(&source));
Ok(FileViewModel {
rel_path: rel.to_string(),
source,
@@ -524,6 +548,130 @@ fn api_foreign_run(root: &ViewRoot, mut request: Request) -> Result<()> {
respond_json(request, json)
}
/// SSE: long-lived `text/event-stream` of EventBus JSON maps (`data: …\n\n`).
fn api_events(request: Request) -> Result<()> {
let rx = crate::host::event_bus::EventBus::global().subscribe();
let body = SseBody::new(rx);
let ct = Header::from_bytes(&b"Content-Type"[..], &b"text/event-stream; charset=utf-8"[..])
.map_err(|_| anyhow::anyhow!("header"))?;
let cc = Header::from_bytes(&b"Cache-Control"[..], &b"no-cache"[..])
.map_err(|_| anyhow::anyhow!("header"))?;
let conn = Header::from_bytes(&b"Connection"[..], &b"keep-alive"[..])
.map_err(|_| anyhow::anyhow!("header"))?;
let resp = Response::empty(StatusCode(200))
.with_header(ct)
.with_header(cc)
.with_header(conn)
.with_data(body, None)
.with_chunked_threshold(0);
request.respond(resp).context("respond sse")?;
Ok(())
}
/// Background `run_file` for the live Stream panel; events go to the EventBus.
fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> {
let mut body = Vec::new();
std::io::Read::read_to_end(&mut request.as_reader(), &mut body)?;
let body = String::from_utf8_lossy(&body);
let v: serde_json::Value = serde_json::from_str(&body).unwrap_or(serde_json::Value::Null);
let rel = v.get("path").and_then(|x| x.as_str()).unwrap_or("").to_string();
let stdin_raw = v.get("stdin").and_then(|x| x.as_str()).unwrap_or("");
let stdin_lines = split_stdin_text(stdin_raw);
if rel.is_empty() {
return respond_json(
request,
serde_json::json!({ "ok": false, "error": "missing path" }).to_string(),
);
}
let abs = match resolve_rel(root, &rel) {
Ok(p) => p,
Err(e) => {
return respond_json(
request,
serde_json::json!({ "ok": false, "error": format!("{e:#}") }).to_string(),
);
}
};
let root_path = root.root.clone();
let rel_clone = rel.clone();
std::thread::spawn(move || {
let start = serde_json::json!({
"type": "run_start",
"path": rel_clone,
});
crate::host::event_bus::EventBus::global().publish_json(&start.to_string());
let source = fs::read_to_string(&abs).unwrap_or_default();
let effective = effective_stdin(&source, &stdin_lines);
let mut opts = RunOptions::default();
opts.stdin_lines = effective;
opts.sleep_limit_ms = Some(30_000);
opts.fs_root = Some(root_path);
match run_file_capture(&abs, &opts) {
Ok(cap) => {
let done = serde_json::json!({
"type": "done",
"path": rel_clone,
"ok": true,
"result": cap.stdout,
});
crate::host::event_bus::EventBus::global().publish_json(&done.to_string());
}
Err(e) => {
let err = serde_json::json!({
"type": "error",
"path": rel_clone,
"message": format!("{e:#}"),
});
crate::host::event_bus::EventBus::global().publish_json(&err.to_string());
}
}
});
respond_json(
request,
serde_json::json!({ "ok": true, "started": true, "path": rel }).to_string(),
)
}
struct SseBody {
rx: Receiver<String>,
buf: Vec<u8>,
pos: usize,
}
impl SseBody {
fn new(rx: Receiver<String>) -> Self {
Self {
rx,
buf: Vec::new(),
pos: 0,
}
}
}
impl Read for SseBody {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
loop {
if self.pos < self.buf.len() {
let n = (self.buf.len() - self.pos).min(out.len());
out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
self.pos += n;
return Ok(n);
}
match self.rx.recv_timeout(Duration::from_secs(15)) {
Ok(json) => {
self.buf = format!("data: {json}\n\n").into_bytes();
self.pos = 0;
}
Err(RecvTimeoutError::Timeout) => {
self.buf = b": ping\n\n".to_vec();
self.pos = 0;
}
Err(RecvTimeoutError::Disconnected) => return Ok(0),
}
}
}
}
fn respond_html(request: Request, body: String) -> Result<()> {
let header = Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..])
.map_err(|_| anyhow::anyhow!("header"))?;
+71 -4
View File
@@ -445,14 +445,81 @@ fn stmt_end_line(stmt: &Stmt) -> u32 {
fn output_card(line: u32, writebacks: &HashMap<u32, String>) -> String {
match writebacks.get(&line) {
Some(body) => format!(
r#"<div class="card output-card"><span class="badge">output</span><pre class="output-body">{}</pre></div>"#,
escape(body)
),
Some(body) => {
let badges = writeback_badges(body);
format!(
r#"<div class="card output-card" id="wb-{line}"><div class="wb-badges">{badges}</div><pre class="output-body">{}</pre></div>"#,
escape(body)
)
}
None => String::new(),
}
}
fn writeback_badges(body: &str) -> String {
let mut keys = Vec::new();
for line in body.lines() {
if let Some(rest) = line.strip_prefix('[') {
if let Some(end) = rest.find(']') {
let k = &rest[..end];
if !k.is_empty() && !keys.iter().any(|x| x == k) {
keys.push(k.to_string());
}
}
}
}
if keys.is_empty() {
return r#"<span class="badge wb-badge">output</span>"#.into();
}
keys.into_iter()
.map(|k| {
let cls = match k.as_str() {
"ok" => "wb-ok",
"error" => "wb-error",
"trace" => "wb-trace",
_ => "wb-other",
};
format!(r#"<span class="badge wb-badge {cls}">{k}</span>"#, k = escape(&k))
})
.collect::<Vec<_>>()
.join(" ")
}
/// Outline links to writeback cards (`#wb-{line}`).
pub fn render_writeback_outline(source: &str) -> String {
let map = writeback::writeback_map(source);
if map.is_empty() {
return String::new();
}
let mut lines: Vec<u32> = map.keys().copied().filter(|l| *l > 0).collect();
lines.sort_unstable();
if lines.is_empty() {
return String::new();
}
let mut out = String::from(
r#"<div class="wb-outline" id="wb-outline"><div class="wb-outline-title">Writebacks</div><ul class="outline-tree">"#,
);
for line in lines {
let body = map.get(&line).map(|s| s.as_str()).unwrap_or("");
let label = if body.contains("[error]") {
"error"
} else if body.contains("[ok]") {
"ok"
} else if body.contains("[trace]") {
"trace"
} else {
"output"
};
out.push_str(&format!(
r##"<li class="outline-item"><a href="#wb-{line}">L{line} · {label}</a></li>"##,
line = line,
label = label,
));
}
out.push_str("</ul></div>");
out
}
fn render_stmt(
stmt: &Stmt,
lines: &[ClassifiedLine],