2 Commits
Author SHA1 Message Date
WHC 7e1dbd9afa v0.8.4: WebUI sessions, diff, settings, slash commands and extensions
ci / linux (clang) (push) Successful in 6m13s
ci / musl (push) Canceled after 0s
ci / windows-cross (push) Canceled after 0s
ci / linux (gcc) (push) Canceled after 6m33s
Sessions: rename, delete and search; /api/retry regenerates the last
answer, editing a prompt resends from there; /api/export downloads the
transcript as Markdown (cst_session_export_md). Session messages carry
note/tool_result markers, so a reload rebuilds the tool steps with
their arguments, output and exit status; subagent progress is shown.

Diff and settings: /api/diff shows the real diff; /api/settings covers
protocol, max_steps, tool switches and confirm; /api/permissions edits
the rules; sandbox status is reported. Session rename no longer reads
past a short title.

Commands: slash commands with completion in the composer (/model,
/provider, /new, /retry, /undo, /compact, /export, /diff, /init,
/skill and more), a Ctrl+P palette, Shift+Tab cycles the approval
mode, F1 or ? shows the keys. "Thinking expanded" is saved in the
settings (show_thinking), "expand all tool output" in the browser.

Extensions: GET /api/extensions lists MCP servers, plugins, skills,
agent roles and subagent runs; POST /api/extensions/reload and
/api/extensions/trust; a workspace switch reloads them. /api/init and
/api/skill run on the server (cst_init_prompt shared with the TUI).

Errors, statuses and [cst] notes are shown in Chinese with a readable
reason instead of rc=; a failed turn's error survives the reload.

Tests: scripts/e2e_webui_sessions.py, e2e_webui_workspace.py and
e2e_webui_ext.py, run from e2e_webui.sh.
2026-10-10 13:57:17 +08:00
WHC 2d1052fd5f v0.8.3: WebUI models, providers and keys; garbled thinking fixed
ci / linux (clang) (push) Successful in 5m56s
ci / linux (gcc) (push) Successful in 8m38s
ci / musl (push) Successful in 7m22s
ci / windows-cross (push) Successful in 9m21s
Streaming: Chinese reasoning showed up garbled in the WebUI. The agent
loop now feeds visible/thinking text in runs instead of byte by byte,
and the WebUI holds an incomplete UTF-8 tail until the next chunk
(cst_utf8_hold_feed), so every think_delta/assistant_delta is whole.

src/provider_switch.c: model list fetch/cache, key verify-and-save and
provider switching moved out of tui.c and shared by TUI and WebUI.

WebUI API:
- GET /api/providers, GET /api/models[?refresh=1] (401 on a rejected
  key, still listing built-ins), POST /api/provider, POST /api/key
  (key checked against /v1/models, saved to credentials 0600, never
  echoed in replies, events or logs)
- /api/config validates everything before applying, persists model,
  effort and approval (not yolo), warns when effort does not apply;
  plan_mode no longer forces read-only
- state: turn_usage, api_base, key_set/key_from, model_info,
  effort_applies, sees_images, max_steps, tool_profile, perm_timeout;
  permission events carry their timeout

Frontend: searchable model picker with refresh and manual entry,
provider picker and key dialog, effort/vision hints, toasts instead of
silent failures, Chinese error text, real protocol in the settings and
usage panels, approval countdown from the server's timeout.

Tests: utf8 hold unit test, scripts/e2e_webui_settings.py (fake
/v1/models, wrong key, switching, persistence, Chinese thinking) run
from e2e_webui.sh, scripts/tui_keys/provider.py.
2026-10-09 15:54:53 +08:00
26 changed files with 4509 additions and 306 deletions
+1
View File
@@ -111,6 +111,7 @@ set(CST_CORE_SOURCES
src/agent_store.c src/agent_store.c
src/json_baseline.c src/json_baseline.c
src/creds.c src/creds.c
src/provider_switch.c
src/mm_tool.c src/mm_tool.c
src/models.c src/models.c
src/model_registry.c src/model_registry.c
+1 -1
View File
@@ -91,7 +91,7 @@ CORE_SRC = \
src/agent_loop.c \ src/agent_loop.c \
src/agent_store.c \ src/agent_store.c \
src/json_baseline.c \ src/json_baseline.c \
src/creds.c \ src/creds.c src/provider_switch.c \
src/mm_tool.c \ src/mm_tool.c \
src/models.c src/model_registry.c \ src/models.c src/model_registry.c \
src/metrics.c \ src/metrics.c \
+88 -11
View File
@@ -88,10 +88,10 @@ GET /api/events?since=<seq> → text/event-stream (chunked)
| `assistant_html` | `text` | **已渲染且已消毒的 HTML 片段**,按顺序追加 | | `assistant_html` | `text` | **已渲染且已消毒的 HTML 片段**,按顺序追加 |
| `assistant_delta` | `text` | 原始文本增量(逐字节真相,做复制/导出时用) | | `assistant_delta` | `text` | 原始文本增量(逐字节真相,做复制/导出时用) |
| `think_delta` | `text` | 推理过程增量(Thought) | | `think_delta` | `text` | 推理过程增量(Thought) |
| `tool` | `id`,`name`,`args`,`phase`,`detail` | `phase` = `open`/`ready`/`run`/`done` | | `tool` | `id`,`name`,`args`,`phase`,`detail` | `phase` = `open`/`ready`/`run`/`progress`/`done`;`progress` 是子代理的最近几步(`detail` 形如 `explore · grep foo · read_file x`),可以出现多次 |
| `tool_result` | `id`,`name`,`out`,`exit`,`bytes`,`truncated` | 完整输出被截到 32 KiB,`truncated=true` | | `tool_result` | `id`,`name`,`out`,`exit`,`bytes`,`truncated` | 完整输出被截到 32 KiB,`truncated=true` |
| `todo` | `text` | `todo_write` 替换后的清单(一行一项) | | `todo` | `text` | `todo_write` 替换后的清单(一行一项) |
| `permission` | `id`,`tool`,`detail`,`preview`,`sandbox` | 需要回答(见下) | | `permission` | `id`,`tool`,`detail`,`preview`,`sandbox`,`timeout` | 需要回答(见下);`timeout` 秒后按拒绝处理 |
| `permission_done` | `id`,`answer` | 问题已结束(超时/取消也会发) | | `permission_done` | `id`,`answer` | 问题已结束(超时/取消也会发) |
| `ask_user` | `id`,`question`,`options[]` | 需要回答 | | `ask_user` | `id`,`question`,`options[]` | 需要回答 |
| `session` | `id` | 切换/新建了会话,客户端应重新拉 `/api/session` | | `session` | `id` | 切换/新建了会话,客户端应重新拉 `/api/session` |
@@ -100,24 +100,50 @@ GET /api/events?since=<seq> → text/event-stream (chunked)
`state` 字段:`workspace` `session` `provider` `model` `effort` `approval` `state` 字段:`workspace` `session` `provider` `model` `effort` `approval`
(`ask|auto|yolo`) `plan_mode` `protocol_tools` `status_busy` `todo` (`ask|auto|yolo`) `plan_mode` `protocol_tools` `status_busy` `todo`
`context_tokens` `undo_available` `pending_images[]` `usage{requests,prompt_tokens, `context_tokens` `undo_available` `pending_images[]` `usage{requests,prompt_tokens,
completion_tokens,cached_tokens,cache_miss_tokens,cost,priced,currency}`。 completion_tokens,cached_tokens,cache_miss_tokens,cost,priced,currency}`
`turn_usage{…}`(上一轮,字段同 `usage`)`api_base` `key_set` `key_from`
(`saved` / 环境变量名 / `session` / 空,**从不含 key 本身**)
`model_info{label,context,vision,reasoning,source,price?}` `effort_applies`
`sees_images`(1 / 0 / -1 未知)`max_steps` `tool_profile` `perm_timeout`
`show_thinking`(思考过程默认展开,存在 `settings.json`,和 TUI 的 `/thinking` 是同一个开关)。
`cached_tokens` / `cache_miss_tokens` 来自上游的 prompt cache 统计,前端用它算命中率。 `cached_tokens` / `cache_miss_tokens` 来自上游的 prompt cache 统计,前端用它算命中率。
`think_delta` / `assistant_delta` 的 `text` 总是完整的 UTF-8:上游在多字节字符中间
断开时,残缺的尾巴留到下一块再发。
### 请求 ### 请求
| 方法 | 路径 | 说明 | | 方法 | 路径 | 说明 |
|---|---|---| |---|---|---|
| GET | `/api/state` | 上面那份快照 | | GET | `/api/state` | 上面那份快照 |
| GET | `/api/session?from=N` | 会话消息(`{messages:[…]}`,形状与 `.agent/sessions/*.jsonl` 一致;assistant 消息额外带 `html`) | | GET | `/api/session?from=N` | 会话消息(`{messages:[…]}`,形状与 `.agent/sessions/*.jsonl` 一致,另加的字段见下) |
| GET | `/api/sessions` | `{current, sessions:[{id,title,messages,mtime}]}` | | GET | `/api/sessions` | `{current, sessions:[{id,title,messages,mtime}]}` |
| POST | `/api/sessions/new` | `{}` → `{id}` | | POST | `/api/sessions/new` | `{}` → `{id}` |
| POST | `/api/sessions/switch` | `{"id":"…"}` | | POST | `/api/sessions/switch` | `{"id":"…"}` |
| POST | `/api/workspace` | `{"path":"/abs/dir"}` —— 换工作目录(权限规则/埋点/AGENTS.md 跟着换),并**在新目录里开一个新会话**(会话是按目录存的);返回 `{id}`,坏路径 → 400 | | POST | `/api/sessions/rename` | `{"id":"…"?,"title":"…"}`(不带 `id` = 当前会话);标题按字符截到 120 字节,空串 = 恢复默认(第一句提问);没这个会话 → 404 |
| POST | `/api/sessions/delete` | `{"id":"…"}` → `{ok,current}`;删的是当前会话时先开一个新会话(并发 `session` 事件);没这个会话 → 404 |
| POST | `/api/retry` | `{}` = 重新生成最后一轮;`{"text":"…"}` = 把最后一句提问换成新文字再跑(编辑重发)。先把最后一轮从会话里退掉,再开新一轮 → 202 `{ok,text}`;没有可重来的轮次 / 轮次在跑 → 409;空串或非字符串 → 400 |
| GET | `/api/export` | 当前会话的 Markdown(`text/markdown`,与 TUI `/export` 同一格式) |
| GET | `/api/diff[?path=p]` | 工作区的真实 diff:`{git,path,files:[{status,path}],diff,truncated}`。`files` 来自 `git status --short`(含未跟踪),`diff` 是 `git diff`(未暂存部分,限 512 KiB);不是 git 仓库 / 没装 git → `git:false`;10 s 超时 |
| GET | `/api/settings` | 运行设置:`protocol`,`protocols[]`,`max_steps`,`tool_profile`,`profiles[]`,`confirm{shell,write,net}`,`approval`,`tools[{name,perm,on,desc,…}]`,`sandbox{kind,active,labels?}` |
| POST | `/api/settings` | `{protocol?,max_steps?,tool_profile?,tools?:{名字:bool},confirm?:{shell?,write?,net?}}`;整体校验后才生效(任何一项不对 → 400,什么都不改),成功后发 `state` |
| GET | `/api/permissions` | 已保存的"总是允许"规则:`{text,tools[],shell_prefixes[]}`(来自 `<workspace>/.agent/permissions.json`) |
| DELETE | `/api/permissions` | 清空这些规则 |
| POST | `/api/init` | `{}` → 202 `{ok,text}`:开一轮,让 agent 分析仓库写 `AGENTS.md`(与 TUI `/init` 同一段提示词) |
| POST | `/api/skill` | `{"name":"…","task":"…"?}` → 202 `{ok,text}`:把 skill 正文内联进这条消息再开一轮(同 TUI `/skill`);没有这个 skill → 404;缺 `name` / 超过 63 字节 / `task` 不是字符串 → 400 |
| GET | `/api/extensions` | `{enabled,trusted,report,task_tool,mcp:[{name,source,command,state,tools,error}],plugins:[{name,source,desc,tools,mcp,skills,error}],skills:[{name,source,desc}],roles:[{name,source,desc,model,read_only}],runs:[{file,role,desc,status,steps,tools,ms}]}`;`state` = `starting/ready/failed/exited/off`,`runs` 是当前会话的子代理运行 |
| POST | `/api/extensions/reload` | 停掉 MCP 服务器和插件,重新读取它们和 skills → `{ok,trusted,report}` |
| POST | `/api/extensions/trust` | `{"on":true\|false}`:信任(或取消)当前工作区——决定它的 `.agent/plugins`、`.agent/mcp.json` 是否加载;写进 `settings.json` 后重新加载,回复同上 |
| POST | `/api/workspace` | `{"path":"/abs/dir"}` —— 换工作目录(权限规则/埋点/AGENTS.md 跟着换,扩展按新目录重新加载),并**在新目录里开一个新会话**(会话是按目录存的);返回 `{id}`,坏路径 → 400 |
| POST | `/api/turn` | `{"text":"…"}` → 202 `{ok:true}`;已有轮次在跑时 **409** | | POST | `/api/turn` | `{"text":"…"}` → 202 `{ok:true}`;已有轮次在跑时 **409** |
| POST | `/api/cancel` | `{}` —— 取消当前轮(不会杀进程);挂起的权限问题按拒绝、提问按忽略处理 | | POST | `/api/cancel` | `{}` —— 取消当前轮(不会杀进程);挂起的权限问题按拒绝、提问按忽略处理 |
| POST | `/api/permission` | `{"id":N,"answer":0\|1\|2\|3}` → deny / once / always-tool / always-prefix | | POST | `/api/permission` | `{"id":N,"answer":0\|1\|2\|3}` → deny / once / always-tool / always-prefix |
| POST | `/api/ask_user` | `{"id":N,"text":"…"}` 或 `{"id":N,"dismiss":true}` | | POST | `/api/ask_user` | `{"id":N,"text":"…"}` 或 `{"id":N,"dismiss":true}` |
| POST | `/api/config` | `{model?,provider?,effort?,approval?,plan_mode?}` | | POST | `/api/config` | `{model?,effort?,approval?,plan_mode?,show_thinking?}`;先整体校验再生效,model/effort/approval(`yolo` 除外)写进 `settings.json`;当前模型不吃 effort 时回 `warning`;带 `provider` → 400(改用 `/api/provider`) |
| GET | `/api/providers` | `{current, providers:[{name,api_base,model,has_key,key_from,key_env,source,current}]}` |
| GET | `/api/models[?refresh=1]` | 当前提供商的模型:`{provider,current,api_base,key_set,api_count,models:[{id,api,label,context,vision,reasoning,source,price?}]}`;先用缓存,过期/缺失/`refresh=1` 时向 `/v1/models` 拉;key 被拒 → 401(仍带内置模型和 `auth:true`),其它失败放在 `api_error` |
| POST | `/api/provider` | `{"name":"…","key":"…"?}`:切换提供商。缺 key → 400 `{need_key:true}`;key 被拒 → 401;没这个提供商 → 404;成功 → `{ok,provider,model,warning?}`,key 验证后存进 `credentials`(0600) |
| POST | `/api/key` | `{"key":"…"}`:换当前提供商的 key,验证与回复同上 |
| POST | `/api/undo` | 回滚最近一轮的文件改动,回 200 + 报告文本 | | POST | `/api/undo` | 回滚最近一轮的文件改动,回 200 + 报告文本 |
| POST | `/api/compact` | 手动压缩上下文 | | POST | `/api/compact` | 手动压缩上下文 |
| POST | `/api/attach?name=x.png` | 请求体是图片原始字节(≤32 MiB),进入"待发送"列表 | | POST | `/api/attach?name=x.png` | 请求体是图片原始字节(≤32 MiB),进入"待发送"列表 |
@@ -126,9 +152,28 @@ completion_tokens,cached_tokens,cache_miss_tokens,cost,priced,currency}`。
| POST | `/api/quit` | 关闭进程 | | POST | `/api/quit` | 关闭进程 |
未命中路由 → `404 {"error":"not found"}`;需要 token 而没给 → `401`。 未命中路由 → `404 {"error":"not found"}`;需要 token 而没给 → `401`。
轮次运行中(或另一个修改正在进行)时,`sessions/new`、`sessions/switch`、`workspace`、 轮次运行中(或另一个修改正在进行)时,`sessions/new`、`sessions/switch`、`sessions/delete`、
`undo`、`compact`、`attach`(上传/清空)以及改 `model/provider/effort` 的 `config` `workspace`、`undo`、`compact`、`attach`(上传/清空)、`provider`、`key`、`retry`、`diff`、
一律 **409**;`approval`/`plan_mode` 可以中途改。 `POST /api/settings`、`DELETE /api/permissions`、`init`、`skill`、`extensions/reload`、
`extensions/trust` 以及改 `model/effort` 的 `config` 一律 **409**;
`approval`/`plan_mode`/`show_thinking` 可以中途改,`sessions/rename`、`export` 与
`GET /api/extensions` 在轮次进行中也能用。
`/api/session` 的每条消息在会话文件的字段之外还带:
| 字段 | 出现在 | 说明 |
|---|---|---|
| `html` | assistant | 已消毒的 Markdown 渲染结果(文本协议时只渲染说明文字,不含调用帧) |
| `text` | 文本协议的 assistant | 去掉调用帧后的说明文字(`content` 仍是原文) |
| `calls` | 带工具调用的 assistant | `[{id,name,args}]`:原生协议来自 `tool_calls`,文本协议从 `content` 解析 |
| `tool_result` | 工具结果 | `true`;原生协议 role 是 `tool`,文本协议 role 是 `user`(凭 `tool_call_id` 区分) |
| `out`,`exit`,`truncated` | 工具结果 | 去掉 `[tool …]` / `result … end` 外框后的输出(截到 32 KiB,按字符边界)与退出码 |
| `note` | 引擎插入的提示 | `true`;如中途切换计划模式时的 `[cst] …` 说明,不是用户说的话 |
客户端据此在刷新后重建"本轮工具调用"列表:`calls` 建行,`tool_call_id` 相同的结果填进去。
key 只出现在请求体里:回复、事件、日志都不会带它。`/api/provider` 与 `/api/key`
跟其它 `/api/*` 一样受 loopback 同源检查或 token 保护。
### 客户端接入示例(10 行) ### 客户端接入示例(10 行)
@@ -164,6 +209,31 @@ Markdown 在**服务端**渲染(复用 TUI 用的 sashidown 流式 API),
对话开始后自动隐去;右栏只给三件事——任务清单、本轮文件改动行数(`+N −M`)、上下文 对话开始后自动隐去;右栏只给三件事——任务清单、本轮文件改动行数(`+N −M`)、上下文
占用与 prompt cache 命中率。布局类在页面脚本之前就写进 `<body>`,避免首帧闪一下再收起。 占用与 prompt cache 命中率。布局类在页面脚本之前就写进 `<body>`,避免首帧闪一下再收起。
### 命令与快捷键
输入框以 `/` 开头时是命令,在页面里执行,不发给模型:打 `/` 弹出列表(↑↓ 选,Tab 补全,
Enter 执行),`/model`、`/effort`、`/approval`、`/provider`、`/skill`、`/thinking`、`/details`
还会补全参数。`/usr/bin 是什么` 这种第一个词里带 `/` 的照常发送;未知命令留在输入框里并提示,
开头加个空格即可当普通消息发出。
| 命令 | 作用 |
|---|---|
| `/new` `/sessions` `/rename [标题]` | 新建 / 会话列表 / 重命名 |
| `/retry` `/edit` `/stop` `/undo` `/compact` | 重新生成 / 编辑重发 / 停止 / 撤销写入 / 压缩上下文 |
| `/export` `/copy` `/diff [文件]` | 导出 Markdown / 复制最后一条回答 / 工作区 diff |
| `/model [id]` `/effort [级别]` `/provider [名字]` `/key` | 模型、推理强度、提供商、API key |
| `/approval [ask\|auto\|yolo]` `/plan` `/build` | 审批权限、计划/构建模式 |
| `/settings`(`/protocol` `/tools` `/max-steps` `/permissions`) | 运行设置 |
| `/init` `/skill 名字 [任务]` `/skills` `/extensions`(`/mcp` `/plugins` `/agents`) | 写 AGENTS.md、用 skill、扩展状态 |
| `/thinking [on\|off]` `/details [on\|off]` | 思考过程默认展开(存 `settings.json`)、工具输出全部展开(存浏览器) |
| `/theme` `/palette` `/help` | 主题、命令面板、帮助 |
快捷键:Ctrl+P 命令面板,Ctrl+K 会话列表,Shift+Tab 循环审批(每次询问 → 自动 → 完全放行),
F1 或 `?` 帮助,Esc 关闭弹窗 / 取消编辑 / 停止当前一轮,Ctrl+B / Ctrl+J 收起左栏 / 右栏。
引擎的英文状态、错误和会话里的 `[cst]` 提示在页面上换成中文;一轮失败时(`turn_end.rc≠0`)
显示可读的原因(比如"API key 无效或已过期(HTTP 401)"、"用满了 30 步上限"),不再是 `rc=-1`。
TUI 里打 `/web` 会另起一个 WebUI 进程(`--web --workspace <当前目录> --new`), TUI 里打 `/web` 会另起一个 WebUI 进程(`--web --workspace <当前目录> --new`),
日志在 `<workspace>/.agent/webui.log`:TUI 不能被 `cst_webui_run()` 的阻塞循环占住, 日志在 `<workspace>/.agent/webui.log`:TUI 不能被 `cst_webui_run()` 的阻塞循环占住,
而且两个进程同时写一个会话文件会把它写坏,所以子进程总是开新会话。 而且两个进程同时写一个会话文件会把它写坏,所以子进程总是开新会话。
@@ -176,7 +246,12 @@ TUI 里打 `/web` 会另起一个 WebUI 进程(`--web --workspace <当前目
```bash ```bash
make check # 含 tests/test_webui(HTTP/SSE/鉴权/消毒) make check # 含 tests/test_webui(HTTP/SSE/鉴权/消毒)
sh scripts/e2e_webui.sh # 用录制流跑完整轮次 + 权限往返,不需要 API key sh scripts/e2e_webui.sh # 用录制流跑完整轮次 + 权限往返,不需要 API key
sh scripts/e2e_webui.sh tests/fixtures/sse/deepseek-ctl ctl # (含 e2e_webui_settings.py:假 /v1/models、换提供商/key、中文思考流;
# e2e_webui_sessions.py:重新生成/编辑重发/导出/重命名/删除/历史字段;
# e2e_webui_workspace.py:diff、运行设置、权限规则;
# e2e_webui_ext.py:/init、/skill、扩展、信任、思考开关)
sh scripts/e2e_webui.sh tests/fixtures/sse/deepseek-ctl-heredoc ctl-heredoc
# (deepseek-ctl 录的是一次契约错误连发的失败运行,不能拿来跑这个)
``` ```
手工验收清单(浏览器): 手工验收清单(浏览器):
@@ -184,7 +259,9 @@ sh scripts/e2e_webui.sh tests/fixtures/sse/deepseek-ctl ctl
1. 打开首页 → 顶部显示 workspace/模型/审批模式,右下状态"就绪"。 1. 打开首页 → 顶部显示 workspace/模型/审批模式,右下状态"就绪"。
2. 输入一句话 → 助手气泡逐字出现;工具卡片自动展开、结束后带 `exit=` 标记。 2. 输入一句话 → 助手气泡逐字出现;工具卡片自动展开、结束后带 `exit=` 标记。
3. 切到 `ask` 审批 → 写文件时弹窗;点"允许一次"后继续,点"拒绝"则该工具返回失败但对话继续。 3. 切到 `ask` 审批 → 写文件时弹窗;点"允许一次"后继续,点"拒绝"则该工具返回失败但对话继续。
4. `会话` 按钮:新建/切换后历史正确重建(刷新页面也一样)。 4. `会话` 按钮:新建/切换后历史正确重建(刷新页面也一样):工具调用折叠成"本轮工具调用",
点开能看到参数和输出;搜索、重命名、删除可用。
4a. 最后一句提问上有"编辑重发",最后一个回答上有"重新生成";右栏文件行点开是真实 diff。
5. 拖入一张图片 → 底部出现待发送提示,发送后历史里能看到图。 5. 拖入一张图片 → 底部出现待发送提示,发送后历史里能看到图。
6. 关掉标签页再打开 → 事件流自动续传,不丢已完成的消息。 6. 关掉标签页再打开 → 事件流自动续传,不丢已完成的消息。
+6
View File
@@ -130,6 +130,12 @@ const cst_message_t *cst_session_get(const cst_session_t *s, int i);
const char *cst_session_path(const cst_session_t *s); const char *cst_session_path(const cst_session_t *s);
int cst_session_clear(cst_session_t *s, int keep_system); int cst_session_clear(cst_session_t *s, int keep_system);
int cst_session_rewrite(cst_session_t *s, const cst_message_t *msgs, int n); int cst_session_rewrite(cst_session_t *s, const cst_message_t *msgs, int n);
/* Tool output: role=tool, or a text-protocol user message answering a call. */
int cst_message_is_tool_result(const cst_message_t *m);
/* The transcript as Markdown, malloc'd (NULL on OOM). Tool output and call
* arguments are cut at 4000 bytes. Takes the session lock. */
char *cst_session_export_md(cst_session_t *s, const char *title,
const char *sid, const char *model);
/* Readers on another thread must hold the lock while using pointers returned /* Readers on another thread must hold the lock while using pointers returned
* by cst_session_get (append may reallocate). Append locks internally. */ * by cst_session_get (append may reallocate). Append locks internally. */
void cst_session_lock(cst_session_t *s); void cst_session_lock(cst_session_t *s);
+79
View File
@@ -0,0 +1,79 @@
#ifndef CST_PROVIDER_SWITCH_H
#define CST_PROVIDER_SWITCH_H
/* Model lists, API keys and provider switches, shared by the TUI and the
* WebUI so both front ends validate and persist the same way.
*
* A key is checked with GET /models: a 401/403 (CST_MODELS_AUTH) rejects
* it, any other failure (offline, no /models route) lets it through
* unverified. A key that passes is saved to <config>/credentials. Keys are
* never copied into err. */
#include "cst_agent.h"
#include "cst_models.h"
#ifdef __cplusplus
extern "C" {
#endif
#define CST_PS_MAX_MODELS 512
#define CST_PS_UNKNOWN (-1) /* no such provider */
#define CST_PS_NEED_KEY (-10) /* no key given, none saved or in the env */
/* Non-negative results are flags: */
#define CST_PS_UNVERIFIED 1 /* /models failed for another reason; err says */
#define CST_PS_UNSAVED 2 /* the credentials file could not be written */
typedef struct {
char id[128];
int api; /* listed by the provider's /models (else built-in only) */
cst_model_info_t info;
} cst_ps_model_t;
/* GET /models; a good answer refreshes models-cache/<provider>.json. The
* count, CST_MODELS_AUTH, or another negative value with err set. */
int cst_ps_fetch(const char *provider, const char *api_base, const char *key,
char ids[][128], int max, char *err, size_t err_sz);
/* The cached list: count, or -1; *fresh when younger than the TTL. */
int cst_ps_cached(const char *provider, char ids[][128], int max, int *fresh);
/* Base URL for provider: cfg's own when it is the current provider (it may
* be overridden), else the preset's; "" when unknown. */
const char *cst_ps_base(const cst_agent_config_t *cfg, const char *provider);
/* The model picker list for cfg's provider: the API's ids (the cache while
* it is fresh, else a fetch; refresh always fetches) followed by the
* built-in names it did not list. *api_rc gets the fetch result (count,
* CST_MODELS_AUTH, -1 with err) or the cached count. Returns the count. */
int cst_ps_models(const cst_agent_config_t *cfg, int refresh,
cst_ps_model_t *out, int max, int *api_rc, char *err,
size_t err_sz);
/* Checks key against /models and saves it: CST_MODELS_AUTH (err set), or
* the CST_PS_* flags. When ids is given it gets the fetched list and *nids
* the raw fetch result. */
int cst_ps_verify_save(const char *provider, const char *api_base,
const char *key, char ids[][128], int max, int *nids,
char *err, size_t err_sz);
/* Point cfg at provider p with key: base URL, the remembered model (else
* the preset's), settings saved. */
void cst_ps_apply_provider(cst_agent_config_t *cfg, const cst_provider_t *p,
const char *key);
/* The whole switch without a prompt: key NULL/"" uses the saved or env
* key (else CST_PS_NEED_KEY); a given key is verified and saved first. A
* preset with no model takes the first one the API lists. The CST_PS_*
* flags, or CST_PS_UNKNOWN / CST_PS_NEED_KEY / CST_MODELS_AUTH. */
int cst_ps_switch_provider(cst_agent_config_t *cfg, const char *name,
const char *key, char *err, size_t err_sz);
/* Replace the current provider's key: verified, saved, put in cfg. Same
* results as cst_ps_verify_save. */
int cst_ps_set_key(cst_agent_config_t *cfg, const char *key, char *err,
size_t err_sz);
#ifdef __cplusplus
}
#endif
#endif
+2
View File
@@ -45,6 +45,8 @@ char *cst_skill_read(const char *workspace, const char *name,
* task. NULL when the skill does not exist. malloc'd. */ * task. NULL when the skill does not exist. malloc'd. */
char *cst_skill_prompt(const char *workspace, const char *name, char *cst_skill_prompt(const char *workspace, const char *name,
const char *task); const char *task);
/* User message for `/init`: have the agent write AGENTS.md. */
const char *cst_init_prompt(void);
/* Register the `skill` tool (idempotent). */ /* Register the `skill` tool (idempotent). */
int cst_skills_register_tool(void); int cst_skills_register_tool(void);
+11
View File
@@ -27,6 +27,17 @@ size_t cst_utf8_floor(const char *s, size_t n);
char *cst_utf8_sanitize(const char *s, size_t n, size_t *out_len); char *cst_utf8_sanitize(const char *s, size_t n, size_t *out_len);
int cst_utf8_valid(const char *s, size_t n); int cst_utf8_valid(const char *s, size_t n);
/* Re-chunks a byte stream so no piece ends inside a UTF-8 sequence: the
* incomplete tail (at most 3 bytes) waits in the hold for the next feed. */
typedef struct {
char b[4];
size_t n;
} cst_utf8_hold_t;
/* Returns the complete prefix of hold+s[0..n) (malloc'd, NUL-terminated,
* *out_len may be 0), or NULL on OOM. */
char *cst_utf8_hold_feed(cst_utf8_hold_t *h, const char *s, size_t n,
size_t *out_len);
/* Text files may start with a UTF-8 BOM (Windows editors): its length (0/3), /* Text files may start with a UTF-8 BOM (Windows editors): its length (0/3),
* and an in-place strip of the NUL-terminated s (*len updated when given). */ * and an in-place strip of the NUL-terminated s (*len updated when given). */
size_t cst_bom_len(const char *s, size_t n); size_t cst_bom_len(const char *s, size_t n);
+1 -1
View File
@@ -3,7 +3,7 @@
#define CST_VERSION_MAJOR 0 #define CST_VERSION_MAJOR 0
#define CST_VERSION_MINOR 8 #define CST_VERSION_MINOR 8
#define CST_VERSION_PATCH 2 #define CST_VERSION_PATCH 4
#define CST_VERSION_STR_(x) #x #define CST_VERSION_STR_(x) #x
#define CST_VERSION_STR(x) CST_VERSION_STR_(x) #define CST_VERSION_STR(x) CST_VERSION_STR_(x)
+12
View File
@@ -282,6 +282,18 @@ if command -v python3 > /dev/null; then
echo "== HTTP hardening" echo "== HTTP hardening"
CST_AGENT="$BIN" python3 "$ROOT/scripts/e2e_webui_http.py" > "$WORK/http.txt" 2>&1 || CST_AGENT="$BIN" python3 "$ROOT/scripts/e2e_webui_http.py" > "$WORK/http.txt" 2>&1 ||
{ cat "$WORK/http.txt"; fail "the HTTP hardening checks"; } { cat "$WORK/http.txt"; fail "the HTTP hardening checks"; }
echo "== settings and streaming"
CST_AGENT="$BIN" python3 "$ROOT/scripts/e2e_webui_settings.py" > "$WORK/settings.txt" 2>&1 ||
{ cat "$WORK/settings.txt"; fail "the settings checks"; }
echo "== sessions, retry and export"
CST_AGENT="$BIN" python3 "$ROOT/scripts/e2e_webui_sessions.py" > "$WORK/sessions.txt" 2>&1 ||
{ cat "$WORK/sessions.txt"; fail "the session checks"; }
echo "== diff, run settings and permission rules"
CST_AGENT="$BIN" python3 "$ROOT/scripts/e2e_webui_workspace.py" > "$WORK/workspace.txt" 2>&1 ||
{ cat "$WORK/workspace.txt"; fail "the workspace checks"; }
echo "== /init, /skill, extensions and the thinking switch"
CST_AGENT="$BIN" python3 "$ROOT/scripts/e2e_webui_ext.py" > "$WORK/ext.txt" 2>&1 ||
{ cat "$WORK/ext.txt"; fail "the extension checks"; }
fi fi
echo "== OK: (events: $(grep -c '^event: ' "$EVENTS"))" echo "== OK: (events: $(grep -c '^event: ' "$EVENTS"))"
+227
View File
@@ -0,0 +1,227 @@
"""WebUI /init, /skill, extensions and the thinking switch against a fake API.
python3 scripts/e2e_webui_ext.py (CST_AGENT= picks the binary)
Checks: show_thinking is validated, lands in the state and in settings.json;
/api/skill inlines the skill and 404s an unknown one; /api/init sends the
AGENTS.md prompt; /api/extensions lists skills and the built-in roles;
trust and reload work and write settings.json; the changing calls are a 409
while a turn runs, the listing is not. HOME points at a temp dir.
"""
import json, os, shutil, subprocess, sys, tempfile, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
BIN = os.environ.get("CST_AGENT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "cst-agent"))
SEEN = [] # the full last user message of every request
class Api(BaseHTTPRequestHandler):
"""Answers "好的"; a prompt with "slow" takes 2 s."""
def log_message(self, *a):
pass
def do_GET(self):
body = json.dumps({"data": [{"id": "deepseek-flash"}]}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
users = [m.get("content") for m in req.get("messages", []) if m.get("role") == "user"]
last = users[-1] if users and isinstance(users[-1], str) else ""
SEEN.append(last)
if "slow" in last:
time.sleep(2)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
for o in ({"delta": {"role": "assistant", "content": "好的"}},
{"delta": {}, "finish_reason": "stop"}):
chunk = {"id": "x", "object": "chat.completion.chunk", "model": "deepseek-flash",
"choices": [dict(index=0, **o)]}
self.wfile.write(b"data: " + json.dumps(chunk, ensure_ascii=False).encode() + b"\n\n")
self.wfile.flush()
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
fails = 0
def check(ok, msg):
global fails
print(("PASS " if ok else "FAIL ") + msg)
fails += 0 if ok else 1
def wait(fn, t=15):
end = time.time() + t
while time.time() < end:
v = fn()
if v:
return v
time.sleep(0.1)
return None
def call(base, path, obj=None, method=None):
data = None if obj is None else json.dumps(obj).encode()
req = urllib.request.Request(base + path, data=data, method=method or ("POST" if data else "GET"),
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, json.loads(r.read() or b"{}")
except urllib.error.HTTPError as e:
try:
return e.code, json.loads(e.read() or b"{}")
except ValueError:
return e.code, {}
def skill(ws, name, desc, body):
d = os.path.join(ws, ".agent", "skills", name)
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "SKILL.md"), "w", encoding="utf-8") as f:
f.write("---\nname: %s\ndescription: %s\n---\n\n%s\n" % (name, desc, body))
api = ThreadingHTTPServer(("127.0.0.1", 0), Api)
threading.Thread(target=api.serve_forever, daemon=True).start()
ws = tempfile.mkdtemp(prefix="cst-ext-")
home = tempfile.mkdtemp(prefix="cst-home-")
skill(ws, "demo", "演示用的 skill", "DEMO-INSTRUCTIONS: 先说你好。")
env = dict(os.environ, HOME=home, XDG_CONFIG_HOME=home + "/.config",
XDG_DATA_HOME=home + "/.local/share", XDG_CACHE_HOME=home + "/.cache")
for k in ("DEEPSEEK_API_KEY", "OPENAI_API_KEY", "CST_API_KEY"):
env.pop(k, None)
log = open(ws + "/server.log", "w+")
proc = subprocess.Popen([BIN, "--web", "--web-port", "0", "--workspace", ws, "--new", "--api-key", "sk-x",
"--provider", "deepseek", "--model", "deepseek-flash",
"--api-base", "http://127.0.0.1:%d/v1" % api.server_address[1],
"--protocol", "native-eos", "--approval", "auto"],
stdout=log, stderr=subprocess.STDOUT, env=env)
def port():
log.seek(0)
for l in log.read().splitlines():
if l.startswith("webui: http://127.0.0.1:"):
return l.split(":")[3].split("/")[0]
def settings():
try:
with open(home + "/.config/cst-agent/settings.json", encoding="utf-8") as f:
return json.load(f)
except OSError:
return {}
def busy(base):
return call(base, "/api/state")[1].get("status_busy")
def turn(base, path, body):
code, d = call(base, path, body)
if code == 202:
time.sleep(0.3)
wait(lambda: not busy(base), 20)
return code, d
try:
base = "http://127.0.0.1:%s" % wait(port)
# 1. the thinking switch
st = call(base, "/api/state")[1]
check(st.get("show_thinking") is False, "show_thinking starts off")
check(call(base, "/api/config", {"show_thinking": "yes"})[0] == 400, "show_thinking must be a bool")
code, _ = call(base, "/api/config", {"show_thinking": True})
check(code == 200 and call(base, "/api/state")[1].get("show_thinking") is True, "show_thinking on")
check(settings().get("show_thinking") is True, "show_thinking is saved in settings.json")
call(base, "/api/config", {"show_thinking": False})
check(settings() and not settings().get("show_thinking"), "and cleared again (%s)" % settings())
# 2. the extensions listing
code, ex = call(base, "/api/extensions")
check(code == 200 and ex.get("enabled") is True and ex.get("trusted") is False,
"extensions: enabled, not trusted (%s)" % code)
names = [s["name"] for s in ex.get("skills", [])]
check(names == ["demo"] and ex["skills"][0].get("desc") == "演示用的 skill"
and ex["skills"][0].get("source") == "workspace", "the workspace skill is listed (%s)" % ex.get("skills"))
roles = [r["name"] for r in ex.get("roles", [])]
check("explore" in roles and all(r.get("source") for r in ex["roles"]), "built-in roles are listed (%s)" % roles)
check(ex.get("mcp") == [] and ex.get("plugins") == [] and ex.get("runs") == [], "no MCP, plugins or runs")
check(ex.get("task_tool") is True and "1 skill" in ex.get("report", ""), "task tool on, report %r" % ex.get("report"))
# 3. /skill
code, d = turn(base, "/api/skill", {"name": "demo", "task": "做点事"})
check(code == 202 and "DEMO-INSTRUCTIONS" in d.get("text", "") and d["text"].endswith("做点事"),
"skill turn accepted (%s)" % code)
check(SEEN and "DEMO-INSTRUCTIONS" in SEEN[-1] and "做点事" in SEEN[-1], "the model saw the skill and the task")
code, d = turn(base, "/api/skill", {"name": "demo"})
check(code == 202 and SEEN[-1].endswith("Apply this skill now."), "a skill without a task")
check(call(base, "/api/skill", {"name": "nope"})[0] == 404, "unknown skill: 404")
check(call(base, "/api/skill", {"name": "../demo"})[0] == 404, "skill ../demo: 404")
check(call(base, "/api/skill", {})[0] == 400, "skill without a name: 400")
check(call(base, "/api/skill", {"name": "x" * 100})[0] == 400, "a long skill name: 400")
check(call(base, "/api/skill", {"name": "demo", "task": 5})[0] == 400, "a non-string task: 400")
# 4. /init
code, d = turn(base, "/api/init", {})
check(code == 202 and "AGENTS.md" in d.get("text", ""), "init accepted (%s)" % code)
check("AGENTS.md" in SEEN[-1], "the model saw the AGENTS.md prompt")
# 5. trust and reload
code, d = call(base, "/api/extensions/trust", {"on": True})
check(code == 200 and d.get("trusted") is True, "trust the workspace (%s %s)" % (code, d))
tw = settings().get("trusted_workspaces", [])
check(any(os.path.realpath(ws) == os.path.realpath(p) for p in tw), "settings.json lists it (%s)" % tw)
check(call(base, "/api/extensions")[1].get("trusted") is True, "the listing says trusted")
code, d = call(base, "/api/extensions/trust", {"on": False})
check(code == 200 and d.get("trusted") is False and not settings().get("trusted_workspaces"),
"untrust (%s)" % settings().get("trusted_workspaces"))
check(call(base, "/api/extensions/trust", {"on": "yes"})[0] == 400, "trust needs a bool")
skill(ws, "zeta", "第二个", "ZETA")
code, d = call(base, "/api/extensions/reload", {})
check(code == 200 and "2 skills" in d.get("report", ""), "reload sees the new skill (%s)" % d)
check([s["name"] for s in call(base, "/api/extensions")[1]["skills"]] == ["demo", "zeta"], "both listed")
# 6. while a turn runs
call(base, "/api/turn", {"text": "slow 慢一点"})
time.sleep(0.4)
check(call(base, "/api/extensions/reload", {})[0] == 409, "reload during a turn: 409")
check(call(base, "/api/extensions/trust", {"on": True})[0] == 409, "trust during a turn: 409")
check(call(base, "/api/skill", {"name": "demo"})[0] == 409, "skill during a turn: 409")
check(call(base, "/api/init", {})[0] == 409, "init during a turn: 409")
check(call(base, "/api/extensions")[0] == 200, "the listing works during a turn")
check(call(base, "/api/config", {"show_thinking": True})[0] == 200, "the thinking switch works during a turn")
wait(lambda: not busy(base), 20)
check(not settings().get("trusted_workspaces"), "the refused trust changed nothing")
# 7. another workspace brings its own skills
ws2 = tempfile.mkdtemp(prefix="cst-ext2-")
skill(ws2, "other", "另一个工作区的", "OTHER")
code, _ = call(base, "/api/workspace", {"path": ws2})
ex = call(base, "/api/extensions")[1]
check(code == 200 and [s["name"] for s in ex.get("skills", [])] == ["other"]
and ex.get("report") == "1 skill", "a workspace switch reloads the extensions (%s)" % ex.get("report"))
code, d = turn(base, "/api/skill", {"name": "other"})
check(code == 202 and "OTHER" in SEEN[-1], "and its skill runs")
shutil.rmtree(ws2, ignore_errors=True)
finally:
proc.terminate()
try:
proc.wait(20)
except subprocess.TimeoutExpired:
proc.kill()
check(False, "server hung on SIGTERM")
log.close()
shutil.rmtree(ws, ignore_errors=True)
shutil.rmtree(home, ignore_errors=True)
api.shutdown()
print("FAILED:", fails)
sys.exit(1 if fails else 0)
+327
View File
@@ -0,0 +1,327 @@
"""WebUI session management against a fake OpenAI-compatible API.
python3 scripts/e2e_webui_sessions.py (CST_AGENT= picks the binary)
Checks: retry runs the last prompt again and edit-and-resend replaces it
(the model sees the new text, the session keeps one copy); retry is a 409
while a turn runs and when there is nothing to retry; export returns the
transcript as Markdown; rename, clear and delete work on the store, and
deleting the open session moves to a new one; history messages carry the
note / tool_result flags. HOME points at a temp dir.
"""
import json, os, shutil, subprocess, sys, tempfile, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
BIN = os.environ.get("CST_AGENT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "cst-agent"))
SEEN = []
def last_prompt(msgs):
"""The prompts are one line; a note before one shares its user message."""
for m in reversed(msgs):
c = m.get("content")
if m.get("role") == "user" and isinstance(c, str):
return c.rstrip("\n").split("\n")[-1]
return ""
class Api(BaseHTTPRequestHandler):
"""Answers "回答:<last prompt>"; a prompt with "slow" takes 2 s."""
def log_message(self, *a):
pass
def do_GET(self):
body = json.dumps({"data": [{"id": "deepseek-flash"}]}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
msgs = req.get("messages", [])
p = last_prompt(msgs)
tail = msgs[-1] if msgs else {}
tc = tail.get("content") if isinstance(tail.get("content"), str) else ""
answered = tail.get("role") == "tool" or tc.startswith("result ")
if not answered:
SEEN.append(p)
if "slow" in p:
time.sleep(2)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
if answered:
chunks = ({"delta": {"role": "assistant", "content": "读完了"}},
{"delta": {}, "finish_reason": "stop"})
elif p.startswith("native"):
args = json.dumps({"path": "hello.txt"})
chunks = ({"delta": {"role": "assistant", "tool_calls": [
{"index": 0, "id": "c1", "type": "function",
"function": {"name": "read_file", "arguments": args}}]}},
{"delta": {}, "finish_reason": "tool_calls"})
elif p.startswith("ctl"):
chunks = ({"delta": {"role": "assistant",
"content": "我来读。\ncall t1 read_file\narg path 9\nhello.txtend\n"}},
{"delta": {}, "finish_reason": "stop"})
else:
chunks = ({"delta": {"role": "assistant", "content": "回答:" + p}},
{"delta": {}, "finish_reason": "stop"})
for o in chunks:
chunk = {"id": "x", "object": "chat.completion.chunk", "model": "deepseek-flash",
"choices": [dict(index=0, **o)]}
self.wfile.write(b"data: " + json.dumps(chunk, ensure_ascii=False).encode() + b"\n\n")
self.wfile.flush()
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
fails = 0
def check(ok, msg):
global fails
print(("PASS " if ok else "FAIL ") + msg)
fails += 0 if ok else 1
def wait(fn, t=15):
end = time.time() + t
while time.time() < end:
v = fn()
if v:
return v
time.sleep(0.1)
return None
def call(base, path, obj=None, method=None, raw_reply=False):
data = None if obj is None else json.dumps(obj).encode()
req = urllib.request.Request(base + path, data=data, method=method or ("POST" if data else "GET"),
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=20) as r:
raw = r.read()
if raw_reply:
return r.status, r.headers.get("Content-Type", ""), raw
return r.status, json.loads(raw or b"{}")
except urllib.error.HTTPError as e:
raw = e.read()
if raw_reply:
return e.code, e.headers.get("Content-Type", ""), raw
try:
return e.code, json.loads(raw or b"{}")
except ValueError:
return e.code, {}
class Sse:
def __init__(self, base):
self.lines = []
self.r = urllib.request.urlopen(base + "/api/events", timeout=60)
threading.Thread(target=self.pump, daemon=True).start()
def pump(self):
try:
for raw in self.r:
self.lines.append(raw)
except Exception:
pass
def count(self, name):
return sum(1 for l in self.lines if l.strip() == b"event: " + name.encode())
def close(self):
try:
self.r.close()
except Exception:
pass
api = ThreadingHTTPServer(("127.0.0.1", 0), Api)
threading.Thread(target=api.serve_forever, daemon=True).start()
ws = tempfile.mkdtemp(prefix="cst-sess-")
home = tempfile.mkdtemp(prefix="cst-home-")
env = dict(os.environ, HOME=home, XDG_CONFIG_HOME=home + "/.config",
XDG_DATA_HOME=home + "/.local/share", XDG_CACHE_HOME=home + "/.cache")
for k in ("DEEPSEEK_API_KEY", "OPENAI_API_KEY", "CST_API_KEY"):
env.pop(k, None)
log = open(ws + "/server.log", "w+")
proc = subprocess.Popen([BIN, "--web", "--web-port", "0", "--workspace", ws, "--new", "--api-key", "sk-x",
"--provider", "deepseek", "--model", "deepseek-flash",
"--api-base", "http://127.0.0.1:%d/v1" % api.server_address[1],
"--protocol", "native-eos", "--approval", "auto"],
stdout=log, stderr=subprocess.STDOUT, env=env)
def port():
log.seek(0)
for l in log.read().splitlines():
if l.startswith("webui: http://127.0.0.1:"):
return l.split(":")[3].split("/")[0]
def messages(base):
return call(base, "/api/session")[1].get("messages", [])
def prompts(base):
return [m["content"] for m in messages(base)
if m["role"] == "user" and not m.get("note") and not m.get("tool_result")]
def answers(base):
return [m["content"] for m in messages(base) if m["role"] == "assistant"]
def turn(base, sse, path, body, want=202):
n = sse.count("turn_end")
code, d = call(base, path, body)
if code == want == 202:
wait(lambda: sse.count("turn_end") > n, 20)
return code, d
try:
base = "http://127.0.0.1:%s" % wait(port)
sse = Sse(base)
time.sleep(0.3)
# 1. retry with nothing to retry, then a first turn
code, d = call(base, "/api/retry", {})
check(code == 409 and "nothing to retry" in d.get("error", ""), "retry on an empty session: 409 (%s)" % code)
turn(base, sse, "/api/turn", {"text": "第一句"})
check(prompts(base) == ["第一句"] and answers(base) == ["回答:第一句"], "first turn stored")
# 2. retry: same prompt again, one copy in the session
code, d = turn(base, sse, "/api/retry", {})
check(code == 202 and d.get("text") == "第一句", "retry accepted (%s %s)" % (code, d))
check(SEEN[-1] == "第一句", "the model saw the same prompt again")
check(prompts(base) == ["第一句"] and answers(base) == ["回答:第一句"],
"after retry: one prompt, one answer (%s)" % prompts(base))
# 3. edit and resend: the new text replaces the old
code, d = turn(base, sse, "/api/retry", {"text": "改过的问题"})
check(code == 202 and d.get("text") == "改过的问题", "edit-and-resend accepted")
check(SEEN[-1] == "改过的问题", "the model saw the edited prompt")
check(prompts(base) == ["改过的问题"] and answers(base) == ["回答:改过的问题"],
"after edit: %s / %s" % (prompts(base), answers(base)))
check(call(base, "/api/retry", {"text": ""})[0] == 400, "an empty edit is a 400")
check(call(base, "/api/retry", {"text": 5})[0] == 400, "a non-string edit is a 400")
# 4. a second turn, then retry only touches the last one
turn(base, sse, "/api/turn", {"text": "第二句"})
turn(base, sse, "/api/retry", {})
check(prompts(base) == ["改过的问题", "第二句"] and len(answers(base)) == 2,
"retry keeps earlier turns: %s" % prompts(base))
# 5. retry while a turn runs is a 409
n = sse.count("turn_end")
call(base, "/api/turn", {"text": "slow 请慢一点"})
code, d = call(base, "/api/retry", {})
check(code == 409, "retry during a turn: 409 (%s)" % code)
wait(lambda: sse.count("turn_end") > n, 20)
# 6. a note (plan mode changed mid-session) is flagged, and retry skips it
call(base, "/api/config", {"plan_mode": True})
turn(base, sse, "/api/turn", {"text": "计划一下"})
ms = messages(base)
notes = [m for m in ms if m.get("note")]
check(len(notes) >= 1 and all(m["role"] == "user" for m in notes),
"a mid-session note is flagged note:true (%d)" % len(notes))
turn(base, sse, "/api/retry", {})
check(SEEN[-1] == "计划一下" and prompts(base)[-1] == "计划一下", "retry after a note reruns the prompt")
call(base, "/api/config", {"plan_mode": False})
# 7. export
code, ctype, raw = call(base, "/api/export", raw_reply=True)
md = raw.decode("utf-8", "replace")
check(code == 200 and ctype.startswith("text/markdown"), "export: %s %s" % (code, ctype))
check(md.startswith("# ") and "## User" in md and "改过的问题" in md and "## Assistant" in md
and "回答:第二句" in md and "第一句" not in md, "export has the transcript")
# 8. rename and clear
st = call(base, "/api/state")[1]
cur = st.get("session")
code, _ = call(base, "/api/sessions/rename", {"title": "我的会话"})
check(code == 200, "rename the open session")
ss = call(base, "/api/sessions")[1]
check(any(s["id"] == cur and s["title"] == "我的会话" for s in ss.get("sessions", [])),
"the list shows the new title")
code, _, raw = call(base, "/api/export", raw_reply=True)
check(raw.decode("utf-8", "replace").startswith("# 我的会话"), "export uses the title")
long = "长" * 100
call(base, "/api/sessions/rename", {"id": cur, "title": long})
t = [s["title"] for s in call(base, "/api/sessions")[1]["sessions"] if s["id"] == cur][0]
check(0 < len(t.encode()) <= 120 and t == "长" * len(t), "a long title is cut on a character (%d bytes)"
% len(t.encode()))
call(base, "/api/sessions/rename", {"title": ""})
t = [s["title"] for s in call(base, "/api/sessions")[1]["sessions"] if s["id"] == cur][0]
check(t == "改过的问题", "an empty title falls back to the first prompt (%r)" % t)
check(call(base, "/api/sessions/rename", {"id": "nope", "title": "x"})[0] == 404, "rename unknown: 404")
check(call(base, "/api/sessions/rename", {"id": "../x", "title": "x"})[0] == 404, "rename ../x: 404")
check(call(base, "/api/sessions/rename", {})[0] == 400, "rename without a title: 400")
# 9. delete another session, then the open one
code, d = call(base, "/api/sessions/new", {})
second = d.get("id")
check(code == 200 and second and second != cur, "a second session")
code, d = call(base, "/api/sessions/delete", {"id": cur})
check(code == 200 and d.get("current") == second, "delete a closed session (%s %s)" % (code, d))
ids = [s["id"] for s in call(base, "/api/sessions")[1]["sessions"]]
check(cur not in ids and not os.path.exists(os.path.join(ws, ".agent", "sessions", cur + ".jsonl")),
"it is gone from the list and the disk")
n = sse.count("session")
code, d = call(base, "/api/sessions/delete", {"id": second})
check(code == 200 and d.get("current") and d["current"] != second, "delete the open session (%s)" % d)
check(call(base, "/api/state")[1].get("session") == d.get("current"), "the state moved to the new one")
check(wait(lambda: sse.count("session") > n, 5), "a session event was sent")
check(call(base, "/api/sessions/delete", {"id": "nope"})[0] == 404, "delete unknown: 404")
check(call(base, "/api/sessions/delete", {})[0] == 400, "delete without an id: 400")
# 10. history: calls and results come back apart, for native and ctl
with open(os.path.join(ws, "hello.txt"), "w", encoding="utf-8") as f:
f.write("你好世界\n")
turn(base, sse, "/api/turn", {"text": "native 读文件"})
ms = messages(base)
a = [m for m in ms if m["role"] == "assistant" and m.get("calls")]
r = [m for m in ms if m.get("tool_result")]
check(len(a) == 1 and a[0]["calls"][0].get("name") == "read_file"
and a[0]["calls"][0].get("args", {}).get("path") == "hello.txt" and a[0]["calls"][0].get("id") == "c1",
"native: the call is listed with its args (%s)" % (a[0].get("calls") if a else ms))
check(len(r) == 1 and r[0]["role"] == "tool" and r[0].get("tool_call_id") == "c1"
and "你好世界" in r[0].get("out", "") and not r[0]["out"].startswith("[tool ")
and r[0].get("exit") == 0 and r[0].get("truncated") is False,
"native: the result carries out/exit without the header (%s)" % r)
check(answers(base)[-1] == "读完了", "native: the turn finished")
check(call(base, "/api/settings", {"protocol": "ctl"})[0] == 200, "switch to the ctl protocol")
turn(base, sse, "/api/turn", {"text": "ctl 读文件"})
ms = messages(base)
a = [m for m in ms if m["role"] == "assistant" and m.get("calls") and m["calls"][0].get("id") == "t1"]
r = [m for m in ms if m.get("tool_result") and m.get("tool_call_id") == "t1"]
check(len(a) == 1 and a[0].get("text", "").strip() == "我来读。" and "call t1" in a[0]["content"]
and a[0]["calls"][0].get("args", {}).get("path") == "hello.txt"
and "call t1" not in a[0].get("html", ""),
"ctl: prose and calls are split (%s)" % (a[0] if a else ms[-4:]))
check(len(r) == 1 and r[0]["role"] == "user" and "你好世界" in r[0].get("out", "")
and not r[0]["out"].startswith("result ") and not r[0]["out"].endswith("end")
and r[0].get("exit") == 0,
"ctl: the result is flagged with out/exit (%s)" % r)
check(r and r[0]["content"] not in prompts(base), "ctl: the result is not a prompt")
call(base, "/api/settings", {"protocol": "native-eos"})
sse.close()
finally:
proc.terminate()
try:
proc.wait(20)
except subprocess.TimeoutExpired:
proc.kill()
check(False, "server hung on SIGTERM")
log.close()
shutil.rmtree(ws, ignore_errors=True)
shutil.rmtree(home, ignore_errors=True)
api.shutdown()
print("FAILED:", fails)
sys.exit(1 if fails else 0)
+313
View File
@@ -0,0 +1,313 @@
"""WebUI settings and streaming against fake OpenAI-compatible APIs.
python3 scripts/e2e_webui_settings.py (CST_AGENT= picks the binary)
Checks: Chinese reasoning streams as whole characters in few events; the
provider list, the model list with capabilities, config validation and
persistence; a wrong key is rejected, a good one switches the provider
(requests then go to the new base URL) and is saved; and all of it
survives a restart. HOME and XDG_CONFIG_HOME point at a temp dir, so no
real credentials or settings are read or written.
"""
import json, os, shutil, stat, subprocess, sys, tempfile, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
BIN = os.environ.get("CST_AGENT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "cst-agent"))
THINK = ["好的,我先看看工作区里", "有哪些文件,然后用中文", "回答这个问题。😀 结束"]
ANSWER = "这是中文回答。"
GOOD_KEYS = {"sk-good", "sk-good2"}
B_REQS = []
def sse_reply(h, model, think, answer):
h.send_response(200)
h.send_header("Content-Type", "text/event-stream")
h.end_headers()
base = {"id": "x", "object": "chat.completion.chunk", "model": model}
def ev(o):
h.wfile.write(b"data: " + json.dumps({**base, **o}, ensure_ascii=False).encode() + b"\n\n")
h.wfile.flush()
for part in think:
ev({"choices": [{"index": 0, "delta": {"role": "assistant", "reasoning_content": part}}]})
ev({"choices": [{"index": 0, "delta": {"content": answer}}]})
ev({"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]})
h.wfile.write(b"data: [DONE]\n\n")
h.wfile.flush()
def send_json(h, code, obj):
body = json.dumps(obj).encode()
h.send_response(code)
h.send_header("Content-Type", "application/json")
h.send_header("Content-Length", str(len(body)))
h.end_headers()
h.wfile.write(body)
class A(BaseHTTPRequestHandler):
"""The starting provider: any key, one model, Chinese reasoning."""
def log_message(self, *a):
pass
def do_GET(self):
send_json(self, 200, {"data": [{"id": "deepseek-flash"}]})
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", 0)))
sse_reply(self, "deepseek-flash", THINK, ANSWER)
class B(BaseHTTPRequestHandler):
"""The provider switched to: /models checks the key."""
def log_message(self, *a):
pass
def key_ok(self):
auth = self.headers.get("Authorization", "")
return auth.startswith("Bearer ") and auth[7:] in GOOD_KEYS
def do_GET(self):
if not self.key_ok():
return send_json(self, 401, {"error": {"message": "invalid api key"}})
send_json(self, 200, {"data": [{"id": "fake-vis"}, {"id": "fake-text"}]})
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
B_REQS.append({"auth": self.headers.get("Authorization", ""), "model": body.get("model")})
if not self.key_ok():
return send_json(self, 401, {"error": {"message": "invalid api key"}})
sse_reply(self, body.get("model") or "fake-vis", [], "B 的回答")
fails = 0
def check(ok, msg):
global fails
print(("PASS " if ok else "FAIL ") + msg)
fails += 0 if ok else 1
class Sse:
def __init__(self, base):
self.lines = []
self.r = urllib.request.urlopen(base + "/api/events", timeout=60)
threading.Thread(target=self.pump, daemon=True).start()
def pump(self):
try:
for raw in self.r:
self.lines.append(raw)
except Exception:
pass
def events(self, name):
out = []
for i, l in enumerate(self.lines):
if l.strip() == b"event: " + name.encode() and i + 1 < len(self.lines):
out.append(self.lines[i + 1][6:])
return out
def close(self):
try:
self.r.close()
except Exception:
pass
def wait(fn, t=15):
end = time.time() + t
while time.time() < end:
v = fn()
if v:
return v
time.sleep(0.1)
return None
def call(base, path, obj=None, method=None):
data = None if obj is None else json.dumps(obj).encode()
req = urllib.request.Request(base + path, data=data, method=method or ("POST" if data else "GET"),
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=20) as r:
raw = r.read()
return r.status, json.loads(raw or b"{}"), raw
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw or b"{}"), raw
except ValueError:
return e.code, {}, raw
def serve(handler):
s = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=s.serve_forever, daemon=True).start()
return s
api_a, api_b = serve(A), serve(B)
ws = tempfile.mkdtemp(prefix="cst-set-")
home = tempfile.mkdtemp(prefix="cst-home-")
cfgdir = home + "/.config/cst-agent"
os.makedirs(cfgdir)
with open(cfgdir + "/models.json", "w") as f:
json.dump({"providers": {"fakeb": {"api_base": "http://127.0.0.1:%d/v1" % api_b.server_address[1],
"key_env": "FAKEB_API_KEY", "default_model": ""}},
"models": [{"match": "fake-vis", "vision": True, "context": 200000},
{"match": "fake-text", "vision": False}]}, f)
env = dict(os.environ, HOME=home, XDG_CONFIG_HOME=home + "/.config",
XDG_DATA_HOME=home + "/.local/share", XDG_CACHE_HOME=home + "/.cache")
for k in ("DEEPSEEK_API_KEY", "FAKEB_API_KEY", "OPENAI_API_KEY", "CST_API_KEY"):
env.pop(k, None)
procs = []
def start(args, tag):
log = open("%s/%s.log" % (ws, tag), "w+")
p = subprocess.Popen([BIN, "--web", "--web-port", "0", "--workspace", ws] + args,
stdout=log, stderr=subprocess.STDOUT, env=env)
procs.append((p, log))
def port():
log.seek(0)
for l in log.read().splitlines():
if l.startswith("webui: http://127.0.0.1:"):
return l.split(":")[3].split("/")[0]
pt = wait(port)
return p, "http://127.0.0.1:%s" % pt
def stop(p):
p.terminate()
try:
p.wait(20)
except subprocess.TimeoutExpired:
p.kill()
check(False, "server hung on SIGTERM")
check(p.returncode is not None and 0 <= p.returncode < 128, "clean exit (%s)" % p.returncode)
def leaked(raw):
return any(k.encode() in raw for k in GOOD_KEYS | {"sk-bad", "sk-x"})
try:
p, base = start(["--new", "--api-key", "sk-x", "--provider", "deepseek", "--model", "deepseek-flash",
"--api-base", "http://127.0.0.1:%d/v1" % api_a.server_address[1],
"--protocol", "native-eos", "--approval", "auto"], "first")
a = Sse(base)
time.sleep(0.3)
# 1. Chinese reasoning: whole characters, a handful of events
code, _, _ = call(base, "/api/turn", {"text": "用中文想一想"})
check(code == 202, "turn accepted")
end = wait(lambda: a.events("turn_end"), 20)
check(bool(end) and json.loads(end[0]).get("rc") == 0, "turn ended rc=0")
raw = a.events("think_delta")
ok = True
for r in raw:
try:
r.decode("utf-8")
except UnicodeDecodeError:
ok = False
check(ok, "every think_delta frame is valid UTF-8")
text = "".join(json.loads(r.decode("utf-8", "replace"))["text"] for r in raw)
want = "".join(THINK)
check(text == want and "\ufffd" not in text, "the thinking text round trips: %r" % text[:60])
check(0 < len(raw) <= 2 * len(THINK) + 2,
"think_delta events: %d for %d bytes" % (len(raw), len(want.encode())))
ans = "".join(json.loads(r)["text"] for r in a.events("assistant_delta"))
check(ans == ANSWER, "the answer round trips: %r" % ans)
# 2. providers and models
code, d, rawp = call(base, "/api/providers")
names = {x["name"]: x for x in d.get("providers", [])}
check(code == 200 and "deepseek" in names and "fakeb" in names, "provider list: %s" % sorted(names))
check(names.get("deepseek", {}).get("current") and names["deepseek"].get("has_key")
and names["deepseek"].get("key_from") == "session", "deepseek: current, key for this run")
check(names.get("fakeb", {}).get("has_key") is False and names["fakeb"].get("source") == "user",
"fakeb: no key yet, from models.json")
check(not leaked(rawp), "no key in /api/providers")
code, d, _ = call(base, "/api/models")
ids = [m["id"] for m in d.get("models", [])]
first = (d.get("models") or [{}])[0]
check(code == 200 and "deepseek-flash" in ids and first.get("api") is True
and "context" in first and "label" in first, "model list: %s" % ids[:5])
# 3. config: validation and persistence
check(call(base, "/api/config", {"effort": "bogus"})[0] == 400, "a bad effort is a 400")
check(call(base, "/api/config", {"provider": "fakeb"})[0] == 400, "provider via /api/config is a 400")
check(call(base, "/api/config", {"model": ""})[0] == 400, "an empty model is a 400")
code, d, _ = call(base, "/api/config", {"model": "deepseek-v4-pro", "effort": "high"})
check(code == 200 and d.get("ok"), "model + effort accepted")
code, s, _ = call(base, "/api/state")
check(s.get("model") == "deepseek-v4-pro" and s.get("effort") == "high", "the state has them")
check(s.get("effort_applies") is True and s.get("key_set") is True and "model_info" in s
and s.get("perm_timeout", 0) > 0 and "turn_usage" in s, "the state has the new fields")
st = open(cfgdir + "/settings.json").read() if os.path.exists(cfgdir + "/settings.json") else ""
check("deepseek-v4-pro" in st and "high" in st, "settings.json remembers model and effort")
# 4. switching provider: no key, a wrong key, a good key
code, d, _ = call(base, "/api/provider", {"name": "fakeb"})
check(code == 400 and d.get("need_key"), "fakeb without a key: need_key (%s)" % code)
code, d, rawp = call(base, "/api/provider", {"name": "fakeb", "key": "sk-bad"})
check(code == 401 and "拒绝" in d.get("error", ""), "a wrong key is rejected (%s %s)" % (code, d.get("error")))
check(not leaked(rawp), "no key in the rejection")
check(call(base, "/api/state")[1].get("provider") == "deepseek", "still on deepseek")
check(call(base, "/api/provider", {"name": "nope"})[0] == 404, "an unknown provider is a 404")
code, d, rawp = call(base, "/api/provider", {"name": "fakeb", "key": "sk-good"})
check(code == 200 and d.get("provider") == "fakeb" and d.get("model") == "fake-vis",
"switched to fakeb, first listed model picked (%s %s)" % (code, d))
check(not leaked(rawp), "no key in the switch reply")
creds = cfgdir + "/credentials"
cr = open(creds).read() if os.path.exists(creds) else ""
check("fakeb.api_key=sk-good" in cr, "the key was saved to credentials")
if os.name == "posix" and os.path.exists(creds):
check(stat.S_IMODE(os.stat(creds).st_mode) == 0o600, "credentials is 0600")
code, d, _ = call(base, "/api/models")
ms = {m["id"]: m for m in d.get("models", [])}
check("fake-vis" in ms and ms["fake-vis"].get("vision") is True and ms["fake-vis"].get("context") == 200000
and ms.get("fake-text", {}).get("vision") is False, "fakeb models with capabilities")
code, d, _ = call(base, "/api/config", {"effort": "low"})
check(code == 200 and d.get("warning"), "effort on a model without it: saved with a warning")
# 5. a turn now goes to the new base URL with the new key
n0 = len(B_REQS)
code, _, _ = call(base, "/api/turn", {"text": "hi B"})
check(code == 202, "turn on fakeb accepted")
wait(lambda: len(a.events("turn_end")) >= 2, 20)
check(len(B_REQS) > n0 and B_REQS[-1]["auth"] == "Bearer sk-good" and B_REQS[-1]["model"] == "fake-vis",
"the request reached fakeb: %s" % (B_REQS[-1:] or "none"))
# 6. replacing the key
code, d, _ = call(base, "/api/key", {"key": "sk-bad"})
check(code == 401, "a wrong replacement key is rejected (%s)" % code)
code, d, _ = call(base, "/api/key", {"key": "sk-good2"})
check(code == 200 and d.get("ok"), "the replacement key is accepted")
check("fakeb.api_key=sk-good2" in open(creds).read(), "the replacement key was saved")
check(call(base, "/api/key", {})[0] == 400, "an empty key body is a 400")
a.close()
stop(p)
# 7. the next start remembers provider, model and key
p, base = start(["--new"], "second")
code, s, raws = call(base, "/api/state")
check(s.get("provider") == "fakeb" and s.get("model") == "fake-vis" and s.get("key_set") is True
and s.get("key_from") == "saved", "restart: %s/%s key %s" % (s.get("provider"), s.get("model"), s.get("key_from")))
check(not leaked(raws), "no key in /api/state")
stop(p)
logs = b"".join(open(lg.name, "rb").read() for _, lg in procs)
check(not leaked(logs.replace(b"sk-x", b"")) , "no key in the server logs")
finally:
for p, log in procs:
if p.poll() is None:
p.kill()
log.close()
shutil.rmtree(ws, ignore_errors=True)
shutil.rmtree(home, ignore_errors=True)
print("FAILED:", fails)
sys.exit(1 if fails else 0)
+206
View File
@@ -0,0 +1,206 @@
"""WebUI workspace views: git diff, run settings, saved permission rules.
python3 scripts/e2e_webui_workspace.py (CST_AGENT= picks the binary)
Checks: /api/diff lists git status and the working-tree diff (per file too),
an option-looking path is only ever a path, and a directory without git
says so; /api/settings reports protocol, tools, confirmations and the
sandbox, rejects a bad body without applying any of it, applies a good one,
and is a 409 while a turn runs; /api/permissions shows the saved rules and
DELETE clears them. HOME points at a temp dir.
"""
import json, os, shutil, subprocess, sys, tempfile, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
BIN = os.environ.get("CST_AGENT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "cst-agent"))
class Api(BaseHTTPRequestHandler):
"""A slow plain answer, so a turn is running for a while."""
def log_message(self, *a):
pass
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", 0)))
time.sleep(2)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
for o in ({"delta": {"role": "assistant", "content": "好"}}, {"delta": {}, "finish_reason": "stop"}):
chunk = {"id": "x", "object": "chat.completion.chunk", "model": "m", "choices": [dict(index=0, **o)]}
self.wfile.write(b"data: " + json.dumps(chunk, ensure_ascii=False).encode() + b"\n\n")
self.wfile.write(b"data: [DONE]\n\n")
fails = 0
def check(ok, msg):
global fails
print(("PASS " if ok else "FAIL ") + msg)
fails += 0 if ok else 1
def wait(fn, t=15):
end = time.time() + t
while time.time() < end:
v = fn()
if v:
return v
time.sleep(0.1)
return None
def call(base, path, obj=None, method=None):
data = None if obj is None else json.dumps(obj).encode()
req = urllib.request.Request(base + path, data=data, method=method or ("POST" if data else "GET"),
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, json.loads(r.read() or b"{}")
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw or b"{}")
except ValueError:
return e.code, {}
def git(*args):
return subprocess.run(["git", "-C", ws] + list(args), capture_output=True, text=True)
api = ThreadingHTTPServer(("127.0.0.1", 0), Api)
threading.Thread(target=api.serve_forever, daemon=True).start()
ws = tempfile.mkdtemp(prefix="cst-ws-")
plain = tempfile.mkdtemp(prefix="cst-nogit-")
home = tempfile.mkdtemp(prefix="cst-home-")
env = dict(os.environ, HOME=home, XDG_CONFIG_HOME=home + "/.config",
XDG_DATA_HOME=home + "/.local/share", XDG_CACHE_HOME=home + "/.cache",
GIT_CONFIG_NOSYSTEM="1")
for k in ("DEEPSEEK_API_KEY", "OPENAI_API_KEY", "CST_API_KEY"):
env.pop(k, None)
have_git = shutil.which("git") is not None
if have_git:
git("init", "-q")
git("config", "user.email", "e2e@example.com")
git("config", "user.name", "e2e")
open(ws + "/a.txt", "w").write("one\n")
git("add", "a.txt")
git("commit", "-q", "-m", "first")
open(ws + "/a.txt", "w").write("one\n第二行\n")
open(ws + "/new.txt", "w").write("new\n")
os.makedirs(ws + "/.agent", exist_ok=True)
json.dump({"tools": ["write_file"], "shell_prefixes": ["make"]}, open(ws + "/.agent/permissions.json", "w"))
log = open(home + "/server.log", "w+")
proc = subprocess.Popen([BIN, "--web", "--web-port", "0", "--workspace", ws, "--new", "--api-key", "sk-x",
"--provider", "deepseek", "--model", "deepseek-flash",
"--api-base", "http://127.0.0.1:%d/v1" % api.server_address[1],
"--protocol", "native-eos", "--approval", "auto"],
stdout=log, stderr=subprocess.STDOUT, env=env)
def port():
log.seek(0)
for l in log.read().splitlines():
if l.startswith("webui: http://127.0.0.1:"):
return l.split(":")[3].split("/")[0]
try:
base = "http://127.0.0.1:%s" % wait(port)
# 1. diff
if have_git:
code, d = call(base, "/api/diff")
files = {f["path"]: f["status"] for f in d.get("files", [])}
check(code == 200 and d.get("git") is True, "diff: git repo seen")
check(files.get("a.txt") == " M" and files.get("new.txt") == "??", "status lists both files: %s" % files)
check("+第二行" in d.get("diff", "") and "a.txt" in d.get("diff", ""), "the diff has the change")
code, d = call(base, "/api/diff?path=a.txt")
check(code == 200 and "+第二行" in d.get("diff", "") and d.get("path") == "a.txt", "diff of one file")
code, d = call(base, "/api/diff?path=new.txt")
check(code == 200 and d.get("diff") == "", "an untracked file has no diff")
evil = ws + "/pwned"
code, d = call(base, "/api/diff?path=" + urllib.request.quote("--output=" + evil))
check(code == 200 and not os.path.exists(evil), "an option-looking path stays a path")
else:
print("SKIP diff checks: no git")
# 2. settings: what is there
code, s = call(base, "/api/settings")
names = [t["name"] for t in s.get("tools", [])]
check(code == 200 and s.get("protocol") == "native-eos" and len(s.get("protocols", [])) == 5,
"settings: protocol %s of %s" % (s.get("protocol"), s.get("protocols")))
check("read_file" in names and all("perm" in t and "on" in t for t in s["tools"]), "tool list: %d tools" % len(names))
check(set(s.get("confirm", {})) == {"shell", "write", "net"}, "confirm flags present")
check(isinstance(s.get("sandbox", {}).get("kind"), str), "sandbox kind: %s" % s.get("sandbox"))
victim = next((t["name"] for t in s["tools"] if t["perm"] == "net"), names[-1])
# 3. a bad body changes nothing
for body, why in (({"protocol": "nope"}, "unknown protocol"), ({"max_steps": 0}, "max_steps 0"),
({"max_steps": "5"}, "max_steps as text"), ({"tool_profile": "huge"}, "unknown profile"),
({"tools": {"nope": False}}, "unknown tool"), ({"tools": {victim: "off"}}, "tool value not bool"),
({"confirm": {"disk": True}}, "unknown confirm key"),
({"max_steps": 9, "protocol": "nope"}, "mixed good and bad")):
check(call(base, "/api/settings", body)[0] == 400, "400 for %s" % why)
check(call(base, "/api/settings")[1].get("max_steps") == s.get("max_steps"), "nothing applied from a bad body")
# 4. a good body applies
code, d = call(base, "/api/settings", {"protocol": "ctl", "max_steps": 7, "tool_profile": "minimal",
"tools": {victim: False}, "confirm": {"shell": True, "net": False}})
check(code == 200 and d.get("ok"), "settings accepted (%s %s)" % (code, d))
code, s2 = call(base, "/api/settings")
t2 = {t["name"]: t for t in s2.get("tools", [])}
check(s2.get("protocol") == "ctl" and s2.get("max_steps") == 7 and s2.get("tool_profile") == "minimal",
"protocol/steps/profile applied")
check(t2.get(victim, {}).get("off") is True and t2[victim]["on"] is False, "%s switched off" % victim)
check(s2["confirm"]["shell"] is True and s2["confirm"]["net"] is False, "confirm flags applied")
st = call(base, "/api/state")[1]
check(st.get("protocol_tools") == "ctl" and st.get("max_steps") == 7 and st.get("tool_profile") == "minimal",
"the state shows them")
call(base, "/api/settings", {"protocol": "native-eos", "tool_profile": "default", "tools": {victim: True}})
t3 = {t["name"]: t for t in call(base, "/api/settings")[1]["tools"]}
check(t3[victim]["off"] is False and t3[victim]["on"] is True, "%s back on" % victim)
# 5. permissions
code, p = call(base, "/api/permissions")
check(code == 200 and p.get("tools") == ["write_file"] and p.get("shell_prefixes") == ["make"]
and "write_file" in p.get("rules", ""), "saved rules: %s %s" % (p.get("tools"), p.get("shell_prefixes")))
code, _ = call(base, "/api/permissions", method="DELETE")
check(code == 200, "DELETE /api/permissions")
p = call(base, "/api/permissions")[1]
check(p.get("tools") == [] and p.get("shell_prefixes") == [], "the rules are gone")
saved = json.load(open(ws + "/.agent/permissions.json"))
check(saved.get("tools") == [] and saved.get("shell_prefixes") == [], "and gone from the file")
# 6. while a turn runs: settings and the rule reset are 409, reads still work
code, _ = call(base, "/api/turn", {"text": "慢慢来"})
check(code == 202, "a slow turn started")
check(call(base, "/api/settings", {"max_steps": 3})[0] == 409, "settings during a turn: 409")
check(call(base, "/api/permissions", method="DELETE")[0] == 409, "rule reset during a turn: 409")
check(call(base, "/api/settings")[0] == 200 and call(base, "/api/permissions")[0] == 200,
"reads during a turn: 200")
if have_git:
check(call(base, "/api/diff")[0] == 200, "diff during a turn: 200")
wait(lambda: not call(base, "/api/state")[1].get("status_busy"), 20)
# 7. a directory without git
if have_git:
code, _ = call(base, "/api/workspace", {"path": plain})
code, d = call(base, "/api/diff")
check(code == 200 and d.get("git") is False and "diff" not in d, "no git repo: git=false")
finally:
proc.terminate()
try:
proc.wait(20)
except subprocess.TimeoutExpired:
proc.kill()
check(False, "server hung on SIGTERM")
log.close()
for d in (ws, plain, home):
shutil.rmtree(d, ignore_errors=True)
api.shutdown()
print("FAILED:", fails)
sys.exit(1 if fails else 0)
+65
View File
@@ -0,0 +1,65 @@
"""TUI /provider and /key against a fake API whose /models checks the key.
nix-shell -p python3Packages.pyte --run "python3 scripts/tui_keys/provider.py"
A wrong key is asked for again, a good one is saved and switches the
provider; /key replaces it. Same code path as the WebUI (provider_switch.c).
"""
import json, os, sys, threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from harness import Term
from keys import check, base
GOOD = {"sk-good", "sk-good2"}
class B(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
auth = self.headers.get("Authorization", "")
ok = auth.startswith("Bearer ") and auth[7:] in GOOD
body = json.dumps({"data": [{"id": "fake-one"}]} if ok else {"error": {"message": "bad key"}}).encode()
self.send_response(200 if ok else 401)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
srv = ThreadingHTTPServer(("127.0.0.1", 0), B)
threading.Thread(target=srv.serve_forever, daemon=True).start()
t = Term(args=("-b", base, "-k", "sk-test"))
cfg = os.path.join(t.home, ".config", "cst-agent")
os.makedirs(cfg, exist_ok=True)
t.close()
with open(os.path.join(cfg, "models.json"), "w") as f:
json.dump({"providers": {"fakeb": {"api_base": "http://127.0.0.1:%d/v1" % srv.server_address[1],
"key_env": "FAKEB_API_KEY", "default_model": ""}}}, f)
t = Term(args=("-b", base, "-k", "sk-test"), home=t.home, env={"FAKEB_API_KEY": ""})
creds = os.path.join(cfg, "credentials")
def screen():
return "\n".join(t.lines())
t.send("/provider fakeb\r", 0.8)
check("a key prompt for fakeb", "API key for fakeb" in screen(), t)
t.send("sk-bad\r", 1.5)
check("a wrong key is asked for again", "rejected that key" in screen(), t)
check("the wrong key is not saved", not os.path.exists(creds) or "sk-bad" not in open(creds).read(), t)
t.send("sk-good\r", 2.0)
check("switched to fakeb", "provider → fakeb" in screen(), t)
check("the good key is saved", os.path.exists(creds) and "fakeb.api_key=sk-good" in open(creds).read(), t)
check("no key on screen", "sk-good" not in screen() and "sk-bad" not in screen(), t)
t.send("/key\r", 0.8)
t.send("sk-good2\r", 2.0)
check("/key replaces it", "fakeb.api_key=sk-good2" in open(creds).read(), t)
t.close()
from keys import FAILS
print("FAILED:", len(FAILS))
sys.exit(min(len(FAILS), 100))
+36 -16
View File
@@ -1282,13 +1282,22 @@ static void on_mm(const ctl_event_t *ev, void *ud) {
} }
static void feed_visible(turn_t *t, const char *data, size_t len) { static void feed_visible(turn_t *t, const char *data, size_t len) {
if (!len || t->stop) /* cut after each '\n' and '>': a call only becomes ready there, and
return; * raw_mark must not take in what follows it in the same chunk */
cst_buf_append(&t->raw, data, len); while (len && !t->stop) {
if (t->ctl) size_t n = 0;
ctl_parser_feed(t->ctl, data, len); while (n < len && data[n] != '\n' && data[n] != '>')
else if (t->mm) n++;
mm_scan_feed(t->mm, data, len); if (n < len)
n++;
cst_buf_append(&t->raw, data, n);
if (t->ctl)
ctl_parser_feed(t->ctl, data, n);
else if (t->mm)
mm_scan_feed(t->mm, data, n);
data += n;
len -= n;
}
} }
static void think_out(turn_t *t, const char *s, size_t n) { static void think_out(turn_t *t, const char *s, size_t n) {
@@ -1306,10 +1315,16 @@ static void on_delta(const char *data, size_t len, void *ud) {
const char *want = t->in_think ? "</think>" : "<think>"; const char *want = t->in_think ? "</think>" : "<think>";
size_t wl = strlen(want); size_t wl = strlen(want);
if (t->taglen == 0 && c != '<') { if (t->taglen == 0 && c != '<') {
/* the whole run up to the next '<' in one call: byte by byte, a
* front end would get every CJK character in three invalid pieces */
size_t j = i + 1;
while (j < len && data[j] != '<')
j++;
if (t->in_think) if (t->in_think)
think_out(t, &c, 1); think_out(t, data + i, j - i);
else else
feed_visible(t, &c, 1); feed_visible(t, data + i, j - i);
i = j - 1;
continue; continue;
} }
t->tagbuf[t->taglen++] = c; t->tagbuf[t->taglen++] = c;
@@ -2933,13 +2948,18 @@ int cst_agent_new_session(cst_agent_t *a, char *id_out, size_t id_sz) {
return -1; return -1;
if (cst_agent_store_ensure(a->cfg.workspace_root) != 0) if (cst_agent_store_ensure(a->cfg.workspace_root) != 0)
return -1; return -1;
char id[128]; char id[128], path[4096];
if (cst_agent_store_new_id(id, sizeof(id)) != 0) /* ids are per second: never reopen (and append to) one that exists */
return -1; for (int tries = 0;; tries++) {
char path[4096]; if (tries == 16 || cst_agent_store_new_id(id, sizeof(id)) != 0 ||
if (cst_agent_store_path_for_id(a->cfg.workspace_root, id, path, cst_agent_store_path_for_id(a->cfg.workspace_root, id, path,
sizeof(path)) != 0) sizeof(path)) != 0)
return -1; return -1;
FILE *fp = fopen(path, "rb");
if (!fp)
break;
fclose(fp);
}
if (agent_reopen_session(a, path) != 0) if (agent_reopen_session(a, path) != 0)
return -1; return -1;
cst_agent_store_set_current(a->cfg.workspace_root, id); cst_agent_store_set_current(a->cfg.workspace_root, id);
+2 -1
View File
@@ -57,7 +57,8 @@ static void make_id(char *out, size_t n) {
time_t now = time(NULL); time_t now = time(NULL);
struct tm tm; struct tm tm;
os_localtime(&now, &tm); os_localtime(&now, &tm);
unsigned r = (unsigned)(os_getpid() ^ (unsigned)now); static unsigned seq;
unsigned r = (unsigned)(os_getpid() ^ (unsigned)now) + 0x9e37u * seq++;
snprintf(out, n, "%04d%02d%02d-%02d%02d%02d-%04x", tm.tm_year + 1900, snprintf(out, n, "%04d%02d%02d-%02d%02d%02d-%04x", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
r & 0xffff); r & 0xffff);
+193
View File
@@ -0,0 +1,193 @@
#include "cst_provider_switch.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cst_ps_fetch(const char *provider, const char *api_base, const char *key,
char ids[][128], int max, char *err, size_t err_sz) {
cst_model_meta_t *m = calloc((size_t)(max > 0 ? max : 1), sizeof(*m));
if (!m) {
snprintf(err, err_sz, "out of memory");
return -1;
}
int r = cst_llm_list_models_meta(api_base, key, m, max, err, err_sz);
if (r >= 0)
cst_models_cache_save(provider, api_base, m, r);
for (int i = 0; i < r; i++)
snprintf(ids[i], 128, "%s", m[i].id);
free(m);
return r;
}
int cst_ps_cached(const char *provider, char ids[][128], int max, int *fresh) {
*fresh = 0;
cst_model_meta_t *m = calloc((size_t)(max > 0 ? max : 1), sizeof(*m));
if (!m)
return -1;
long age = 0;
int n = cst_models_cache_load(provider, m, max, &age);
for (int i = 0; i < n; i++)
snprintf(ids[i], 128, "%s", m[i].id);
free(m);
*fresh = n > 0 && age >= 0 && age < CST_MODELS_CACHE_TTL;
return n > 0 ? n : -1;
}
const char *cst_ps_base(const cst_agent_config_t *cfg, const char *provider) {
if (cfg && strcmp(cfg->provider, provider) == 0)
return cfg->api_base;
const cst_provider_t *p = cst_provider_find(provider);
return p ? p->api_base : "";
}
int cst_ps_models(const cst_agent_config_t *cfg, int refresh,
cst_ps_model_t *out, int max, int *api_rc, char *err,
size_t err_sz) {
err[0] = 0;
*api_rc = -1;
char(*ids)[128] = calloc(CST_PS_MAX_MODELS, sizeof(*ids));
if (!ids) {
snprintf(err, err_sz, "out of memory");
return 0;
}
int fresh = 0;
int na = cst_ps_cached(cfg->provider, ids, CST_PS_MAX_MODELS, &fresh);
*api_rc = na;
if ((refresh || !fresh) && cfg->api_key[0]) {
char(*got)[128] = calloc(CST_PS_MAX_MODELS, sizeof(*got));
if (got) {
int r = cst_ps_fetch(cfg->provider, cfg->api_base, cfg->api_key, got,
CST_PS_MAX_MODELS, err, err_sz);
*api_rc = r;
if (r >= 0) {
memcpy(ids, got, (size_t)r * sizeof(*ids));
na = r;
}
free(got);
}
}
int n = 0;
for (int i = 0; i < na && n < max; i++, n++) {
snprintf(out[n].id, sizeof(out[n].id), "%s", ids[i]);
out[n].api = 1;
cst_model_info(cfg->provider, ids[i], &out[n].info);
}
char builtin[32][128];
int nb = cst_models_list(cfg->model, builtin, 32);
for (int i = 0; i < nb && n < max; i++) {
int dup = 0;
for (int k = 0; k < na && !dup; k++)
dup = strcmp(ids[k], builtin[i]) == 0;
if (dup)
continue;
memcpy(out[n].id, builtin[i], sizeof(out[n].id));
out[n].id[sizeof(out[n].id) - 1] = 0;
out[n].api = 0;
cst_model_info(cfg->provider, builtin[i], &out[n].info);
n++;
}
free(ids);
return n;
}
int cst_ps_verify_save(const char *provider, const char *api_base,
const char *key, char ids[][128], int max, int *nids,
char *err, size_t err_sz) {
err[0] = 0;
char(*own)[128] = NULL;
if (!ids) {
own = calloc(CST_PS_MAX_MODELS, sizeof(*own));
if (!own) {
snprintf(err, err_sz, "out of memory");
return CST_PS_UNVERIFIED | CST_PS_UNSAVED;
}
ids = own;
max = CST_PS_MAX_MODELS;
}
int r = cst_ps_fetch(provider, api_base, key, ids, max, err, err_sz);
free(own);
if (nids)
*nids = r;
if (r == CST_MODELS_AUTH)
return CST_MODELS_AUTH;
int flags = r < 0 ? CST_PS_UNVERIFIED : 0;
if (r >= 0)
err[0] = 0;
if (cst_creds_save(provider, key) != 0)
flags |= CST_PS_UNSAVED;
return flags;
}
void cst_ps_apply_provider(cst_agent_config_t *cfg, const cst_provider_t *p,
const char *key) {
cst_settings_t s;
cst_settings_load(&s);
const char *model = cst_settings_model(&s, p->name);
snprintf(cfg->provider, sizeof(cfg->provider), "%s", p->name);
snprintf(cfg->api_base, sizeof(cfg->api_base), "%s", p->api_base);
snprintf(cfg->model, sizeof(cfg->model), "%s", model ? model : p->model);
snprintf(cfg->api_key, sizeof(cfg->api_key), "%s", key);
cst_settings_remember(cfg);
}
int cst_ps_switch_provider(cst_agent_config_t *cfg, const char *name,
const char *key, char *err, size_t err_sz) {
err[0] = 0;
const cst_provider_t *p = name ? cst_provider_find(name) : NULL;
if (!p) {
snprintf(err, err_sz, "unknown provider '%.64s'", name ? name : "");
return CST_PS_UNKNOWN;
}
char k[512];
int flags = 0;
char(*ids)[128] = calloc(CST_PS_MAX_MODELS, sizeof(*ids));
int nids = -1;
if (key && key[0]) {
snprintf(k, sizeof(k), "%s", key);
flags = cst_ps_verify_save(p->name, p->api_base, k, ids,
ids ? CST_PS_MAX_MODELS : 0, &nids, err,
err_sz);
if (flags < 0) {
memset(k, 0, sizeof(k));
free(ids);
return flags;
}
} else if (cst_creds_resolve(p->name, k, sizeof(k), NULL) != 0) {
free(ids);
snprintf(err, err_sz, "%s needs an API key", p->name);
return CST_PS_NEED_KEY;
}
cst_ps_apply_provider(cfg, p, k);
memset(k, 0, sizeof(k));
if (!cfg->model[0] && ids) {
/* a router preset: the first model the API lists */
int fresh = 0;
if (nids <= 0)
nids = cst_ps_cached(p->name, ids, CST_PS_MAX_MODELS, &fresh);
if (nids <= 0) {
char e2[256];
nids = cst_ps_fetch(p->name, cfg->api_base, cfg->api_key, ids,
CST_PS_MAX_MODELS, e2, sizeof(e2));
}
if (nids > 0) {
snprintf(cfg->model, sizeof(cfg->model), "%s", ids[0]);
cst_settings_remember(cfg);
}
}
free(ids);
return flags;
}
int cst_ps_set_key(cst_agent_config_t *cfg, const char *key, char *err,
size_t err_sz) {
if (!key || !key[0]) {
snprintf(err, err_sz, "empty key");
return CST_PS_NEED_KEY;
}
int r = cst_ps_verify_save(cfg->provider, cfg->api_base, key, NULL, 0, NULL,
err, err_sz);
if (r >= 0)
snprintf(cfg->api_key, sizeof(cfg->api_key), "%s", key);
return r;
}
+60
View File
@@ -8,6 +8,7 @@
#include "cJSON.h" #include "cJSON.h"
#include "cst_agent.h" #include "cst_agent.h"
#include "cst_attach.h" #include "cst_attach.h"
#include "cst_util.h"
#include <pthread.h> #include <pthread.h>
#include <stdio.h> #include <stdio.h>
@@ -409,3 +410,62 @@ int cst_session_rewrite(cst_session_t *s, const cst_message_t *msgs, int n) {
free(copy); free(copy);
return rc; return rc;
} }
int cst_message_is_tool_result(const cst_message_t *m) {
return m && (m->role == CST_ROLE_TOOL ||
(m->role == CST_ROLE_USER && m->tool_call_id[0]));
}
static void md_fence(cst_buf_t *b, const char *s, size_t max) {
size_t n = strlen(s);
if (n > max)
n = cst_utf8_floor(s, max);
cst_buf_puts(b, "````\n");
cst_buf_append(b, s, n);
cst_buf_puts(b, n < strlen(s) ? "\n…(truncated)\n````\n\n" : "\n````\n\n");
}
char *cst_session_export_md(cst_session_t *s, const char *title,
const char *sid, const char *model) {
if (!s)
return NULL;
cst_buf_t b = {0};
cst_buf_printf(&b, "# %s\n\nsession `%s` · model `%s`\n\n",
title ? title : "", sid ? sid : "", model ? model : "");
cst_session_lock(s);
for (int i = 0; i < cst_session_count(s); i++) {
const cst_message_t *m = cst_session_get(s, i);
const char *c = m->content ? m->content : "";
if (m->role == CST_ROLE_SYSTEM)
continue;
if (cst_message_is_tool_result(m)) {
cst_buf_printf(&b, "**Tool result** `%s`\n\n", m->tool_name);
md_fence(&b, c, 4000);
} else if (cst_message_is_note(m)) {
cst_buf_puts(&b, "> ");
cst_buf_append(&b, c, strcspn(c, "\n"));
cst_buf_puts(&b, "\n\n");
} else if (m->role == CST_ROLE_USER) {
cst_buf_puts(&b, "## User\n\n");
cst_buf_puts(&b, c);
cst_buf_puts(&b, "\n\n");
for (int k = 0; k < m->nattach; k++) {
char d[128];
cst_attach_describe(&m->attach[k], d, sizeof(d));
cst_buf_printf(&b, "- image `%s` (%s)\n", m->attach[k].name, d);
}
if (m->nattach)
cst_buf_puts(&b, "\n");
} else {
cst_buf_puts(&b, "## Assistant\n\n");
cst_buf_puts(&b, c);
cst_buf_puts(&b, "\n\n");
if (m->tool_calls_json && m->tool_calls_json[0]) {
cst_buf_puts(&b, "**Tool calls**\n\n");
md_fence(&b, m->tool_calls_json, 4000);
}
}
}
cst_session_unlock(s);
return cst_buf_steal(&b);
}
+10
View File
@@ -488,6 +488,16 @@ char *cst_skill_read(const char *ws, const char *name, const char *file,
return cst_buf_steal(&b); return cst_buf_steal(&b);
} }
const char *cst_init_prompt(void) {
return "Analyze this repository and write an AGENTS.md file at the "
"workspace root for future coding agents. Cover: what the project "
"is, how to build, test and run it (exact commands), the directory "
"layout, coding conventions you can infer from the code, and "
"anything surprising. Explore with list_dir/glob/grep/read_file "
"before writing. Keep it under 150 lines. If AGENTS.md already "
"exists, improve it rather than starting over.";
}
char *cst_skill_prompt(const char *ws, const char *name, const char *task) { char *cst_skill_prompt(const char *ws, const char *name, const char *task) {
int code = 0; int code = 0;
char *body = cst_skill_read(ws, name, NULL, &code); char *body = cst_skill_read(ws, name, NULL, &code);
+24 -112
View File
@@ -11,6 +11,7 @@
#include "cst_mcp.h" #include "cst_mcp.h"
#include "cst_models.h" #include "cst_models.h"
#include "cst_plugins.h" #include "cst_plugins.h"
#include "cst_provider_switch.h"
#include "cst_skills.h" #include "cst_skills.h"
#include "cst_subagent.h" #include "cst_subagent.h"
#include "cst_textsel.h" #include "cst_textsel.h"
@@ -1041,10 +1042,7 @@ static int find_tool_block(tui_t *t, const char *id) {
return -1; return -1;
} }
static int msg_is_tool_result(const cst_message_t *m) { #define msg_is_tool_result cst_message_is_tool_result
return m && (m->role == CST_ROLE_TOOL ||
(m->role == CST_ROLE_USER && m->tool_call_id[0]));
}
/* Strip the "[tool …]" / "result <id> exit=N <n>" header and "end" trailer. */ /* Strip the "[tool …]" / "result <id> exit=N <n>" header and "end" trailer. */
static void tool_result_view(const char *content, const char **body, static void tool_result_view(const char *content, const char **body,
@@ -3886,46 +3884,11 @@ static void am_store(const char *provider, int r, char ids[][128],
pthread_mutex_unlock(&g_am_mu); pthread_mutex_unlock(&g_am_mu);
} }
/* GET /models; a good answer also refreshes models-cache/<provider>.json. */
static int fetch_models(const char *provider, const char *base,
const char *key, char ids[][128], int max, char *err,
size_t err_sz) {
cst_model_meta_t *m = calloc((size_t)max, sizeof(*m));
if (!m) {
snprintf(err, err_sz, "out of memory");
return -1;
}
int r = cst_llm_list_models_meta(base, key, m, max, err, err_sz);
if (r >= 0)
cst_models_cache_save(provider, base, m, r);
for (int i = 0; i < r; i++)
snprintf(ids[i], 128, "%s", m[i].id);
free(m);
return r;
}
/* The cached list for provider into ids: count, or -1; *fresh when it is
* younger than CST_MODELS_CACHE_TTL. */
static int cached_models(const char *provider, char ids[][128], int max,
int *fresh) {
*fresh = 0;
cst_model_meta_t *m = calloc((size_t)max, sizeof(*m));
if (!m)
return -1;
long age = 0;
int n = cst_models_cache_load(provider, m, max, &age);
for (int i = 0; i < n; i++)
snprintf(ids[i], 128, "%s", m[i].id);
free(m);
*fresh = n > 0 && age >= 0 && age < CST_MODELS_CACHE_TTL;
return n > 0 ? n : -1;
}
static void *probe_thread(void *arg) { static void *probe_thread(void *arg) {
probe_arg_t *a = arg; probe_arg_t *a = arg;
static char ids[AM_MAX][128]; /* one probe runs per provider switch */ static char ids[AM_MAX][128]; /* one probe runs per provider switch */
char err[256]; char err[256];
int r = fetch_models(a->provider, a->base, a->key, ids, AM_MAX, err, int r = cst_ps_fetch(a->provider, a->base, a->key, ids, AM_MAX, err,
sizeof(err)); sizeof(err));
if (r >= 0 || r == CST_MODELS_AUTH || !a->have_cache) if (r >= 0 || r == CST_MODELS_AUTH || !a->have_cache)
am_store(a->provider, r, ids, err); am_store(a->provider, r, ids, err);
@@ -3937,23 +3900,13 @@ static void *probe_thread(void *arg) {
return NULL; return NULL;
} }
/* Base URL for a provider: the live config for the current one (it may be
* overridden), else the preset. */
static const char *provider_base(const tui_t *t, const char *provider) {
const cst_agent_config_t *cfg = cst_agent_config(t->agent);
if (cfg && strcmp(cfg->provider, provider) == 0)
return cfg->api_base;
const cst_provider_t *p = cst_provider_find(provider);
return p ? p->api_base : "";
}
static void start_probe(tui_t *t) { static void start_probe(tui_t *t) {
const cst_agent_config_t *cfg = cst_agent_config(t->agent); const cst_agent_config_t *cfg = cst_agent_config(t->agent);
if (!cfg || !cfg->api_key[0] || g_am_threads > 0) if (!cfg || !cfg->api_key[0] || g_am_threads > 0)
return; return;
static char ids[AM_MAX][128]; static char ids[AM_MAX][128];
int fresh = 0; int fresh = 0;
int nc = cached_models(cfg->provider, ids, AM_MAX, &fresh); int nc = cst_ps_cached(cfg->provider, ids, AM_MAX, &fresh);
pthread_mutex_lock(&g_am_mu); pthread_mutex_lock(&g_am_mu);
snprintf(g_am.provider, sizeof(g_am.provider), "%s", cfg->provider); snprintf(g_am.provider, sizeof(g_am.provider), "%s", cfg->provider);
pthread_mutex_unlock(&g_am_mu); pthread_mutex_unlock(&g_am_mu);
@@ -4039,13 +3992,14 @@ static int obtain_key(tui_t *t, const char *provider, char *out, size_t n,
return 0; return 0;
char dir[1024] = "the config directory"; char dir[1024] = "the config directory";
os_config_dir(dir, sizeof(dir)); os_config_dir(dir, sizeof(dir));
const char *base = provider_base(t, provider); const char *base = cst_ps_base(cst_agent_config(t->agent), provider);
char title[128], hint[1300]; char title[128], hint[1300];
snprintf(title, sizeof(title), "API key for %s", provider); snprintf(title, sizeof(title), "API key for %s", provider);
snprintf(hint, sizeof(hint), "%.200s · saved to %.900s/credentials (only you " snprintf(hint, sizeof(hint), "%.200s · saved to %.900s/credentials (only you "
"can read it)", "can read it)",
base, dir); base, dir);
char note[300] = ""; char note[300] = "";
int flags;
for (;;) { for (;;) {
if (secret_input_run(t, title, hint, out, n) != 0) if (secret_input_run(t, title, hint, out, n) != 0)
return -1; return -1;
@@ -4053,8 +4007,10 @@ static int obtain_key(tui_t *t, const char *provider, char *out, size_t n,
draw_status(t); draw_status(t);
static char ids[AM_MAX][128]; static char ids[AM_MAX][128];
char err[256]; char err[256];
int r = fetch_models(provider, base, out, ids, AM_MAX, err, sizeof(err)); int r = -1;
if (r == CST_MODELS_AUTH) { flags = cst_ps_verify_save(provider, base, out, ids, AM_MAX, &r, err,
sizeof(err));
if (flags == CST_MODELS_AUTH) {
snprintf(hint, sizeof(hint), "%s rejected that key (%.200s) — paste " snprintf(hint, sizeof(hint), "%s rejected that key (%.200s) — paste "
"another one", "another one",
base, err); base, err);
@@ -4064,13 +4020,13 @@ static int obtain_key(tui_t *t, const char *provider, char *out, size_t n,
snprintf(g_am.provider, sizeof(g_am.provider), "%s", provider); snprintf(g_am.provider, sizeof(g_am.provider), "%s", provider);
pthread_mutex_unlock(&g_am_mu); pthread_mutex_unlock(&g_am_mu);
am_store(provider, r, ids, err); am_store(provider, r, ids, err);
if (r < 0) if (flags & CST_PS_UNVERIFIED)
snprintf(note, sizeof(note), "could not verify the key (%.200s); " snprintf(note, sizeof(note), "could not verify the key (%.200s); "
"saved anyway", "saved anyway",
err); err);
break; break;
} }
if (cst_creds_save(provider, out) != 0) if (flags & CST_PS_UNSAVED)
set_status(t, "warning: could not save the key; it is used for this run " set_status(t, "warning: could not save the key; it is used for this run "
"only"); "only");
else if (note[0]) else if (note[0])
@@ -4302,7 +4258,7 @@ static void cmd_model(tui_t *t, char *arg, int *quit) {
set_status(t, "fetching the model list…"); set_status(t, "fetching the model list…");
draw_status(t); draw_status(t);
char err[256]; char err[256];
na = fetch_models(cfg->provider, cfg->api_base, cfg->api_key, names, na = cst_ps_fetch(cfg->provider, cfg->api_base, cfg->api_key, names,
AM_MAX, err, sizeof(err)); AM_MAX, err, sizeof(err));
pthread_mutex_lock(&g_am_mu); pthread_mutex_lock(&g_am_mu);
snprintf(g_am.provider, sizeof(g_am.provider), "%s", cfg->provider); snprintf(g_am.provider, sizeof(g_am.provider), "%s", cfg->provider);
@@ -4436,15 +4392,8 @@ static void cmd_provider(tui_t *t, char *arg, int *quit) {
push_system_line(t, "(provider unchanged: %s needs an API key)", p->name); push_system_line(t, "(provider unchanged: %s needs an API key)", p->name);
return; return;
} }
cst_settings_t s; cst_ps_apply_provider(cfg, p, key);
cst_settings_load(&s);
const char *model = cst_settings_model(&s, p->name);
snprintf(cfg->provider, sizeof(cfg->provider), "%s", p->name);
snprintf(cfg->api_base, sizeof(cfg->api_base), "%s", p->api_base);
snprintf(cfg->model, sizeof(cfg->model), "%s", model ? model : p->model);
snprintf(cfg->api_key, sizeof(cfg->api_key), "%s", key);
memset(key, 0, sizeof(key)); memset(key, 0, sizeof(key));
cst_settings_remember(cfg);
push_system_line(t, "(provider → %s · %s · model %s)", p->name, p->api_base, push_system_line(t, "(provider → %s · %s · model %s)", p->name, p->api_base,
cfg->model); cfg->model);
if (am_models(p->name, NULL, 0) < 0) if (am_models(p->name, NULL, 0) < 0)
@@ -4822,12 +4771,6 @@ static void cmd_diff(tui_t *t, char *arg, int *quit) {
free(df.out); free(df.out);
} }
static void md_fence(FILE *fp, const char *s, size_t max) {
size_t n = strlen(s);
fprintf(fp, "````\n%.*s%s\n````\n\n", (int)(n > max ? max : n), s,
n > max ? "\n…(truncated)" : "");
}
static void cmd_export(tui_t *t, char *arg, int *quit) { static void cmd_export(tui_t *t, char *arg, int *quit) {
(void)quit; (void)quit;
const cst_agent_config_t *cfg = cst_agent_config(t->agent); const cst_agent_config_t *cfg = cst_agent_config(t->agent);
@@ -4847,44 +4790,20 @@ static void cmd_export(tui_t *t, char *arg, int *quit) {
*sl = 0; *sl = 0;
os_mkdir_p(dir, 0755); os_mkdir_p(dir, 0755);
} }
FILE *fp = fopen(path, "wb"); char *md = cst_session_export_md(cst_agent_session(t->agent), t->title, sid,
cfg->model);
FILE *fp = md ? fopen(path, "wb") : NULL;
if (!fp) { if (!fp) {
free(md);
push_system_line(t, "Error: cannot write %s", path); push_system_line(t, "Error: cannot write %s", path);
return; return;
} }
fprintf(fp, "# %s\n\nsession `%s` · model `%s`\n\n", t->title, sid, fputs(md, fp);
cfg->model); free(md);
cst_session_t *s = cst_agent_session(t->agent); if (fclose(fp) != 0) {
cst_session_lock(s); push_system_line(t, "Error: cannot write %s", path);
for (int i = 0; i < cst_session_count(s); i++) { return;
const cst_message_t *m = cst_session_get(s, i);
const char *c = m->content ? m->content : "";
if (m->role == CST_ROLE_SYSTEM)
continue;
if (msg_is_tool_result(m)) {
fprintf(fp, "**Tool result** `%s`\n\n", m->tool_name);
md_fence(fp, c, 4000);
} else if (cst_message_is_note(m)) {
fprintf(fp, "> %.*s\n\n", (int)strcspn(c, "\n"), c);
} else if (m->role == CST_ROLE_USER) {
fprintf(fp, "## User\n\n%s\n\n", c);
for (int k = 0; k < m->nattach; k++) {
char d[128];
cst_attach_describe(&m->attach[k], d, sizeof(d));
fprintf(fp, "- image `%s` (%s)\n", m->attach[k].name, d);
}
if (m->nattach)
fputc('\n', fp);
} else {
fprintf(fp, "## Assistant\n\n%s\n\n", c);
if (m->tool_calls_json && m->tool_calls_json[0]) {
fprintf(fp, "**Tool calls**\n\n");
md_fence(fp, m->tool_calls_json, 4000);
}
}
} }
cst_session_unlock(s);
fclose(fp);
push_system_line(t, "(exported to %s)", path); push_system_line(t, "(exported to %s)", path);
} }
@@ -5061,14 +4980,7 @@ static void cmd_init(tui_t *t, char *arg, int *quit) {
(void)arg; (void)arg;
(void)quit; (void)quit;
free(t->pending_prompt); free(t->pending_prompt);
t->pending_prompt = xstrdup( t->pending_prompt = xstrdup(cst_init_prompt());
"Analyze this repository and write an AGENTS.md file at the workspace "
"root for future coding agents. Cover: what the project is, how to "
"build, test and run it (exact commands), the directory layout, coding "
"conventions you can infer from the code, and anything surprising. "
"Explore with list_dir/glob/grep/read_file before writing. Keep it "
"under 150 lines. If AGENTS.md already exists, improve it rather than "
"starting over.");
} }
static void cmd_compact(tui_t *t, char *arg, int *quit) { static void cmd_compact(tui_t *t, char *arg, int *quit) {
+20
View File
@@ -99,6 +99,26 @@ size_t cst_utf8_floor(const char *s, size_t n) {
return i - 1; /* sequence incomplete: cut before lead byte */ return i - 1; /* sequence incomplete: cut before lead byte */
} }
char *cst_utf8_hold_feed(cst_utf8_hold_t *h, const char *s, size_t n,
size_t *out_len) {
size_t have = h->n;
char *all = malloc(have + n + 1);
if (!all)
return NULL;
memcpy(all, h->b, have);
if (n)
memcpy(all + have, s, n);
size_t len = have + n;
size_t cut = cst_utf8_floor(all, len);
if (len - cut > sizeof(h->b))
cut = len;
h->n = len - cut;
memcpy(h->b, all + cut, h->n);
all[cut] = 0;
*out_len = cut;
return all;
}
static size_t utf8_seq_ok(const unsigned char *p, size_t left) { static size_t utf8_seq_ok(const unsigned char *p, size_t left) {
unsigned char c = p[0]; unsigned char c = p[0];
size_t need; size_t need;
+1215 -43
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -280,8 +280,38 @@ static void test_sanitize(void) {
} }
} }
/* Streamed deltas cut anywhere must reach the browser as whole characters. */
static void test_utf8_hold(void) {
const char *src = "思考:先读 main.c,再改 😀 emoji。";
size_t len = strlen(src);
for (size_t step = 1; step <= 5; step++) {
cst_utf8_hold_t h = {0};
cst_buf_t out = {0};
for (size_t i = 0; i < len; i += step) {
size_t n = len - i < step ? len - i : step;
size_t got = 0;
char *piece = cst_utf8_hold_feed(&h, src + i, n, &got);
CHECK(piece != NULL);
CHECK(h.n < 4);
CHECK(cst_utf8_valid(piece, got));
CHECK(cst_buf_append(&out, piece, got) == 0);
free(piece);
}
CHECK(h.n == 0);
CHECK(out.len == len && memcmp(out.buf, src, len) == 0);
cst_buf_free(&out);
}
/* a stray continuation byte is not held forever */
cst_utf8_hold_t h = {0};
size_t got = 0;
char *piece = cst_utf8_hold_feed(&h, "\x80\x80\x80\x80", 4, &got);
CHECK(piece && got == 4 && h.n == 0);
free(piece);
}
int main(void) { int main(void) {
CHECK(os_net_init() == 0); CHECK(os_net_init() == 0);
test_utf8_hold();
test_query(); test_query();
test_sanitize(); test_sanitize();
test_http(); test_http();
+1385 -115
View File
File diff suppressed because it is too large Load Diff
+11 -2
View File
@@ -69,6 +69,7 @@
<svg class="i"><use href="#i-refresh"/></svg> <svg class="i"><use href="#i-refresh"/></svg>
</button> </button>
</div> </div>
<input id="sess-search" class="sess-search" type="search" placeholder="搜索会话" autocomplete="off">
<div id="sessions-list" class="sessions"></div> <div id="sessions-list" class="sessions"></div>
<div class="side-foot"> <div class="side-foot">
@@ -133,6 +134,11 @@
<footer id="composer"> <footer id="composer">
<div id="pending" class="pending" hidden></div> <div id="pending" class="pending" hidden></div>
<div id="edit-bar" class="edit-bar" hidden>
<span>编辑上一条消息:发送后替换它并重新回答(文件改动保留,需要时先撤销)</span>
<span class="grow"></span>
<button id="btn-edit-cancel" class="link">取消</button>
</div>
<!-- permission gate: inline, the turn really is waiting on it --> <!-- permission gate: inline, the turn really is waiting on it -->
<div id="gate" class="gate" hidden> <div id="gate" class="gate" hidden>
@@ -146,8 +152,9 @@
<div class="gate-row" id="gate-buttons"></div> <div class="gate-row" id="gate-buttons"></div>
</div> </div>
<div id="slash" class="slash" role="listbox" hidden></div>
<div class="box"> <div class="box">
<textarea id="input" rows="1" placeholder="给 CST-Agent 派个任务…"></textarea> <textarea id="input" rows="1" placeholder="给 CST-Agent 派个任务…(/ 打开命令,F1 看快捷键)"></textarea>
<div class="box-row"> <div class="box-row">
<button id="btn-plus" class="icon att" title="添加图片或计划模式"> <button id="btn-plus" class="icon att" title="添加图片或计划模式">
<svg class="i"><use href="#i-plus"/></svg> <svg class="i"><use href="#i-plus"/></svg>
@@ -191,7 +198,8 @@
</section> </section>
<section class="card" id="card-files"> <section class="card" id="card-files">
<h4>文件改动 <span class="badge" id="files-count">0</span></h4> <h4>文件改动 <span class="badge" id="files-count">0</span>
<span class="grow"></span><button id="btn-diff" class="link" title="git status + git diff">查看 diff</button></h4>
<div id="files-body" class="muted">本轮还没有改动文件。</div> <div id="files-body" class="muted">本轮还没有改动文件。</div>
</section> </section>
@@ -208,6 +216,7 @@
<div id="backdrop"></div> <div id="backdrop"></div>
<div id="pop" class="pop" hidden></div> <div id="pop" class="pop" hidden></div>
<div id="modal" hidden><div id="modal-box"></div></div> <div id="modal" hidden><div id="modal-box"></div></div>
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
<script> <script>
/* Layout is decided here, before app.js runs and before the first paint: the /* Layout is decided here, before app.js runs and before the first paint: the
* rail must not flash open and then fold, and a broken script further down can * rail must not flash open and then fold, and a broken script further down can
+184 -4
View File
@@ -339,7 +339,7 @@ body.no-side #side { pointer-events: none; }
background: var(--bg-lift); border-radius: 18px 18px 6px 18px; background: var(--bg-lift); border-radius: 18px 18px 6px 18px;
padding: 9px 15px; max-width: 76%; white-space: pre-wrap; word-break: break-word; padding: 9px 15px; max-width: 76%; white-space: pre-wrap; word-break: break-word;
} }
.msg.error .body { color: var(--danger); } .msg.error .body { color: var(--danger); white-space: pre-wrap; }
.body > :first-child, .live-html > :first-child { margin-top: 0; } .body > :first-child, .live-html > :first-child { margin-top: 0; }
.body > :last-child, .live-html > :last-child { margin-bottom: 0; } .body > :last-child, .live-html > :last-child { margin-bottom: 0; }
.body h1, .body h2, .body h3, .body h4 { line-height: 1.35; margin: 1.1em 0 .5em; } .body h1, .body h2, .body h3, .body h4 { line-height: 1.35; margin: 1.1em 0 .5em; }
@@ -380,7 +380,8 @@ body.no-side #side { pointer-events: none; }
.turn-meta details > summary { cursor: pointer; list-style: none; color: var(--fg-faint); font-size: 12px; transition: color var(--t-fast); } .turn-meta details > summary { cursor: pointer; list-style: none; color: var(--fg-faint); font-size: 12px; transition: color var(--t-fast); }
.turn-meta details > summary::-webkit-details-marker { display: none; } .turn-meta details > summary::-webkit-details-marker { display: none; }
.turn-meta details > summary:hover { color: var(--fg-dim); } .turn-meta details > summary:hover { color: var(--fg-dim); }
.msg-actions { display: flex; gap: 2px; padding: 4px 0 0 36px; opacity: 0; transition: opacity var(--t) var(--ease); } .msg:has(> .msg-actions) { flex-wrap: wrap; row-gap: 0; }
.msg-actions { display: flex; flex-basis: 100%; gap: 2px; padding: 4px 0 0 36px; opacity: 0; transition: opacity var(--t) var(--ease); }
.msg:hover .msg-actions, .msg-actions:focus-within { opacity: 1; } .msg:hover .msg-actions, .msg-actions:focus-within { opacity: 1; }
.msg-actions button { .msg-actions button {
height: 26px; padding: 0 9px; border-radius: 8px; color: var(--fg-faint); font-size: 12px; height: 26px; padding: 0 9px; border-radius: 8px; color: var(--fg-faint); font-size: 12px;
@@ -425,6 +426,19 @@ body.no-side #side { pointer-events: none; }
} }
.step-line.bad .phase, .step-line.bad .name { color: var(--danger); } .step-line.bad .phase, .step-line.bad .name { color: var(--danger); }
.step-line.done .phase::before { content: "✓"; } .step-line.done .phase::before { content: "✓"; }
.step-line.bad .phase::before { content: "✕"; }
/* a sub-agent's latest steps, next to its task */
.step-line .step-detail {
flex: 0 1 40%; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-family: var(--mono); font-size: 11.5px; color: var(--fg-faint);
}
.step-line.done .step-detail { display: none; }
/* "[cst] plan mode is now ON" and other engine notes in the history */
.note-line {
padding: 6px 0 2px 36px; font-size: 12px; color: var(--fg-faint);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.note-line::before { content: "· "; }
.step-body { padding: 0 0 6px; animation: fade-in var(--t) var(--ease) both; } .step-body { padding: 0 0 6px; animation: fade-in var(--t) var(--ease) both; }
.step-out, .step-args-full { .step-out, .step-args-full {
font-family: var(--mono); font-size: 12px; background: var(--bg-code); font-family: var(--mono); font-size: 12px; background: var(--bg-code);
@@ -448,6 +462,71 @@ body.no-side #side { pointer-events: none; }
#composer > * { max-width: 760px; margin: 0 auto; } #composer > * { max-width: 760px; margin: 0 auto; }
.pending { display: flex; flex-wrap: wrap; gap: 8px; padding: 0 0 8px; } .pending { display: flex; flex-wrap: wrap; gap: 8px; padding: 0 0 8px; }
.pending .chip { background: var(--bg-soft); border-color: var(--line); } .pending .chip { background: var(--bg-soft); border-color: var(--line); }
.edit-bar {
display: flex; align-items: center; gap: 8px; padding: 6px 10px; margin-bottom: 8px;
border-radius: 10px; border: 1px solid var(--line); background: var(--bg-soft);
color: var(--fg-dim); font-size: 12.5px;
}
.edit-bar[hidden] { display: none; }
.msg.user .msg-actions { justify-content: flex-end; padding-left: 0; }
.sess-search {
width: calc(100% - 8px); margin: 0 4px 8px; height: 30px; padding: 0 10px;
border-radius: 9px; border: 1px solid var(--line); background: var(--bg-soft);
color: var(--fg); font-size: 13px;
}
.sess-item { cursor: pointer; }
#modal-box .sess-list { max-height: min(56vh, 520px); overflow-y: auto; margin: 4px 0 10px; }
#modal-box .sess button { flex: 0 0 auto; }
.sess-item .more {
flex: 0 0 auto; align-self: center; width: 22px; height: 22px; border-radius: 6px;
display: grid; place-items: center; color: var(--fg-faint); opacity: 0;
transition: opacity var(--t-fast), background var(--t-fast);
}
.sess-item:hover .more, .sess-item .more:focus-visible { opacity: 1; }
.sess-item .more:hover { background: var(--bg-hover); color: var(--fg); }
.sess-item .more .i { width: 16px; height: 16px; }
#modal-box .sess button.danger { color: var(--danger, #e5484d); }
button.fstat { width: 100%; text-align: left; border-radius: 7px; transition: background var(--t-fast); }
button.fstat:hover { background: var(--bg-hover); }
.danger-text { color: var(--danger); }
#modal-box.wide { width: min(980px, 100%); }
#modal-box h4.sub { margin: 16px 0 6px; font-size: 13px; color: var(--fg-dim); font-weight: 650; }
#modal-box .field select, #modal-box .field input[type=number] {
flex: 1 1 auto; min-width: 150px; background: var(--bg-lift); color: var(--fg);
border: 1px solid var(--line); border-radius: 10px; padding: 7px 10px; outline: none;
}
#modal-box .field > span { width: 84px; }
#modal-box .checks { display: flex; flex-wrap: wrap; gap: 14px; }
#modal-box .check { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; }
#modal-box .tool-list { max-height: 34vh; overflow-y: auto; border: 1px solid var(--line); border-radius: 10px; padding: 4px; }
#modal-box .tool-row {
display: flex; align-items: center; gap: 8px; padding: 5px 6px; border-radius: 7px;
font-size: 12.5px; cursor: pointer;
}
#modal-box .tool-row:hover { background: var(--bg-hover); }
#modal-box .tool-row.dim code { opacity: .55; }
#modal-box .tool-row code { font-family: var(--mono); font-size: 12px; flex: 0 0 auto; }
#modal-box .tool-row .perm { flex: 0 0 auto; color: var(--fg-faint); font-size: 11px; border: 1px solid var(--line); border-radius: 6px; padding: 0 5px; }
#modal-box .tool-row .desc { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--fg-dim); }
#modal-box .diff-files { display: flex; flex-direction: column; gap: 1px; max-height: 24vh; overflow-y: auto; margin-bottom: 10px; }
#modal-box .diff-file {
display: flex; gap: 10px; align-items: center; text-align: left; padding: 5px 8px;
border-radius: 7px; font-size: 12.5px;
}
#modal-box .diff-file:hover { background: var(--bg-hover); }
#modal-box .diff-file.on { background: var(--accent-weak); }
#modal-box .diff-file .st { flex: 0 0 52px; color: var(--fg-faint); font-size: 11.5px; }
#modal-box .diff-file .p { font-family: var(--mono); overflow-wrap: anywhere; }
pre.diff {
margin: 0; padding: 10px 0; max-height: 52vh; overflow: auto; border-radius: 10px;
background: var(--bg-soft); border: 1px solid var(--line);
font-family: var(--mono); font-size: 12px; line-height: 1.5;
}
pre.diff span { display: block; padding: 0 12px; white-space: pre; min-height: 1.5em; }
pre.diff .add { color: var(--text-success); background: color-mix(in srgb, var(--text-success) 10%, transparent); }
pre.diff .del { color: var(--text-error); background: color-mix(in srgb, var(--text-error) 10%, transparent); }
pre.diff .hunk { color: var(--accent); }
pre.diff .h { color: var(--fg-faint); font-weight: 600; }
.box { .box {
border: 1px solid var(--border-medium); border-radius: var(--radius-lg); border: 1px solid var(--border-medium); border-radius: var(--radius-lg);
@@ -546,7 +625,54 @@ body.no-side #side { pointer-events: none; }
.pop-input button:active { transform: scale(.96); } .pop-input button:active { transform: scale(.96); }
.kv { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 5px 10px; font-size: 13px; } .kv { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 5px 10px; font-size: 13px; }
.kv span { color: var(--fg-dim); } .kv span { color: var(--fg-dim); }
.kv b { font-variant-numeric: tabular-nums; font-weight: 600; } .kv b { font-variant-numeric: tabular-nums; font-weight: 600; min-width: 0; overflow-wrap: anywhere; text-align: right; }
.pop { max-height: calc(100vh - 16px); overflow-y: auto; }
.pop:has(.pop-list) { min-width: min(360px, 94vw); max-width: min(440px, 94vw); }
.pop-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.pop-list { max-height: min(46vh, 420px); overflow-y: auto; }
.pop-list .pop-item .pt { overflow-wrap: anywhere; font-family: var(--mono); font-size: 12.5px; }
.pop-empty { padding: 10px; color: var(--fg-faint); font-size: 12.5px; }
.pop-note { padding: 2px 10px 6px; color: var(--fg-faint); font-size: 11.5px; line-height: 1.45; }
.pop-note:empty { display: none; }
.pop-note.bad { color: var(--danger); }
.pop-note.warn { color: var(--warn); }
.pop-item.dim { opacity: .55; }
button.link { color: var(--link); padding: 0 4px; font-size: inherit; text-decoration: underline; }
.ok-text { color: var(--text-success); }
.warn-text { color: var(--warn); }
/* providers and the key dialog */
#modal-box .prov {
display: flex; align-items: center; gap: 10px; padding: 9px 8px;
border-bottom: 1px solid var(--line); border-radius: 8px;
}
#modal-box .prov.on { background: var(--accent-weak); }
#modal-box .prov .pm { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
#modal-box .prov .pm span { overflow-wrap: anywhere; }
#modal-box .prov-acts button {
height: 30px; padding: 0 12px; border-radius: 9px; font-weight: 600; font-size: 13px;
border: 1px solid var(--line-strong); background: var(--bg-lift); white-space: nowrap;
}
#modal-box .prov-acts button.ok { background: var(--accent); color: var(--accent-fg); border-color: transparent; }
#modal-box .key-input {
width: 100%; margin-top: 12px; background: var(--bg-lift); border: 1px solid var(--line);
border-radius: 10px; padding: 9px 11px; outline: none; font-family: var(--mono);
}
#modal-box .key-input:focus { border-color: var(--accent-line); }
#modal-box .key-err { min-height: 18px; margin-top: 6px; color: var(--danger); font-size: 12.5px; }
/* one line of feedback for anything that failed or needs a look */
.toast {
position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); z-index: 60;
max-width: min(560px, 92vw); padding: 10px 14px; border-radius: 12px;
background: var(--main-surface-tertiary); border: 1px solid var(--border-medium);
box-shadow: var(--shadow); font-size: 13px; line-height: 1.45; overflow-wrap: anywhere;
animation: fade-up 160ms var(--ease) both;
}
.toast.err { border-color: color-mix(in srgb, var(--danger) 55%, transparent); color: var(--danger); }
.toast.warn { border-color: color-mix(in srgb, var(--warn) 55%, transparent); color: var(--warn); }
.toast.ok { border-color: var(--accent-line); color: var(--accent); }
.toast[hidden] { display: none; }
/* --- right panel ---------------------------------------------------------- */ /* --- right panel ---------------------------------------------------------- */
/* the right panel mirrors the rail: fixed-width contents, clipped by the track, /* the right panel mirrors the rail: fixed-width contents, clipped by the track,
@@ -612,6 +738,60 @@ body.no-panel #panel { pointer-events: none; }
#modal-box .sess .id { font-family: var(--mono); font-size: 11.5px; color: var(--fg-faint); } #modal-box .sess .id { font-family: var(--mono); font-size: 11.5px; color: var(--fg-faint); }
#modal-box .sess .t { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13.5px; } #modal-box .sess .t { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13.5px; }
/* --- commands: the list over the composer, the palette, the help sheet ---- */
#composer { position: relative; }
.slash {
position: absolute; left: 20px; right: 20px; bottom: calc(100% - 6px); z-index: 20;
max-height: min(46vh, 360px); overflow-y: auto; padding: 5px;
background: var(--main-surface-tertiary); border: 1px solid var(--border-medium);
border-radius: 14px; box-shadow: var(--shadow); animation: pop-in 140ms var(--ease) both;
}
.slash[hidden] { display: none; }
.slash-item, .palette-item {
display: flex; align-items: baseline; gap: 10px; width: 100%; padding: 7px 10px;
border-radius: 9px; text-align: left; font-size: 13px;
}
.slash-item.on, .palette-item.on { background: var(--accent-weak); }
.slash-item:hover, .palette-item:hover { background: var(--bg-hover); }
.slash-item code, .palette-item code { font-family: var(--mono); font-size: 12.5px; color: var(--fg); flex: 0 0 auto; }
.slash-item.on code, .palette-item.on code { color: var(--accent); }
.slash-item .hint { font-family: var(--mono); font-size: 11.5px; color: var(--fg-faint); flex: 0 0 auto; }
.slash-item .desc, .palette-item .desc {
flex: 1 1 auto; min-width: 0; color: var(--fg-dim); font-size: 12.5px;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
#modal-box .palette-list { max-height: min(52vh, 460px); overflow-y: auto; margin-top: 8px; }
kbd {
font-family: var(--mono); font-size: 11px; color: var(--fg-dim); white-space: nowrap;
border: 1px solid var(--line-strong); border-bottom-width: 2px; border-radius: 6px; padding: 1px 6px;
background: var(--bg-soft);
}
.palette-item kbd { flex: 0 0 auto; }
#modal-box .keys-grid {
display: grid; grid-template-columns: max-content 1fr; gap: 7px 14px; align-items: baseline;
font-size: 13px;
}
#modal-box .keys-grid kbd { justify-self: start; }
#modal-box .keys-grid.cmds code { font-family: var(--mono); font-size: 12.5px; }
#modal-box .keys-grid span { color: var(--fg-dim); }
#modal-box .ext-list { display: flex; flex-direction: column; gap: 2px; }
#modal-box .ext-row {
display: flex; align-items: center; gap: 10px; padding: 7px 8px; border-radius: 8px;
border-bottom: 1px solid var(--line);
}
#modal-box .ext-row .pm { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
#modal-box .ext-row .pm > div:last-child:not(.ext-title) { overflow-wrap: anywhere; }
#modal-box .ext-title { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; font-size: 13.5px; }
#modal-box .ext-badge {
font-size: 11px; border: 1px solid var(--line-strong); border-radius: 6px; padding: 0 6px; color: var(--fg-dim);
}
#modal-box .ext-badge.ok { color: var(--accent); border-color: var(--accent-line); }
#modal-box .ext-badge.bad { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 55%, transparent); }
#modal-box .ext-row > button {
flex: 0 0 auto; height: 30px; padding: 0 12px; border-radius: 9px; font-weight: 600; font-size: 13px;
border: 1px solid var(--line-strong); background: var(--bg-lift); white-space: nowrap;
}
/* --- narrow screens: rail and panel become drawers ------------------------ */ /* --- narrow screens: rail and panel become drawers ------------------------ */
#backdrop { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); z-index: 30; display: none; animation: fade-in var(--t) var(--ease) both; } #backdrop { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); z-index: 30; display: none; animation: fade-in var(--t) var(--ease) both; }
body.drawer-open #backdrop { display: block; } body.drawer-open #backdrop { display: block; }
@@ -630,7 +810,7 @@ body.drawer-open #backdrop { display: block; }
#to-bottom { bottom: 150px; right: 16px; } #to-bottom { bottom: 150px; right: 16px; }
.hero h1 { font-size: 21px; } .hero h1 { font-size: 21px; }
.msg.user .body { max-width: 88%; } .msg.user .body { max-width: 88%; }
.turn-meta, .msg-actions, .turn-steps { padding-left: 0; } .turn-meta, .msg-actions, .turn-steps, .note-line { padding-left: 0; }
} }
@media (min-width: 901px) { #backdrop { display: none !important; } } @media (min-width: 901px) { #backdrop { display: none !important; } }