From 7e3b193d496575bf99b0642be592471f39981b56 Mon Sep 17 00:00:00 2001 From: cflmy Date: Mon, 10 Aug 2026 17:25:24 +0800 Subject: [PATCH] Stop plan loops after child success; harden stream UX. Prefer DONE + runtime solidify when the child already returned a value, compact parent observations, drop the SSE 8MiB raw-buffer abort, and drip-stream the view panel via POST /api/run. Co-authored-by: Cursor --- doc/design/view.md | 37 +- doc/roadmap/agent-streaming.md | 12 +- ext/ai/agent.mq.md | 177 ++++++++-- src/host/net.rs | 63 +++- src/view/html.rs | 622 ++++++++++++++++++++++++++++----- src/view/mod.rs | 127 +++++-- src/view/render.rs | 2 + 7 files changed, 868 insertions(+), 172 deletions(-) diff --git a/doc/design/view.md b/doc/design/view.md index d359795..3d01333 100644 --- a/doc/design/view.md +++ b/doc/design/view.md @@ -102,11 +102,39 @@ marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc | `GET` | `/` | 默认打开第一个 `.mq.md`(无文件时为空提示) | | `GET` | `/file?path=…` | 单文件页 | | `GET` | `/api/tree` | JSON 树(可选) | -| `GET` | `/api/events?path=…` | SSE(`text/event-stream`):订阅进程内 EventBus(`reasoning` / `delta` / `round` / `decision` / `done` / `error`) | -| `POST` | `/api/run` | JSON `{path, stdin?}`:后台 `run_file`;事件进 bus;结束补 `done`/`error`(不替代页内整页 stdout) | +| `GET` | `/api/events?path=…` | 可选长订 EventBus(调试);**Stream 面板默认不用**(避免页载常连导致标签页一直转圈) | +| `POST` | `/api/run` | JSON `{path, stdin?}` → **直接返回** `text/event-stream`(本次 run 的事件);结束后关流 | | `POST` | `/api/foreign-run` | 外联代码块试跑 | -根目录锁死;拒绝 `..` 逃逸。默认页加载仍整页执行;Stream 面板为增强路径(`EventSource` + Run)。 +根目录锁死;拒绝 `..` 逃逸。默认页加载仍可整页执行;Stream 为增强路径。 + +### 5.1 Stream 面板(对齐主流 LLM 呈现) + +参考常见助手产品(思考折叠 + 正文流式、工具/子步骤独立卡片):**不要**把所有 SSE 事件打成一条混色终端日志。 + +| 区块 | 事件 | 呈现 | +|------|------|------| +| **Thinking** | `reasoning` | 可折叠;流式追加到同一块;默认展开直至本轮 `delta`/`done` 开始,之后可收起 | +| **Answer** | `delta` | **主文**;token 连续拼进同一段落(禁止每 token 换行);主色正文 | +| **Decision** | `decision` | 时间线条目标记(`RUN` / `CONTINUE` / `DONE` + 可选 summary) | +| **Child / Workbook** | `round` | **独立卡片**:轮次、退出码、workbook 链(`/file?path=`)、可选 `result` 摘要;与父思考/答案视觉分离 | +| **Status** | `run_start` / `done` / `error` | 顶栏状态 + 错误行;`done.result` 仅在无 Answer 块时作摘要,不与 reasoning 混排 | + +**传输与流畅度(对齐 ChatGPT 类产品):** + +1. **Run = 一次 `fetch` POST**,用 `ReadableStream` 读响应体里的 SSE 帧;**不要**页载常驻 `EventSource`。 +2. **「Run with input」拦截表单**:`preventDefault` 后走同一 Stream `/api/run`,**禁止整页重载**;带 `?stdin=` 进入时 live 页也不再阻塞跑完,改为自动开 Stream。 +3. **只改 Stream 对话框 DOM**;token **按动画帧合批**写入单一文本节点(避免每 token 触发布局)。 +4. **Stick-to-bottom**:仅在用户仍贴底时跟随;程序化 `scrollTop` 产生的 scroll 事件忽略;上拉后不抢滚动,可点「↓ Latest」。 +5. **Stop**:`AbortController` 中止 fetch。 + +视觉约束(与 §2 一致): + +- 浅色内容面,不用深色「伪终端」底;Thinking 用次要字色 / 浅底。 +- 一屏只突出 Answer;Thinking 与 Child 是附属。 +- plan 多轮:每一轮 Child 一张卡;父侧 Thinking/Answer 按 decision 分轮,不清空历史。 + +事件字段约定(与 [agent-streaming.md](../roadmap/agent-streaming.md) 一致):`round` 可带 `result`(子 `# main` 返回值摘要);`reasoning`/`delta` 的 `text` 为增量。 --- @@ -116,4 +144,5 @@ marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc 2. `view output public -o public`(或临时目录)生成可点的 `index.html`(首文件)与各 `pages/…`。 3. 静态页中执行区与 `marqdo run` 一致(未加 `--no-exec` 时);失败诊断路径无 `\\?\`。 4. 冷启动无明显外网依赖。 -5. 调试用 `marqdo debug`(默认端口 7430),与 view 页面分离。 +5. 调试用 `marqdo debug`(默认端口 7430),与 view 页面分离。 +6. Stream:`fetch`+SSE 局部更新;Thinking/Answer 分栏;stick-to-bottom;rAF 合批;页载不常连 EventSource。 diff --git a/doc/roadmap/agent-streaming.md b/doc/roadmap/agent-streaming.md index 1350f74..bcf4c46 100644 --- a/doc/roadmap/agent-streaming.md +++ b/doc/roadmap/agent-streaming.md @@ -65,7 +65,7 @@ ext/ai/agent step/plan 订阅事件 → 可选透传或写回「过程槽」 | `reasoning` | 模型思考增量(如 DeepSeek `reasoning_content`) | `text` | | `delta` | 模型答案增量文本 | `text` | | `tool_start` / `tool_end` | 工具轮 | `name`, `result?` | -| `round` | plan 轮次边界 | `round`, `workbook`, `exit_code?` | +| `round` | plan 轮次边界(子工作簿跑完) | `round`, `workbook`, `exit_code?`, `result?`(子返回值摘要) | | `decision` | DONE / CONTINUE / RUN | `decision`, `summary?` | | `done` | 本调用结束 | `result`(答案正文;不含 thinking) | | `error` | 失败 | `message` | @@ -113,9 +113,17 @@ plan 特有: | 面 | 做法 | |----|------| | CLI | `delta` 直接写 stdout(无额外 JSON 包装);结构化事件可 `--trace-events` 走 stderr / 旁路文件 | -| `marqdo view` | 调试/运行面板订阅同一事件(WebSocket 或 SSE) | +| `marqdo view` | Execution 区 Stream 面板订阅 SSE(见 [view.md](../design/view.md) §5.1):Thinking / Answer / Child 分栏,非混色日志 | | 库调用方 | foreach 事件集合,自行决定 UI | +**view Stream 锁定(S3 UI):** + +1. `reasoning` → 可折叠 Thinking;`delta` → 主文 Answer(连续拼接)。 +2. `round` → 独立 Child/Workbook 卡(路径链 + 可选 `result`);不与父 Answer 混排。 +3. `decision` → 时间线条目标记。 +4. 视觉跟 view HIG 浅色壳,不用深色终端底。 +5. **传输**:`POST /api/run` 直接 SSE;前端 `fetch`+`ReadableStream`(非页载 EventSource);rAF 合批;stick-to-bottom。 + --- ## 4. 与「返回优先」的关系 diff --git a/ext/ai/agent.mq.md b/ext/ai/agent.mq.md index d4f286f..422ac16 100644 --- a/ext/ai/agent.mq.md +++ b/ext/ai/agent.mq.md @@ -97,10 +97,10 @@ Allowlist check, then invoke the runbook `##` via `lib/subtask` (`spawn fn=` → + `goal` + `skeleton`=single -Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skeleton=dual`: research then write agents. Solidify notes remind the parent to replace proven `step` calls with ordinary `##` code. +Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skeleton=dual`: research then write agents. On success the parent chooses DONE; runtime `agent_workbook_solidify` freezes the answer. *`q` = > json.quote text=`goal` * -*`esc` = > json.parse text={"h":"---\ntitle: agent workbook\n> ext/ai/llm.mq.md\n> ext/ai/agent.mq.md\n> lib/json.mq.md\n> lib/sys.mq.md\n> lib/writeback.mq.md\n> lib/subtask.mq.md\n---\n\n# Goal\n\nParent goal is embedded as JSON in # main.\n\n## Solidify\n\nWhen a step is proven, replace worker.step with ordinary code that returns the answer via **…** (not print). Quiet file subtasks discard stdout; the parent reads wait.value.\n\n# main\n\n> llm.load_env\n\n","s1":"\u002a\u0060model\u0060 = > llm.llm \u002a\n","s2":"\u002a\u0060tools\u0060 = > json.parse text=[] \u002a\n","s3":"\u002a\u0060worker\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You are a workbook worker. Finish the task; do not invent tools. Prefer a direct answer. \u002a\n","s4":"\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","s5":"} \u002a\n","s6":"\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task \u002a\n","s7":"\u002a\u0060out\u0060 = > \u0060worker\u0060.step task=\u0060task\u0060 \u002a\n","s7b":"\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result \u002a\n","s8":"\u002a\u002a\u0060text\u0060\u002a\u002a\n","d3":"\u002a\u0060research\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You gather facts for the goal. Be concise. Do not invent tools. \u002a\n","d3b":"\u002a\u0060writer\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You write the final answer from research notes. Do not invent tools. \u002a\n","d4":"\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","d5":"} \u002a\n","d6":"\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task \u002a\n","d7":"\u002a\u0060notes\u0060 = > \u0060research\u0060.step task=\u0060task\u0060 \u002a\n","d8":"\u002a\u0060ns\u0060 = > json.stringify value=\u0060notes\u0060 \u002a\n","d9":"\u002a\u0060wt\u0060 = Write the final answer. Research notes: \u002a\n","d10":"\u002a\u0060wt\u0060 = \u0060wt\u0060 + \u0060ns\u0060 \u002a\n","d11":"\u002a\u0060out\u0060 = > \u0060writer\u0060.step task=\u0060wt\u0060 \u002a\n","d11b":"\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result \u002a\n","d12":"\u002a\u002a\u0060text\u0060\u002a\u002a\n"} * +*`esc` = > json.parse text={"h":"---\ntitle: agent workbook\n> ext/ai/llm.mq.md\n> ext/ai/agent.mq.md\n> lib/json.mq.md\n> lib/sys.mq.md\n> lib/writeback.mq.md\n> lib/subtask.mq.md\n---\n\n# Goal\n\nParent goal is embedded as JSON in # main.\n\n## Solidify\n\nWhen the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as **return** (do not invent long FIND/REPLACE).\n\n# main\n\n> llm.load_env\n\n","s1":"\u002a\u0060model\u0060 = > llm.llm \u002a\n","s2":"\u002a\u0060tools\u0060 = > json.parse text=[] \u002a\n","s3":"\u002a\u0060worker\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You are a workbook worker. Finish the task; do not invent tools. Prefer a direct answer. \u002a\n","s4":"\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","s5":"} \u002a\n","s6":"\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task \u002a\n","s7":"\u002a\u0060out\u0060 = > \u0060worker\u0060.step task=\u0060task\u0060 \u002a\n","s7b":"\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result \u002a\n","s8":"\u002a\u002a\u0060text\u0060\u002a\u002a\n","d3":"\u002a\u0060research\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You gather facts for the goal. Be concise. Do not invent tools. \u002a\n","d3b":"\u002a\u0060writer\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You write the final answer from research notes. Do not invent tools. \u002a\n","d4":"\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","d5":"} \u002a\n","d6":"\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task \u002a\n","d7":"\u002a\u0060notes\u0060 = > \u0060research\u0060.step task=\u0060task\u0060 \u002a\n","d8":"\u002a\u0060ns\u0060 = > json.stringify value=\u0060notes\u0060 \u002a\n","d9":"\u002a\u0060wt\u0060 = Write the final answer. Research notes: \u002a\n","d10":"\u002a\u0060wt\u0060 = \u0060wt\u0060 + \u0060ns\u0060 \u002a\n","d11":"\u002a\u0060out\u0060 = > \u0060writer\u0060.step task=\u0060wt\u0060 \u002a\n","d11b":"\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result \u002a\n","d12":"\u002a\u002a\u0060text\u0060\u002a\u002a\n"} * *`h` = > json.get value=`esc` key=h * *`s1` = > json.get value=`esc` key=s1 * *`s2` = > json.get value=`esc` key=s2 * @@ -323,9 +323,89 @@ Parent developer-agent prompt. `phase=decompose`: pre-run (design step ③) befo *`up` = None* *`skill` = > agent_marqdo_skill * -*`obs_s` = > json.stringify value=`observation` * + +Omit full workbook `source` and large slot/value bodies from the parent prompt — they bloat context and invite endless solidify guessing. Runtime `agent_workbook_solidify` runs on DECISION: DONE. + +*`obs_path` = > json.get value=`observation` key=path * +*`obs_code` = > json.get value=`observation` key=exit_code * +*`obs_val` = > json.get value=`observation` key=value * +*`obs_slots` = > json.get value=`observation` key=slots * +*`obs_src` = > json.get value=`observation` key=source * +*`src_len` = 0* +*`has_step` = False* +1. `obs_src` + *`src_len` = > len value=`obs_src` * + *`step_parts` = > split value=`obs_src` sep=worker.step * + *`n_step` = > len value=`step_parts` * + 1. `n_step` > 1 + *`has_step` = True* + 2. * + *`_` = 1* +2. * + *`_` = 1* + +*`compact` = > json.parse text={"note":"source/slot bodies omitted. If exit_code is 0 and has_value, prefer DECISION: DONE immediately — runtime solidifies worker.step. CONTINUE only to fix failures or redesign structure. Never paste user prose into REPLACE."} * +*`compact` = > json.set map=`compact` key=path value=`obs_path` * +*`compact` = > json.set map=`compact` key=exit_code value=`obs_code` * +*`compact` = > json.set map=`compact` key=source_len value=`src_len` * +*`compact` = > json.set map=`compact` key=has_worker_step value=`has_step` * +*`compact` = > json.set map=`compact` key=solidify_on_done value=True * + +*`val_txt` = > str value=`obs_val` * +*`val_len` = > len value=`val_txt` * +1. `obs_val` + *`compact` = > json.set map=`compact` key=has_value value=True * + *`compact` = > json.set map=`compact` key=value_len value=`val_len` * + 1. `val_len` > 200 + *`_` = 1* + 2. * + *`compact` = > json.set map=`compact` key=value value=`obs_val` * +2. * + *`compact` = > json.set map=`compact` key=has_value value=False * + +*`slots_brief` = > json.parse text=[] * +1. `obs_slots` + - [`slot`](`obs_slots`) + *`sk` = > json.get value=`slot` key=key * + *`sl` = > json.get value=`slot` key=line * + *`sb` = > json.get value=`slot` key=body * + *`sb_txt` = > str value=`sb` * + *`sb_len` = > len value=`sb_txt` * + *`brief` = > json.parse text={"key":""} * + *`brief` = > json.set map=`brief` key=key value=`sk` * + *`brief` = > json.set map=`brief` key=line value=`sl` * + *`brief` = > json.set map=`brief` key=body_len value=`sb_len` * + *`slots_brief` = > json.append list=`slots_brief` item=`brief` * +2. * + *`_` = 1* +*`compact` = > json.set map=`compact` key=slots value=`slots_brief` * + +*`last_ok` = > json.get value=`observation` key=last_ok * +*`last_error` = > json.get value=`observation` key=last_error * +1. `last_ok` + *`ok_txt` = > str value=`last_ok` * + *`ok_len` = > len value=`ok_txt` * + *`compact` = > json.set map=`compact` key=last_ok_len value=`ok_len` * + 1. `ok_len` > 200 + *`compact` = > json.set map=`compact` key=last_ok_omitted value=True * + 2. * + *`compact` = > json.set map=`compact` key=last_ok value=`last_ok` * +2. * + *`_` = 1* +1. `last_error` + *`err_txt` = > str value=`last_error` * + *`err_len` = > len value=`err_txt` * + 1. `err_len` > 200 + *`compact` = > json.set map=`compact` key=last_error_omitted value=True * + *`compact` = > json.set map=`compact` key=last_error_len value=`err_len` * + 2. * + *`compact` = > json.set map=`compact` key=last_error value=`last_error` * +2. * + *`_` = 1* + +*`obs_s` = > json.stringify value=`compact` * *`goal_s` = > json.stringify value=`goal` * -*`esc` = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- workbook observation ---\n","d":"\n\n--- marqdo skill ---\n","e_rev":"\n\n--- how to act ---\nYou are a Marqdo agent-development master.\nPriority order:\n1) Code first: if the goal is a fixed answer, solidify to a **return** (e.g. **pong**) or ordinary ## — no further LLM worker.step. Do not rely on > print; file subtasks are quiet and the parent consumes wait.value.\n2) If exit_code is 0 AND the workbook source still contains worker.step (or .单步), you MUST CONTINUE with a FIND/REPLACE that solidifies to a returned answer. Never DONE while .step remains.\n3) If exit_code is 0 AND already solidified (no worker.step) with a clear main return, DECISION: DONE with a short SUMMARY.\n4) If exploring an alternate path, try a meaningfully DIFFERENT structure than prior attempts (e.g. dual agents, narrower standing, or pure code). Do not merely re-run the same step.\n5) Prefer multiple narrow agents over one giant standing when roles differ.\nNever rewrite the whole .mq.md file.\nReply with EXACTLY one protocol:\nDECISION: DONE\nSUMMARY: \nOR\nDECISION: CONTINUE\nPATCH:\n<<<\nFIND\n\n===\nREPLACE\n\n>>>\n(You may repeat <<< blocks.)\n","e_dec":"\n\n--- how to act ---\nYou are a Marqdo agent-development master. PRE-RUN DECOMPOSE: the workbook has NOT been executed yet.\nPriority order:\n1) Code first: if the goal is a fixed answer, PATCH to a **return** (no worker.step / .单步), then DECISION: RUN (runtime will spawn once) or DECISION: DONE with SUMMARY after solidify.\n2) If the skeleton is fine to execute as-is, reply DECISION: RUN (patches optional; zero patches are OK).\n3) To reshape before the first run, DECISION: CONTINUE with FIND/REPLACE patches; runtime applies them then spawns.\n4) Prefer multiple narrow agents when roles differ. Never rewrite the whole .mq.md file.\nReply with EXACTLY one protocol:\nDECISION: RUN\nOR\nDECISION: DONE\nSUMMARY: \nOR\nDECISION: CONTINUE\nPATCH:\n<<<\nFIND\n\n===\nREPLACE\n\n>>>\n(You may repeat <<< blocks.)\n","f":"\n\n--- explore attempt ---\n"} * +*`esc` = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- workbook observation ---\n","d":"\n\n--- marqdo skill ---\n","e_rev":"\n\n--- how to act ---\nYou are a Marqdo agent-development master.\nPriority order (STOP RULES — follow top-down):\n1) SUCCESS STOP: if exit_code is 0 AND has_value is true, reply DECISION: DONE with a one-line SUMMARY immediately. Do NOT invent FIND/REPLACE. Runtime agent_workbook_solidify removes worker.step on DONE — has_worker_step true is NOT a reason to CONTINUE.\n2) FAILURE ONLY: CONTINUE with short FIND/REPLACE (<20 lines) only when exit_code is non-zero, has_value is false, or the returned value clearly fails the goal. Prefer structure edits; never paste itineraries/schedules/observation prose into REPLACE.\n3) Code-first for fixed answers (e.g. pong): solidify via DONE (runtime) or a tiny structural patch — not by rewriting child prose.\n4) If exploring an alternate path, try a meaningfully DIFFERENT structure than prior attempts. Do not merely re-run the same step.\n5) Prefer multiple narrow agents over one giant standing when roles differ.\nNever rewrite the whole .mq.md file.\nThe moment success is observed, emit DONE and stop — do not keep being helpful.\nReply with EXACTLY one protocol:\nDECISION: DONE\nSUMMARY: \nOR\nDECISION: CONTINUE\nPATCH:\n<<<\nFIND\n\n===\nREPLACE\n\n>>>\n(You may repeat <<< blocks.)\n","e_dec":"\n\n--- how to act ---\nYou are a Marqdo agent-development master. PRE-RUN DECOMPOSE: the workbook has NOT been executed yet.\nPriority order:\n1) If the skeleton is fine to execute as-is, reply DECISION: RUN (zero patches OK). Prefer RUN over inventing user-facing prose.\n2) Code first: if the goal is a fixed answer, PATCH to a **return** (no worker.step / .单步), then DECISION: RUN or DECISION: DONE with SUMMARY after solidify.\n3) To reshape before the first run, DECISION: CONTINUE with short FIND/REPLACE (<20 lines); runtime applies them then spawns.\n4) Prefer multiple narrow agents when roles differ. Never paste long itineraries into REPLACE.\nNever rewrite the whole .mq.md file.\nReply with EXACTLY one protocol:\nDECISION: RUN\nOR\nDECISION: DONE\nSUMMARY: \nOR\nDECISION: CONTINUE\nPATCH:\n<<<\nFIND\n\n===\nREPLACE\n\n>>>\n(You may repeat <<< blocks.)\n","f":"\n\n--- explore attempt ---\n"} * *`a` = > json.get value=`esc` key=a * *`b` = > json.get value=`esc` key=b * *`c` = > json.get value=`esc` key=c * @@ -409,16 +489,21 @@ True when source still contains `worker.step` or `.单步`. + `round` + `workbook` + `exit_code` + + `result`=None + `stream`=False + `echo`=False -Append a `round` event when `stream=True`. Optional `echo` prints a short TTY marker (not the full workbook path). +Append a `round` event when `stream=True`. Optional `result` is the child `# main` return (for view Child cards). Optional `echo` prints a short TTY marker (not the full workbook path). 1. `stream` *`ev` = > json.parse text={"type":"round"} * *`ev` = > json.set map=`ev` key=round value=`round` * *`ev` = > json.set map=`ev` key=workbook value=`workbook` * *`ev` = > json.set map=`ev` key=exit_code value=`exit_code` * + 1. `result` + *`ev` = > json.set map=`ev` key=result value=`result` * + 2. * + *`_` = 1* *`events` = > json.append list=`events` item=`ev` * > sys.stream_publish event=`ev` 1. `echo` @@ -687,7 +772,7 @@ Non-hit path runs parent **decompose** before the first child spawn (`DECISION: *`out` = > json.set map=`out` key=summary value=`sum` * *`out` = > json.set map=`out` key=observation value=`last_obs` * *`out` = > json.set map=`out` key=result value=`child_val` * - *`events` = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` stream=`stream` echo=`echo` * + *`events` = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo` * 1. `writeback` *`body` = > json.stringify value=`out` * > writeback.record value=`body` key=ok @@ -734,7 +819,7 @@ Non-hit path runs parent **decompose** before the first child spawn (`DECISION: *`out` = > json.set map=`out` key=summary value=`sum` * *`out` = > json.set map=`out` key=observation value=`last_obs` * *`out` = > json.set map=`out` key=result value=`child_val` * - *`events` = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` stream=`stream` echo=`echo` * + *`events` = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo` * 1. `writeback` *`body` = > json.stringify value=`out` * > writeback.record value=`body` key=ok @@ -854,7 +939,7 @@ Non-hit path runs parent **decompose** before the first child spawn (`DECISION: *`child_val` = > json.get value=`aw` key=value * *`last_obs` = > json.get value=`aw` key=observation * *`round` = 1* - *`events` = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` stream=`stream` echo=`echo` * + *`events` = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo` * 1. `code` == 0 *`done` = 1* *`status` = ok* @@ -887,42 +972,66 @@ Non-hit path runs parent **decompose** before the first child spawn (`DECISION: *`code` = > json.get value=`aw` key=code * *`child_val` = > json.get value=`aw` key=value * *`last_obs` = > json.get value=`aw` key=observation * - *`events` = > plan_append_round events=`events` round=`round` workbook=`path` exit_code=`code` stream=`stream` echo=`echo` * - *`ctx` = > build_plan_context agent=`self` goal=`goal` observation=`last_obs` explore_attempt=`explore_attempt` explore_n=`explore_n` phase=revise * - 1. `stream` - *`evs` = > `model`.complete prompt=`ctx` stream=True echo=`echo` * - *`last_reply` = > llm.stream_result events=`evs` * - *`events` = > plan_merge_deltas events=`events` from=`evs` stream=`stream` * + *`events` = > plan_append_round events=`events` round=`round` workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo` * + +Deterministic success stop (loop engineering): when the child already returned a value, do not ask the parent LLM to invent solidify patches — DONE + runtime solidify. + + 1. `code` == 0 + 1. `child_val` + 1. `improve` + *`auto_done` = None* + 2. * + *`auto_done` = 1* + 2. * + *`auto_done` = None* 2. * - *`last_reply` = > `model`.complete prompt=`ctx` * - *`last_reply` = > trim value=`last_reply` * - *`dec` = > extract_plan_decision reply=`last_reply` * - *`events` = > plan_append_decision events=`events` decision=`dec` stream=`stream` * - 1. `dec` == DONE + *`auto_done` = None* + + 1. `auto_done` > agent_workbook_solidify path=`path` observation=`last_obs` *`done` = 1* *`status` = ok* - *`summary` = > extract_plan_summary reply=`last_reply` * + *`summary` = child returned value; solidified * *`err` = None* + *`dec` = DONE* + *`events` = > plan_append_decision events=`events` decision=`dec` stream=`stream` summary=`summary` * *`left` = 0* - 2. `dec` == CONTINUE - *`n` = > fs.apply_patch_blocks path=`path` text=`last_reply` * - 1. `n` - *`left` = `left` - 1* + 2. * + *`ctx` = > build_plan_context agent=`self` goal=`goal` observation=`last_obs` explore_attempt=`explore_attempt` explore_n=`explore_n` phase=revise * + 1. `stream` + *`evs` = > `model`.complete prompt=`ctx` stream=True echo=`echo` * + *`last_reply` = > llm.stream_result events=`evs` * + *`events` = > plan_merge_deltas events=`events` from=`evs` stream=`stream` * 2. * + *`last_reply` = > `model`.complete prompt=`ctx` * + *`last_reply` = > trim value=`last_reply` * + *`dec` = > extract_plan_decision reply=`last_reply` * + *`events` = > plan_append_decision events=`events` decision=`dec` stream=`stream` * + 1. `dec` == DONE + > agent_workbook_solidify path=`path` observation=`last_obs` + *`done` = 1* + *`status` = ok* + *`summary` = > extract_plan_summary reply=`last_reply` * + *`err` = None* + *`left` = 0* + 2. `dec` == CONTINUE + *`n` = > fs.apply_patch_blocks path=`path` text=`last_reply` * + 1. `n` + *`left` = `left` - 1* + 2. * + *`done` = 1* + *`status` = error* + *`err` = no patches applied * + *`summary` = > extract_plan_summary reply=`last_reply` * + *`left` = 0* + 3. `dec` == RUN + *`left` = `left` - 1* + 4. * *`done` = 1* *`status` = error* - *`err` = no patches applied * - *`summary` = > extract_plan_summary reply=`last_reply` * + *`err` = unrecognized plan decision * + *`summary` = `last_reply`* *`left` = 0* - 3. `dec` == RUN - *`left` = `left` - 1* - 4. * - *`done` = 1* - *`status` = error* - *`err` = unrecognized plan decision * - *`summary` = `last_reply`* - *`left` = 0* 1. `status` == ok 1. `promote` diff --git a/src/host/net.rs b/src/host/net.rs index e1ae7f1..71430cf 100644 --- a/src/host/net.rs +++ b/src/host/net.rs @@ -348,18 +348,22 @@ fn read_sse_body_to_events( echo: bool, ) -> Result, String> { let mut buf = String::new(); - let mut raw = String::new(); let mut events = Vec::new(); let mut result = String::new(); let mut data_buf: Vec = Vec::new(); let mut echoed = false; let mut saw_reasoning = false; + // Soft cap on *stored* event payload (bus still gets every frame). DeepSeek + // thinking can exceed tens of MiB; we must not retain the raw wire body. + let mut stored_bytes: usize = 0; + const STORE_CAP: usize = 2 * 1024 * 1024; let flush_data = |data_buf: &mut Vec, events: &mut Vec, result: &mut String, echoed: &mut bool, saw_reasoning: &mut bool, + stored_bytes: &mut usize, echo: bool| -> Result { if data_buf.is_empty() { @@ -376,14 +380,38 @@ fn read_sse_body_to_events( } let v: serde_json::Value = serde_json::from_str(data).map_err(|e| format!("openai sse json: {e}"))?; - Ok(push_openai_delta_events( + // Always publish to the view bus; optionally skip retaining huge histories. + let before = events.len(); + let stop = push_openai_delta_events( &v, events, result, echoed, saw_reasoning, echo, - )) + ); + // Cap retained history only; EventBus already has every frame for the view. + let mut i = before; + while i < events.len() { + let add = match &events[i] { + Value::Map(m) => m + .iter() + .filter(|(k, _)| *k == "text" || *k == "result" || *k == "message") + .filter_map(|(_, val)| match val { + Value::Text(t) => Some(t.len()), + _ => None, + }) + .sum::(), + _ => 0, + }; + if stored_bytes.saturating_add(add) > STORE_CAP { + events.truncate(i); + break; + } + *stored_bytes = stored_bytes.saturating_add(add); + i += 1; + } + Ok(stop) }; loop { @@ -394,10 +422,6 @@ fn read_sse_body_to_events( if n == 0 { break; } - raw.push_str(&buf); - if raw.len() > 8 * 1024 * 1024 { - return Err("http sse response exceeds 8MiB limit".into()); - } let line = buf.strip_suffix('\n').unwrap_or(&buf); let line = line.strip_suffix('\r').unwrap_or(line); if line.is_empty() { @@ -407,6 +431,7 @@ fn read_sse_body_to_events( &mut result, &mut echoed, &mut saw_reasoning, + &mut stored_bytes, echo, )? { break; @@ -424,6 +449,7 @@ fn read_sse_body_to_events( &mut result, &mut echoed, &mut saw_reasoning, + &mut stored_bytes, echo, )?; if echo && echoed { @@ -570,4 +596,27 @@ data: [DONE]\n\ _ => panic!("expected done map"), } } + + #[test] + fn sse_body_over_8mib_does_not_error() { + // Formerly failed with "http sse response exceeds 8MiB limit" because raw + // wire bytes were accumulated. Streaming must keep going; store is soft-capped. + let frame = + "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"0123456789\"}}]}\n\n"; + let mut body = String::with_capacity(9 * 1024 * 1024); + while body.len() < 8 * 1024 * 1024 + 1024 { + body.push_str(frame); + } + body.push_str("data: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\n"); + body.push_str("data: [DONE]\n\n"); + let ev = read_sse_body_to_events(std::io::Cursor::new(body), false).unwrap(); + assert!( + ev.iter().any(|e| matches!( + e, + Value::Map(m) if m.iter().any(|(k, v)| k == "type" && matches!(v, Value::Text(t) if t == "done")) + && m.iter().any(|(k, v)| k == "result" && matches!(v, Value::Text(t) if t == "ok")) + )), + "expected done with result ok" + ); + } } diff --git a/src/view/html.rs b/src/view/html.rs index dac3549..a44edaa 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -522,55 +522,168 @@ section.block > h2 { margin: 0 0 0.85rem; border: 1px solid var(--line); border-radius: var(--radius); - background: #0f172a; - color: #e2e8f0; + background: var(--surface); overflow: hidden; + position: relative; } .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); + padding: 0.65rem 0.85rem; + background: #fafafa; + border-bottom: 1px solid var(--line); + font: 0.85rem/1 var(--sans); + color: var(--ink); } .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; + padding: 0.4rem 0.85rem; + border-radius: 8px; + border: 1px solid var(--line); + background: #1d1d1f; + color: #fff; cursor: pointer; } .stream-head button:disabled { - opacity: 0.5; + opacity: 0.45; cursor: not-allowed; } .stream-status { margin-left: auto; - color: #94a3b8; + color: var(--muted); font: 0.72rem/1 var(--mono); } -.stream-log { - margin: 0; - padding: 0.75rem 0.85rem; - min-height: 6rem; - max-height: 18rem; +.stream-head button.stream-stop { + background: #fff; + color: #1d1d1f; + border-color: var(--line); +} +.stream-jump { + position: absolute; + left: 50%; + bottom: 0.65rem; + transform: translateX(-50%); + z-index: 2; + font: 0.72rem/1 var(--sans); + padding: 0.35rem 0.7rem; + border-radius: 999px; + border: 1px solid var(--line); + background: #fff; + color: var(--ink); + cursor: pointer; + box-shadow: 0 1px 2px rgba(0,0,0,0.06); +} +.stream-jump[hidden] { display: none; } +.stream-body { + position: relative; + padding: 0.85rem 1rem 1rem; + min-height: 5rem; + max-height: 28rem; overflow: auto; - font: 0.78rem/1.45 var(--mono); + display: flex; + flex-direction: column; + gap: 0.75rem; +} +.stream-empty { + color: var(--muted); + font: 0.85rem/1.4 var(--sans); + margin: 0; +} +.stream-turn { + display: flex; + flex-direction: column; + gap: 0.55rem; +} +.stream-thinking { + border: 1px solid var(--line); + border-radius: 10px; + background: #f5f5f7; + padding: 0.35rem 0.65rem 0.55rem; +} +.stream-thinking > summary { + cursor: pointer; + list-style: none; + font: 0.78rem/1.4 var(--sans); + color: var(--muted); + user-select: none; + padding: 0.25rem 0; +} +.stream-thinking > summary::-webkit-details-marker { display: none; } +.stream-thinking > summary::before { + content: "▸ "; + color: #aeaeb2; +} +.stream-thinking[open] > summary::before { content: "▾ "; } +.stream-thinking-body { + margin: 0.15rem 0 0; + font: 0.82rem/1.5 var(--sans); + color: #6e6e73; white-space: pre-wrap; word-break: break-word; } -.stream-log .ev-mark { - color: #93c5fd; +.stream-answer { + font: 0.95rem/1.55 var(--sans); + color: var(--ink); + white-space: pre-wrap; + word-break: break-word; } -.stream-log .ev-reason { - color: #c4b5fd; +.stream-answer:empty { display: none; } +.stream-decision { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.35rem 0.65rem; + font: 0.78rem/1.35 var(--sans); + color: var(--muted); + padding: 0.15rem 0; + border-top: 1px dashed var(--line); } -.stream-log .ev-err { - color: #fca5a5; +.stream-decision strong { + font-weight: 600; + color: #1d1d1f; + letter-spacing: 0.02em; +} +.stream-child { + border: 1px solid var(--line); + border-left: 3px solid #2563eb; + border-radius: 10px; + background: #f8fafc; + padding: 0.65rem 0.85rem; +} +.stream-child-head { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.4rem 0.75rem; + font: 0.78rem/1.3 var(--sans); + color: var(--muted); + margin-bottom: 0.35rem; +} +.stream-child-head strong { + color: #1d1d1f; + font-weight: 600; +} +.stream-child-head a { color: #1d4ed8; } +.stream-child-meta { + font: 0.72rem/1.3 var(--mono); + color: var(--muted); +} +.stream-child-body { + font: 0.88rem/1.5 var(--sans); + color: var(--ink); + white-space: pre-wrap; + word-break: break-word; +} +.stream-child-body:empty { display: none; } +.stream-err { + font: 0.85rem/1.45 var(--sans); + color: #9b1c1c; + background: #fff5f5; + border: 1px solid #e4c1c1; + border-radius: 8px; + padding: 0.55rem 0.75rem; + white-space: pre-wrap; } .code-head { display: flex; @@ -856,81 +969,383 @@ 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 body = document.getElementById("stream-body"); 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; + var stopBtn = document.getElementById("stream-stop"); + var jumpBtn = document.getElementById("stream-jump"); + if (!body) return; + + var turn = null; + var thinkingEl = null; + var thinkingBody = null; + var answerEl = null; + var reasonNode = null; + var answerNode = null; + var pinned = true; + var ignoreScroll = false; + var pendingReason = ""; + var pendingAnswer = ""; + var raf = 0; + // Drip 1 Unicode scalar per frame (一字一吐). Catch up if backlog grows. + var CHARS_PER_TICK = 1; + var abortCtrl = null; + + function nearBottom() {{ + return body.scrollHeight - body.scrollTop - body.clientHeight < 72; }} - 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)); + function updateJump() {{ + if (!jumpBtn) return; + jumpBtn.hidden = pinned; + }} + function scrollIfPinned() {{ + if (!pinned) {{ + updateJump(); + return; }} - }}; - 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; }}); + ignoreScroll = true; + body.scrollTop = body.scrollHeight; + // Ignore the scroll event our own assignment fires. + requestAnimationFrame(function () {{ + ignoreScroll = false; }}); + updateJump(); + }} + function onUserScrollIntent() {{ + // Re-evaluate after the browser applies the user scroll. + requestAnimationFrame(function () {{ + if (ignoreScroll) return; + pinned = nearBottom(); + updateJump(); + }}); + }} + body.addEventListener("scroll", function () {{ + if (ignoreScroll) return; + pinned = nearBottom(); + updateJump(); + }}, {{ passive: true }}); + body.addEventListener("wheel", onUserScrollIntent, {{ passive: true }}); + body.addEventListener("touchmove", onUserScrollIntent, {{ passive: true }}); + if (jumpBtn) {{ + jumpBtn.addEventListener("click", function () {{ + pinned = true; + ignoreScroll = true; + body.scrollTop = body.scrollHeight; + requestAnimationFrame(function () {{ ignoreScroll = false; }}); + updateJump(); + }}); + }} + + function clearStream() {{ + body.innerHTML = ""; + turn = null; + thinkingEl = null; + thinkingBody = null; + answerEl = null; + reasonNode = null; + answerNode = null; + pendingReason = ""; + pendingAnswer = ""; + if (raf) {{ cancelAnimationFrame(raf); raf = 0; }} + pinned = true; + updateJump(); + }} + function ensureTurn() {{ + if (turn) return; + turn = document.createElement("div"); + turn.className = "stream-turn"; + body.appendChild(turn); + }} + function ensureThinking() {{ + ensureTurn(); + if (thinkingEl) return; + thinkingEl = document.createElement("details"); + thinkingEl.className = "stream-thinking"; + thinkingEl.open = true; + var sum = document.createElement("summary"); + sum.textContent = "Thinking"; + thinkingBody = document.createElement("div"); + thinkingBody.className = "stream-thinking-body"; + reasonNode = document.createTextNode(""); + thinkingBody.appendChild(reasonNode); + thinkingEl.appendChild(sum); + thinkingEl.appendChild(thinkingBody); + turn.appendChild(thinkingEl); + }} + function ensureAnswer() {{ + ensureTurn(); + if (answerEl) return; + answerEl = document.createElement("div"); + answerEl.className = "stream-answer"; + answerNode = document.createTextNode(""); + answerEl.appendChild(answerNode); + turn.appendChild(answerEl); + }} + function flushPendingAll() {{ + if (raf) {{ cancelAnimationFrame(raf); raf = 0; }} + if (pendingReason) {{ + ensureThinking(); + reasonNode.data += pendingReason; + pendingReason = ""; + }} + if (pendingAnswer) {{ + ensureAnswer(); + answerNode.data += pendingAnswer; + pendingAnswer = ""; + }} + scrollIfPinned(); + }} + function dripPending() {{ + raf = 0; + function take(src, n) {{ + var chars = Array.from(src); + var takeN = Math.min(n, chars.length); + return [chars.slice(0, takeN).join(""), chars.slice(takeN).join("")]; + }} + if (pendingReason) {{ + ensureThinking(); + var n = pendingReason.length > 240 ? 12 : (pendingReason.length > 80 ? 4 : CHARS_PER_TICK); + var r = take(pendingReason, n); + reasonNode.data += r[0]; + pendingReason = r[1]; + }} else if (pendingAnswer) {{ + ensureAnswer(); + var n2 = pendingAnswer.length > 240 ? 12 : (pendingAnswer.length > 80 ? 4 : CHARS_PER_TICK); + var a = take(pendingAnswer, n2); + answerNode.data += a[0]; + pendingAnswer = a[1]; + }} + scrollIfPinned(); + if (pendingReason || pendingAnswer) {{ + raf = requestAnimationFrame(dripPending); + }} + }} + function queueText(kind, text) {{ + if (!text) return; + if (kind === "reasoning") pendingReason += text; + else pendingAnswer += text; + if (!raf) raf = requestAnimationFrame(dripPending); + }} + function formatResult(v) {{ + if (v == null) return ""; + if (typeof v === "string") return v; + try {{ return JSON.stringify(v, null, 2); }} catch (e) {{ return String(v); }} + }} + function resetTurnRefs() {{ + turn = null; + thinkingEl = null; + thinkingBody = null; + answerEl = null; + reasonNode = null; + answerNode = null; + }} + function addDecision(ev) {{ + flushPendingAll(); + ensureTurn(); + var row = document.createElement("div"); + row.className = "stream-decision"; + var label = document.createElement("strong"); + label.textContent = "DECISION: " + (ev.decision || "?"); + row.appendChild(label); + if (ev.summary) {{ + var s = document.createElement("span"); + s.textContent = ev.summary; + row.appendChild(s); + }} + turn.appendChild(row); + resetTurnRefs(); + scrollIfPinned(); + }} + function addChildCard(ev) {{ + flushPendingAll(); + var card = document.createElement("div"); + card.className = "stream-child"; + var head = document.createElement("div"); + head.className = "stream-child-head"; + var title = document.createElement("strong"); + title.textContent = "Child workbook"; + head.appendChild(title); + var meta = document.createElement("span"); + meta.className = "stream-child-meta"; + var bits = []; + if (ev.round != null) bits.push("round " + ev.round); + if (ev.exit_code != null) bits.push("exit " + ev.exit_code); + meta.textContent = bits.join(" · "); + head.appendChild(meta); + if (ev.workbook) {{ + var a = document.createElement("a"); + a.href = "/file?path=" + encodeURIComponent(ev.workbook); + a.textContent = ev.workbook; + head.appendChild(a); + }} + card.appendChild(head); + var res = formatResult(ev.result); + if (res) {{ + var out = document.createElement("div"); + out.className = "stream-child-body"; + out.textContent = res.length > 8000 ? res.slice(0, 8000) + "…" : res; + card.appendChild(out); + }} + body.appendChild(card); + resetTurnRefs(); + scrollIfPinned(); + }} + function addError(msg) {{ + flushPendingAll(); + var err = document.createElement("div"); + err.className = "stream-err"; + err.textContent = msg || "error"; + body.appendChild(err); + scrollIfPinned(); + }} + function handleEvent(ev) {{ + var t = ev.type || "?"; + if (t === "reasoning") {{ + queueText("reasoning", ev.text || ""); + }} else if (t === "delta") {{ + queueText("answer", ev.text || ""); + }} else if (t === "error") {{ + addError(ev.message || "error"); + if (status) status.textContent = "error"; + }} else if (t === "decision") {{ + addDecision(ev); + }} else if (t === "round") {{ + addChildCard(ev); + }} else if (t === "run_start") {{ + if (status) status.textContent = "running…"; + ensureTurn(); + var mark = document.createElement("div"); + mark.className = "stream-decision"; + var strong = document.createElement("strong"); + strong.textContent = "RUN"; + mark.appendChild(strong); + if (ev.path) {{ + var sp = document.createElement("span"); + sp.textContent = ev.path; + mark.appendChild(sp); + }} + turn.appendChild(mark); + scrollIfPinned(); + }} else if (t === "done") {{ + flushPendingAll(); + if (ev.run_id != null && status) status.textContent = "done"; + var hasAnswer = answerNode && answerNode.data; + if (!hasAnswer && typeof ev.result === "string" && ev.result) {{ + ensureAnswer(); + answerNode.data += ev.result; + scrollIfPinned(); + }} + if (thinkingEl && (answerNode && answerNode.data)) thinkingEl.open = false; + }} + }} + function setRunning(on) {{ + if (runBtn) runBtn.disabled = on; + var formBtn = document.querySelector(".stdin-form button[type='submit']"); + if (formBtn) formBtn.disabled = on; + if (stopBtn) {{ + stopBtn.disabled = !on; + stopBtn.hidden = !on; + }} + }} + async function readSseStream(response) {{ + var ctype = (response.headers.get("content-type") || "").toLowerCase(); + if (ctype.indexOf("application/json") !== -1) {{ + var data = await response.json(); + throw new Error(data.error || data.message || JSON.stringify(data)); + }} + if (!response.ok) {{ + var errText = await response.text(); + throw new Error(errText || ("HTTP " + response.status)); + }} + if (!response.body || !response.body.getReader) {{ + throw new Error("ReadableStream not supported"); + }} + var reader = response.body.getReader(); + var decoder = new TextDecoder(); + var buf = ""; + while (true) {{ + var chunk = await reader.read(); + if (chunk.done) break; + buf += decoder.decode(chunk.value, {{ stream: true }}); + buf = buf.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + var parts = buf.split("\n\n"); + buf = parts.pop() || ""; + for (var i = 0; i < parts.length; i++) {{ + var block = parts[i]; + if (!block || block.charAt(0) === ":") continue; + var lines = block.split("\n"); + var dataLines = []; + for (var j = 0; j < lines.length; j++) {{ + var line = lines[j]; + if (line.indexOf("data:") === 0) {{ + dataLines.push(line.slice(5).replace(/^ /, "")); + }} + }} + if (!dataLines.length) continue; + try {{ + handleEvent(JSON.parse(dataLines.join("\n"))); + }} catch (e) {{ + addError(String(e)); + }} + }} + }} + flushPendingAll(); + }} + function startRun() {{ + if (abortCtrl) abortCtrl.abort(); + abortCtrl = new AbortController(); + setRunning(true); + if (status) status.textContent = "running…"; + clearStream(); + pinned = true; + var stdinEl = document.getElementById("stdin"); + fetch("/api/run", {{ + method: "POST", + headers: {{ + "Content-Type": "application/json", + "Accept": "text/event-stream" + }}, + body: JSON.stringify({{ + path: window.MARQDO_FILE_PATH || "", + stdin: stdinEl ? stdinEl.value : "" + }}), + signal: abortCtrl.signal + }}) + .then(readSseStream) + .then(function () {{ + if (status && status.textContent === "running…") status.textContent = "done"; + }}) + .catch(function (e) {{ + if (e && e.name === "AbortError") {{ + if (status) status.textContent = "stopped"; + return; + }} + addError(String(e && e.message ? e.message : e)); + if (status) status.textContent = "error"; + }}) + .finally(function () {{ + setRunning(false); + abortCtrl = null; + }}); + }} + window.marqdoStreamRun = startRun; + if (stopBtn) {{ + stopBtn.addEventListener("click", function () {{ + if (abortCtrl) abortCtrl.abort(); + }}); + }} + if (runBtn) {{ + runBtn.addEventListener("click", function () {{ startRun(); }}); + }} + var form = document.querySelector(".stdin-form"); + if (form) {{ + form.addEventListener("submit", function (ev) {{ + ev.preventDefault(); + startRun(); + }}); + }} + if (window.MARQDO_AUTO_STREAM) {{ + startRun(); }} }} @@ -1157,7 +1572,14 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM ( "pending", "input", - "Fill preset input below, then click Run with input.".to_string(), + "Fill preset input, then Run with input — output streams in the panel (no page reload)." + .to_string(), + ) + } else if vm.auto_stream { + ( + "pending", + "stream", + "Streaming in the panel below…".to_string(), ) } else if vm.ok { ( @@ -1264,9 +1686,13 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
Stream + idle
-

+  
+

Use Run with input or Run — thinking and answer stream here.

+
+ "# .to_string(), LinkMode::Static { .. } => String::new(), @@ -1276,6 +1702,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM

{title}{status_label}

{rel}

@@ -1298,6 +1725,7 @@ window.MARQDO_FILE_PATH = {path_js}; "#, live = live_flag, path_js = escape_js_string(rel), + auto_stream = if vm.auto_stream { "true" } else { "false" }, title = escape(title), status = status, status_label = status_label, diff --git a/src/view/mod.rs b/src/view/mod.rs index 8dd0685..2539dfa 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -323,13 +323,16 @@ pub(crate) fn build_file_view( }; let effective = effective_stdin(&source, stdin_lines); let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source); + // Live + has `input` + stdin ready → stream via client `/api/run` (no page-blocking capture). + let auto_stream = + live && !input_prompts.is_empty() && !awaiting_input && !stdin_lines.is_empty(); // Same host caps as `marqdo run`. Soft exit + sleep clamp only. let mut opts = RunOptions::default(); opts.stdin_lines = effective.clone(); opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) }; // Optional: sandbox to the whole view tree so sibling folders are reachable. opts.fs_root = Some(root.root.clone()); - let (stdout, stderr, ok, plots) = if awaiting_input { + let (stdout, stderr, ok, plots) = if awaiting_input || auto_stream { (String::new(), String::new(), true, Vec::new()) } else { match run_file_capture(abs, &opts) { @@ -348,7 +351,7 @@ pub(crate) fn build_file_view( } }; // Re-read after run so writeback slots / workbook edits show in Structure. - if !awaiting_input { + if !awaiting_input && !auto_stream { if let Ok(next) = fs::read_to_string(abs) { source = next; if let Ok(module) = crate::parse::parse_source(&source) { @@ -369,6 +372,7 @@ pub(crate) fn build_file_view( preset_stdin: effective.join("\n"), input_prompts, awaiting_input, + auto_stream, plots, }) } @@ -549,26 +553,13 @@ fn api_foreign_run(root: &ViewRoot, mut request: Request) -> Result<()> { } /// SSE: long-lived `text/event-stream` of EventBus JSON maps (`data: …\n\n`). +/// Kept for debugging; the Stream panel uses `POST /api/run` instead (no page-load spinner). 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(()) + respond_sse(request, SseBody::new(rx, false)) } -/// Background `run_file` for the live Stream panel; events go to the EventBus. +/// Run a file and stream EventBus events as SSE on this same response (ChatGPT-style fetch stream). 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)?; @@ -578,25 +569,31 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> { 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( + return respond_json_status( request, + StatusCode(400), 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( + return respond_json_status( request, + StatusCode(400), serde_json::json!({ "ok": false, "error": format!("{e:#}") }).to_string(), ); } }; + // Subscribe before spawn so early tokens are not lost. + let rx = crate::host::event_bus::EventBus::global().subscribe(); + let run_id = next_run_id(); let root_path = root.root.clone(); let rel_clone = rel.clone(); std::thread::spawn(move || { let start = serde_json::json!({ "type": "run_start", + "run_id": run_id, "path": rel_clone, }); crate::host::event_bus::EventBus::global().publish_json(&start.to_string()); @@ -608,17 +605,21 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> { opts.fs_root = Some(root_path); match run_file_capture(&abs, &opts) { Ok(cap) => { + // Keep the terminal frame small — tokens already streamed via bus. + let preview: String = cap.stdout.chars().take(500).collect(); let done = serde_json::json!({ "type": "done", + "run_id": run_id, "path": rel_clone, "ok": true, - "result": cap.stdout, + "result": preview, }); crate::host::event_bus::EventBus::global().publish_json(&done.to_string()); } Err(e) => { let err = serde_json::json!({ "type": "error", + "run_id": run_id, "path": rel_clone, "message": format!("{e:#}"), }); @@ -626,30 +627,80 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> { } } }); - respond_json( - request, - serde_json::json!({ "ok": true, "started": true, "path": rel }).to_string(), - ) + // Only close on this run's terminal frame — ignore nested LLM `done` without run_id. + respond_sse(request, SseBody::for_run(rx, run_id)) +} + +fn next_run_id() -> u64 { + use std::sync::atomic::{AtomicU64, Ordering}; + static SEQ: AtomicU64 = AtomicU64::new(1); + SEQ.fetch_add(1, Ordering::Relaxed) +} + +fn respond_sse(request: Request, body: SseBody) -> Result<()> { + 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, no-transform"[..]) + .map_err(|_| anyhow::anyhow!("header"))?; + let conn = Header::from_bytes(&b"Connection"[..], &b"keep-alive"[..]) + .map_err(|_| anyhow::anyhow!("header"))?; + let xb = Header::from_bytes(&b"X-Accel-Buffering"[..], &b"no"[..]) + .map_err(|_| anyhow::anyhow!("header"))?; + let resp = Response::empty(StatusCode(200)) + .with_header(ct) + .with_header(cc) + .with_header(conn) + .with_header(xb) + .with_data(body, None) + .with_chunked_threshold(0); + request.respond(resp).context("respond sse")?; + Ok(()) } struct SseBody { rx: Receiver, buf: Vec, pos: usize, + /// When set, close after a `done`/`error` frame that carries this `run_id`. + stop_run_id: Option, + closed: bool, } impl SseBody { - fn new(rx: Receiver) -> Self { + fn new(rx: Receiver, _legacy: bool) -> Self { Self { rx, buf: Vec::new(), pos: 0, + stop_run_id: None, + closed: false, } } + + fn for_run(rx: Receiver, run_id: u64) -> Self { + Self { + rx, + buf: Vec::new(), + pos: 0, + stop_run_id: Some(run_id), + closed: false, + } + } + + fn frame_ends_run(json: &str, run_id: u64) -> bool { + let id_marker = format!("\"run_id\":{run_id}"); + if !json.contains(&id_marker) { + return false; + } + json.contains("\"type\":\"done\"") || json.contains("\"type\":\"error\"") + } } impl Read for SseBody { fn read(&mut self, out: &mut [u8]) -> io::Result { + if self.closed && self.pos >= self.buf.len() { + return Ok(0); + } loop { if self.pos < self.buf.len() { let n = (self.buf.len() - self.pos).min(out.len()); @@ -657,16 +708,30 @@ impl Read for SseBody { self.pos += n; return Ok(n); } + if self.closed { + return Ok(0); + } match self.rx.recv_timeout(Duration::from_secs(15)) { Ok(json) => { + let terminal = self + .stop_run_id + .map(|id| Self::frame_ends_run(&json, id)) + .unwrap_or(false); self.buf = format!("data: {json}\n\n").into_bytes(); self.pos = 0; + if terminal { + self.closed = true; + } } Err(RecvTimeoutError::Timeout) => { + // Comment heartbeat keeps intermediaries from buffering forever. self.buf = b": ping\n\n".to_vec(); self.pos = 0; } - Err(RecvTimeoutError::Disconnected) => return Ok(0), + Err(RecvTimeoutError::Disconnected) => { + self.closed = true; + return Ok(0); + } } } } @@ -681,9 +746,15 @@ fn respond_html(request: Request, body: String) -> Result<()> { } fn respond_json(request: Request, body: String) -> Result<()> { + respond_json_status(request, StatusCode(200), body) +} + +fn respond_json_status(request: Request, code: StatusCode, body: String) -> Result<()> { let header = Header::from_bytes(&b"Content-Type"[..], &b"application/json; charset=utf-8"[..]) .map_err(|_| anyhow::anyhow!("header"))?; - let resp = Response::from_string(body).with_header(header); + let resp = Response::from_string(body) + .with_status_code(code) + .with_header(header); request.respond(resp).context("respond")?; Ok(()) } diff --git a/src/view/render.rs b/src/view/render.rs index b926bf8..f5fb780 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -37,6 +37,8 @@ pub struct FileViewModel { pub input_prompts: Vec, /// Live view: program uses `input` but no stdin yet — execution deferred until form submit. pub awaiting_input: bool, + /// Live view: stdin present — skip blocking page-load run; client auto-starts Stream SSE. + pub auto_stream: bool, /// SVG plots from math lib (embedded in Execution). pub plots: Vec, }