From 0c6b0549e792d063bc0889ed9bb6e4b534f10ef8 Mon Sep 17 00:00:00 2001 From: rock-solid-sites Date: Wed, 13 May 2026 23:57:29 +0200 Subject: [PATCH 001/129] docs: translate configuration.md and mcp.md to English MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit These docs ship in Chinese only. This adds English translations for the same content. Translation was done in DeepSeek web chat (free, off-API) by a non-Chinese-speaking contributor — please verify accuracy before merging. --- docs/configuration.md | 201 +++++++++++++++++++++--------------------- docs/mcp.md | 136 ++++++++++++++-------------- 2 files changed, 168 insertions(+), 169 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index f8e52c3..369f8e4 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,71 +1,71 @@ -# Deep Code 配置 +# Deep Code Configuration -## 配置层级 +## Configuration Hierarchy -配置按以下优先级顺序应用(数字较小的会被数字较大的覆盖): +Configuration is applied in the following priority order (lower-numbered sources are overridden by higher-numbered ones): -| 层级 | 配置来源 | 说明 | -| ---- | ------------ | ------------------------------------------- | -| 1 | 默认值 | 应用程序内硬编码的默认值 | -| 2 | 用户设置文件 | 当前用户的全局设置 | -| 3 | 项目设置文件 | 项目特定的设置 | -| 4 | 环境变量 | 系统范围或会话特定的变量 | +| Layer | Configuration Source | Description | +| ----- | -------------------- | ---------------------------------------------- | +| 1 | Defaults | Hardcoded defaults within the application | +| 2 | User settings file | Global settings for the current user | +| 3 | Project settings file| Project-specific settings | +| 4 | Environment variables| System-wide or session-specific variables | -## 设置文件 +## Settings File -Deep Code 使用 `settings.json` 设置文件进行持久化配置,支持两个层级的存放位置: +Deep Code uses the `settings.json` file for persistent configuration, supporting two storage locations: -| 文件类型 | 位置 | 作用范围 | -| ------------ | ---------------------------------- | ---------------------------------------------------- | -| 用户设置文件 | `~/.deepcode/settings.json` | 适用于当前用户的所有 Deep Code 会话。 | -| 项目设置文件 | `项目根目录/.deepcode/settings.json` | 仅在该特定项目中运行 Deep Code 时生效。项目设置会覆盖用户设置。 | +| File Type | Location | Scope | +| ------------------- | ----------------------------------------- | --------------------------------------------------------------------- | +| User settings file | `~/.deepcode/settings.json` | Applies to all Deep Code sessions for the current user. | +| Project settings file | `/.deepcode/settings.json` | Takes effect only when running Deep Code in that specific project. Project settings override user settings. | -### `settings.json` 中的可用设置 +### Available Settings in `settings.json` -以下是 `settings.json` 支持的全部顶层字段,以及 `env` 内部支持的子字段: +The following are all the top-level fields supported in `settings.json`, along with the sub-fields inside `env`: -| 字段 | 类型 | 说明 | -| -------------------- | --------- | ------------------------------------------------------------------- | -| `env` | object | 环境变量分组(见下方子字段表) | -| `model` | string | 模型名称。优先级高于 `env.MODEL` | -| `thinkingEnabled` | boolean | 是否启用思考模式(DeepSeek V4 系列默认启用) | -| `reasoningEffort` | string | 推理强度,可选 `"high"` 或 `"max"`(默认 `"max"`) | -| `debugLogEnabled` | boolean | 是否启用调试日志输出(默认 `false`) | -| `notify` | string | 任务完成通知脚本的完整路径(如 Slack 通知脚本) | -| `webSearchTool` | string | 自定义联网搜索脚本的完整路径 | -| `mcpServers` | object | MCP 服务器配置(键为服务名,值为 McpServerConfig 对象) | +| Field | Type | Description | +| ------------------ | ------- | --------------------------------------------------------------------------- | +| `env` | object | Group of environment variables (see sub-field table below) | +| `model` | string | Model name. Takes precedence over `env.MODEL` | +| `thinkingEnabled` | boolean | Whether to enable thinking mode (enabled by default for DeepSeek V4 series)| +| `reasoningEffort` | string | Reasoning intensity, either `"high"` or `"max"` (default `"max"`) | +| `debugLogEnabled` | boolean | Enable debug log output (default `false`) | +| `notify` | string | Full path to a task-completion notification script (e.g., Slack notification script) | +| `webSearchTool` | string | Full path to a custom web search script | +| `mcpServers` | object | MCP server configurations (keys are service names, values are McpServerConfig objects) | -#### `env` 子字段 +#### `env` Sub-fields -| 字段 | 类型 | 说明 | -| ---------- | ------ | ------------------------------------------------------------------ | -| `MODEL` | string | 模型名称。例如 `"deepseek-v4-pro"`、`"deepseek-v4-flash"` | -| `BASE_URL` | string | API 请求的基础 URL。例如 `"https://api.deepseek.com"` | -| `API_KEY` | string | API 密钥 | -| `THINKING_ENABLED` | string | 是否启用思考模式 | -| `REASONING_EFFORT` | string | 推理强度 | -| `DEBUG_LOG_ENABLED` | string | 是否启用调试日志输出 | -| `<其他任意KEY>` | string | 自定义环境变量 | +| Field | Type | Description | +| ----------------- | ------ | ---------------------------------------------------------------- | +| `MODEL` | string | Model name, e.g. `"deepseek-v4-pro"`, `"deepseek-v4-flash"` | +| `BASE_URL` | string | Base URL for API requests, e.g. `"https://api.deepseek.com"` | +| `API_KEY` | string | API key | +| `THINKING_ENABLED`| string | Enable thinking mode | +| `REASONING_EFFORT`| string | Reasoning intensity | +| `DEBUG_LOG_ENABLED`| string| Enable debug log output | +| `` | string | Custom environment variable | -#### `thinkingEnabled` — 思考模式 +#### `thinkingEnabled` — Thinking Mode -是否启用 DeepSeek 思考模式。设置为 `true` 启用、`false` 禁用。 +Whether to enable DeepSeek thinking mode. Set to `true` to enable, `false` to disable. -- 对于 `deepseek-v4-pro` 和 `deepseek-v4-flash`,思考模式**默认启用**。 -- 对于其他模型,思考模式**默认关闭**。 +- For `deepseek-v4-pro` and `deepseek-v4-flash`, thinking mode is **enabled by default**. +- For other models, thinking mode is **disabled by default**. -#### `reasoningEffort` — 推理强度 +#### `reasoningEffort` — Reasoning Intensity -当思考模式启用时,控制模型思考的深度: +When thinking mode is enabled, controls the depth of the model’s reasoning: -| 值 | 说明 | -| ------ | --------------------------------- | -| `max` | 最大推理深度(默认值) | -| `high` | 较高推理深度,token消耗相对较小 | +| Value | Description | +| ------ | --------------------------------------------------------- | +| `max` | Maximum reasoning depth (default) | +| `high` | Higher reasoning depth with relatively lower token usage | -#### `notify` — 任务完成通知 +#### `notify` — Task Completion Notification -设置一个 Shell 脚本的完整路径。当 AI 助手完成一轮任务后,会自动执行该脚本,可用于发送通知(如 Slack 消息)。 +Set a full path to a shell script. When the AI assistant finishes a round of tasks, the script is executed automatically, which can be used to send notifications (e.g., a Slack message). ```json { @@ -73,9 +73,9 @@ Deep Code 使用 `settings.json` 设置文件进行持久化配置,支持两 } ``` -#### `webSearchTool` — 自定义联网搜索 +#### `webSearchTool` — Custom Web Search -Deep Code 内置免费可用的 Web Search 工具。如果需要自定义搜索逻辑,可将 `webSearchTool` 设为一个可执行脚本的完整路径: +Deep Code has a built-in, free-to-use Web Search tool. If you need custom search logic, set `webSearchTool` to the full path of an executable script: ```json { @@ -83,16 +83,16 @@ Deep Code 内置免费可用的 Web Search 工具。如果需要自定义搜索 } ``` -脚本接收一个搜索查询参数,输出 JSON 格式的结果供 AI 使用。 +The script receives a search query as an argument and outputs results in JSON format for the AI. -#### `mcpServers` — MCP 服务器 +#### `mcpServers` — MCP Servers -MCP(Model Context Protocol)服务器配置。值是键值对,键为服务名称,值为服务器配置对象。 +Configuration for MCP (Model Context Protocol) servers. The value is a key-value pair, where the key is the service name and the value is a server configuration object. ```json { "mcpServers": { - "<服务名>": { + "": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { @@ -103,71 +103,70 @@ MCP(Model Context Protocol)服务器配置。值是键值对,键为服务 } ``` -| McpServerConfig 字段 | 类型 | 必填 | 说明 | -| -------------------- | -------- | ---- | -------------------------------------------------------------------- | -| `command` | string | 是 | 可执行文件路径或命令(如 `npx`、`node`、`python`) | -| `args` | string[] | 否 | 传递给命令的参数列表 | -| `env` | object | 否 | 传递给 MCP 服务器进程的环境变量 | +| McpServerConfig field | Type | Required | Description | +| --------------------- | -------- | -------- | ------------------------------------------------------------------------ | +| `command` | string | Yes | Executable path or command (e.g. `npx`, `node`, `python`) | +| `args` | string[] | No | List of arguments passed to the command | +| `env` | object | No | Environment variables passed to the MCP server process | -> 当 `command` 为 `npx` 时,Deep Code 会自动在参数前补充 `-y`。 +> When `command` is `npx`, Deep Code automatically prepends `-y` to the arguments. -详细 MCP 使用说明请参考 [mcp.md](mcp.md)。 +For detailed MCP usage instructions, refer to [mcp.md](mcp.md). +#### `debugLogEnabled` — Debug Log -#### `debugLogEnabled` — 调试日志 +Set to `true` to enable detailed debug logging (default `false`), useful for troubleshooting API calls and tool execution. -设为 `true` 可让程序输出详细的调试日志(默认 `false`),用于排查 API 调用和工具执行的问题。 +## Environment Variable Priority -## 环境变量优先级 +Environment variables are a common way to configure applications, especially for sensitive information (such as api-key) or settings that may change between environments. -环境变量是配置应用程序的常用方式,尤其适用于敏感信息(如 api-key)或可能在不同环境之间更改的设置。 +### Priority Principle -### 优先级原则 +Environment variable priority follows the logic of “the more specific and localized the configuration, the higher the priority”, and the override rule of “env files protect existing environment by default, system variables override env files”. (The `env` object in settings.json can be thought of as a type of env file.) -环境变量优先级遵循“越具体、越局部的配置,优先级越高”和“env文件默认保护现有环境,系统变量高于env文件”的覆盖逻辑。(settings.json的env对象可以认为是一种env文件) +Priority levels (from lowest to highest): +1. `env` defined at the top level of `settings.json` – this is a general configuration for the entire tool and all its subprocesses (global variables). Can be overridden by outer environment variables, but the environment variable KEY has the `DEEPCODE_` prefix removed. +2. `env` defined inside `mcpServers` in `settings.json` – this is the most specific configuration for a particular MCP service (local variables). Can be overridden by outer environment variables, but the KEY has the `MCP_` prefix removed. +3. Shell/system environment variables – operating system level. -优先级层级 (由低到高) -1. settings.json 外层的 env:这是针对整个工具及其所有子进程的通用配置(全局变量)。可被外层环境变量覆盖,但环境变量KEY会移除`DEEPCODE_`前缀。 -2. settings.json mcpServers 内定义的 env:这是针对特定 MCP 服务的最具体配置(局部变量)。可被外层环境变量覆盖,但环境变量KEY会移除`MCP_`前缀。 -3. Shell 环境系统变量:操作系统层面的环境变量。 +### Scenarios -### 场景 +#### 1. Setting the model’s api_key and base_url -#### 一、设置模型的api_key, base_url +Applied in the following priority order (lower-numbered sources are overridden by higher-numbered ones) – using api_key as an example: -按以下优先级顺序应用(数字较小的会被数字较大的覆盖)(以api_key为例): +1. Hardcoded default: `""` +2. User-level settings.json: `{"env": {"API_KEY": "abc123"}}` +3. Project-level settings.json: `{"env": {"API_KEY": "abc123"}}` +4. System environment variable: `DEEPCODE_API_KEY=abc123 deepcode` -1. 硬编码默认值: `""` -2. 用户级settings.json: `{"env": {"API_KEY": "abc123"}}` -3. 项目级settings.json: `{"env": {"API_KEY": "abc123"}}` -4. 系统环境变量: `DEEPCODE_API_KEY=abc123 deepcode` +#### 2. Setting model, thinkingEnabled, and reasoningEffort -#### 二、设置模型的model, thinkingEnabled, reasoningEffort +Applied in the following priority order (lower-numbered overridden by higher-numbered) – using thinkingEnabled as an example: -按以下优先级顺序应用(数字较小的会被数字较大的覆盖)(以thinkingEnabled为例): +1. Hardcoded default: `true` +2. User-level settings.json: `{"env": {"THINKING_ENABLED": "true"}}` +3. User-level settings.json: `{"thinkingEnabled": true}` +4. Project-level settings.json: `{"env": {"THINKING_ENABLED": "true"}}` +5. Project-level settings.json: `{"thinkingEnabled": true}` +6. System environment variable: `DEEPCODE_THINKING_ENABLED=true deepcode` -1. 硬编码默认值: `true` -2. 用户级settings.json: `{"env": {"THINKING_ENABLED": "true"}}` -3. 用户级settings.json: `{"thinkingEnabled": true}` -4. 项目级settings.json: `{"env": {"THINKING_ENABLED": "true"}}` -5. 项目级settings.json: `{"thinkingEnabled": true}` -6. 系统环境变量: `DEEPCODE_THINKING_ENABLED=true deepcode` +#### 3. Setting environment variables for external scripts like notify and webSearchTool -#### 三、设置启动notify, webSearchTool等外挂脚本的环境变量 +Applied in the following priority order (lower-numbered overridden by higher-numbered) – using notify as an example: -按以下优先级顺序应用(数字较小的会被数字较大的覆盖)(以notify为例): +1. Hardcoded default: `os.environ.get('WEBHOOK', '...') # notify script code` +2. User-level settings.json: `{"env": {"WEBHOOK": "..."}}` +3. Project-level settings.json: `{"env": {"WEBHOOK": "true"}}` +4. System environment variable: `DEEPCODE_WEBHOOK=... deepcode` -1. 硬编码默认值:`os.environ.get('WEBHOOK', '...') # notify脚本代码` -2. 用户级settings.json: `{"env": {"WEBHOOK": "..."}}` -3. 项目级settings.json: `{"env": {"WEBHOOK": "true"}}` -4. 系统环境变量: `DEEPCODE_WEBHOOK=... deepcode` +#### 4. Setting environment variables for an MCP Service -#### 四、设置MCP Service的环境变量 +Applied in the following priority order (lower-numbered overridden by higher-numbered) – using a GitHub MCP server as an example: -按以下优先级顺序应用(数字较小的会被数字较大的覆盖)(以github MCP server为例): - -1. 用户级settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` -2. 用户级settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` -3. 项目级settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` -4. 项目级settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` -5. 系统环境变量: `DEEPCODE_MCP_GITHUB_PERSONAL_ACCESS_TOKEN=... deepcode` +1. User-level settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` +2. User-level settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` +3. Project-level settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` +4. Project-level settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` +5. System environment variable: `DEEPCODE_MCP_GITHUB_PERSONAL_ACCESS_TOKEN=... deepcode` \ No newline at end of file diff --git a/docs/mcp.md b/docs/mcp.md index fe6711d..11adda5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,22 +1,22 @@ -# Deep Code CLI MCP 配置指南 +# Deep Code CLI MCP Configuration Guide -Deep Code CLI 支持 MCP(Model Context Protocol),让 AI 助手能够连接外部工具和服务,如 GitHub、浏览器、数据库等。 +Deep Code CLI supports MCP (Model Context Protocol), enabling AI assistants to connect with external tools and services such as GitHub, browsers, databases, and more. -## 概述 +## Overview -配置 MCP 后,Deep Code 可以: +Once MCP is configured, Deep Code can: -- 操作 GitHub 仓库(查看 Issues、创建 PR、搜索代码等) -- 操控浏览器(截图、点击、填表单等) -- 访问文件系统 -- 连接数据库和 API -- ...以及任何兼容 MCP 协议的外部服务 +- Operate on GitHub repositories (view issues, create PRs, search code, etc.) +- Control browsers (screenshots, clicks, form filling, etc.) +- Access the file system +- Connect to databases and APIs +- ...and any external service compatible with the MCP protocol -MCP 工具在 Deep Code 中的命名格式为 `mcp__<服务名>__<工具名>`,例如 `mcp__github__search_code`。 +MCP tools are named in Deep Code using the format `mcp____`, for example `mcp__github__search_code`. -## 配置 MCP 服务器 +## Configuring MCP Servers -编辑 `~/.deepcode/settings.json`,添加 `mcpServers` 字段: +Edit `~/.deepcode/settings.json` and add the `mcpServers` field: ```json { @@ -28,30 +28,30 @@ MCP 工具在 Deep Code 中的命名格式为 `mcp__<服务名>__<工具名>`, "thinkingEnabled": true, "reasoningEffort": "max", "mcpServers": { - "<服务名称>": { - "command": "<可执行文件>", - "args": ["<参数1>", "<参数2>"], + "": { + "command": "", + "args": ["", ""], "env": { - "<环境变量>": "<值>" + "": "" } } } } ``` -### 配置项说明 +### Configuration Fields -| 字段 | 类型 | 必填 | 说明 | -| --------- | -------- | ---- | ---------------------------------------------------------------------------------------------------------------------- | -| `command` | string | 是 | MCP 服务器的可执行文件路径或命令(如 `npx`、`node`、`python`)。当命令是 `npx` 时,Deep Code 会自动在参数前补充 `-y`。 | -| `args` | string[] | 否 | 传递给命令的参数列表 | -| `env` | object | 否 | 传递给 MCP 服务器进程的环境变量(如 API Key) | +| Field | Type | Required | Description | +| --------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `command` | string | Yes | Path or command of the MCP server executable (e.g., `npx`, `node`, `python`). When the command is `npx`, Deep Code automatically prepends `-y` to the arguments. | +| `args` | string[] | No | List of arguments to pass to the command | +| `env` | object | No | Environment variables (e.g., API keys) to pass to the MCP server process | -## 常用 MCP 示例 +## Common MCP Examples ### GitHub MCP -让 Deep Code 直接操作 GitHub 仓库(搜索代码、管理 Issue/PR、读写文件等): +Allows Deep Code to directly operate on GitHub repositories (search code, manage issues/PRs, read/write files, etc.): ```json { @@ -67,11 +67,11 @@ MCP 工具在 Deep Code 中的命名格式为 `mcp__<服务名>__<工具名>`, } ``` -> GitHub Personal Access Token 可在 [GitHub Settings > Developer settings > Personal access tokens](https://github.com/settings/tokens) 生成。 +> Generate a GitHub Personal Access Token at [GitHub Settings > Developer settings > Personal access tokens](https://github.com/settings/tokens). -### 浏览器控制(Playwright) +### Browser Control (Playwright) -让 Deep Code 操控浏览器进行截图、页面操作等: +Lets Deep Code control a browser for screenshots, page interactions, etc.: ```json { @@ -84,9 +84,9 @@ MCP 工具在 Deep Code 中的命名格式为 `mcp__<服务名>__<工具名>`, } ``` -### 文件系统 +### File System -让 Deep Code 在指定目录中读写文件: +Enables Deep Code to read and write files within a specified directory: ```json { @@ -99,7 +99,7 @@ MCP 工具在 Deep Code 中的命名格式为 `mcp__<服务名>__<工具名>`, } ``` -### 自定义 Python MCP +### Custom Python MCP ```json { @@ -115,9 +115,9 @@ MCP 工具在 Deep Code 中的命名格式为 `mcp__<服务名>__<工具名>`, } ``` -## 完整配置示例 +## Full Configuration Example -以下是一个配置了 GitHub 和 Playwright 两个 MCP 服务器的完整 `~/.deepcode/settings.json`: +Below is a complete `~/.deepcode/settings.json` with both GitHub and Playwright MCP servers configured: ```json { @@ -144,62 +144,62 @@ MCP 工具在 Deep Code 中的命名格式为 `mcp__<服务名>__<工具名>`, } ``` -## 使用 MCP +## Using MCP -配置完成后,启动 `deepcode`,使用 `/mcp` 命令管理 MCP 连接: +After configuration, start `deepcode` and use the `/mcp` command to manage MCP connections: -- `/mcp` — 查看已配置的 MCP 服务器状态 -- `/mcp add` — 添加新的 MCP 服务器 -- `/mcp remove` — 移除 MCP 服务器 -- `/mcp list` — 列出所有已连接的 MCP 服务器及其工具 +- `/mcp` — View the status of configured MCP servers +- `/mcp add` — Add a new MCP server +- `/mcp remove` — Remove an MCP server +- `/mcp list` — List all connected MCP servers and their tools -在对话中直接使用 MCP 工具名称即可调用,例如: +Simply use the MCP tool name in your conversation to invoke it, for example: ``` -帮我搜索 GitHub 上 deepcode-cli 仓库的 issues +Help me search for issues in the deepcode-cli repository on GitHub ``` -AI 会自动调用 `mcp__github__search_issues` 工具完成操作。 +The AI will automatically invoke the `mcp__github__search_issues` tool to complete the action. -## 工具命名规则 +## Tool Naming Convention -MCP 工具名称由三部分组成:`mcp__<服务名>__<工具名>` +An MCP tool name consists of three parts: `mcp____` -| 服务名 | 工具名 | 完整调用名 | -| ---------- | ----------------------- | ------------------------------------------ | -| github | search_code | `mcp__github__search_code` | -| github | create_pull_request | `mcp__github__create_pull_request` | -| playwright | browser_navigate | `mcp__playwright__browser_navigate` | -| playwright | browser_take_screenshot | `mcp__playwright__browser_take_screenshot` | +| Service | Tool Name | Full Invocation Name | +| ---------- | ----------------------- | ------------------------------------------- | +| github | search_code | `mcp__github__search_code` | +| github | create_pull_request | `mcp__github__create_pull_request` | +| playwright | browser_navigate | `mcp__playwright__browser_navigate` | +| playwright | browser_take_screenshot | `mcp__playwright__browser_take_screenshot` | -你可以通过 `/mcp list` 查看每个服务器提供的具体工具列表。 +You can view the list of tools provided by each server using `/mcp list`. -## 故障排查 +## Troubleshooting -### 启动失败 +### Startup Failure -如果 MCP 服务器无法启动,检查: +If an MCP server fails to start, check: -1. `command` 是否已安装(如 `npx` 需要 Node.js) -2. `env` 中的环境变量是否正确(如 `GITHUB_PERSONAL_ACCESS_TOKEN`) -3. 运行 `deepcode` 的终端是否有网络访问权限 +1. Whether `command` is installed (e.g., `npx` requires Node.js) +2. Whether environment variables in `env` are correct (e.g., `GITHUB_PERSONAL_ACCESS_TOKEN`) +3. Whether the terminal running `deepcode` has network access -### 工具不显示 +### Tools Not Showing Up -1. 确认 `settings.json` 中的 `mcpServers` 字段格式正确 -2. 启动 deepcode 后使用 `/mcp` 查看服务器状态 -3. 如果服务器状态显示错误,根据错误信息排查 +1. Verify that the `mcpServers` field in `settings.json` is correctly formatted +2. After starting deepcode, use `/mcp` to check server status +3. If the server status shows an error, debug based on the error message -### Windows 用户 +### Windows Users -在 Windows 上,Deep Code CLI 会自动为 `.cmd` 命令添加 shell 支持。如果你的 MCP 命令是批处理脚本,确保文件名以 `.cmd` 结尾。 +On Windows, Deep Code CLI automatically adds shell support for `.cmd` commands. If your MCP command is a batch script, ensure the filename ends with `.cmd`. -## 编写你自己的 MCP 服务器 +## Writing Your Own MCP Server -MCP 服务器遵循 [Model Context Protocol](https://modelcontextprotocol.io/) 规范,使用 JSON-RPC 2.0 通信。你可以用任何语言编写 MCP 服务器,只要实现以下协议即可: +MCP servers follow the [Model Context Protocol](https://modelcontextprotocol.io/) specification and communicate using JSON‑RPC 2.0. You can write an MCP server in any language as long as it implements the following methods: -1. `initialize` — 握手和协议协商 -2. `tools/list` — 返回可用工具列表 -3. `tools/call` — 执行工具调用 +1. `initialize` — Handshake and protocol negotiation +2. `tools/list` — Return the list of available tools +3. `tools/call` — Execute a tool call -更多参考:[MCP 官方文档](https://modelcontextprotocol.io/) +For more information, see the [official MCP documentation](https://modelcontextprotocol.io/). \ No newline at end of file From fb38560830a55c217122ebff5ee42836523d7c3b Mon Sep 17 00:00:00 2001 From: hcyang Date: Thu, 14 May 2026 14:23:04 +0800 Subject: [PATCH 002/129] =?UTF-8?q?feat(mcp):=20=E9=9B=86=E6=88=90?= =?UTF-8?q?=E5=B9=B6=E5=B1=95=E7=A4=BAMCP=E6=9C=8D=E5=8A=A1=E5=99=A8?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E5=92=8C=E8=B5=84=E6=BA=90=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增McpStatusList组件,实现MCP服务器状态、工具、提示和资源的可视化展示 - 修改App组件,支持切换视图显示MCP状态列表 - MCP客户端增加对prompts和resources的分页列表及读取功能 - MCP管理器扩展,支持发现和管理prompts及resources,及工具列表变化的事件通知 - 优化MCP客户端,支持JSON-RPC通知的处理,完善请求超时控制 - 在session中添加MCP工具列表变化监听,实时更新工具定义数据 - 提供键盘操作支持,实现MCP状态列表的上下翻页和快速导航 - 美化MCP状态列表界面,显示服务器状态及能力的详细信息 --- src/mcp/mcp-client.ts | 133 ++++++++++++++++++++++-- src/mcp/mcp-manager.ts | 185 ++++++++++++++++++++++++++++++++- src/session.ts | 3 + src/ui/App.tsx | 39 ++----- src/ui/McpStatusList.tsx | 219 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 537 insertions(+), 42 deletions(-) create mode 100644 src/ui/McpStatusList.tsx diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts index 0fad322..a086c1d 100644 --- a/src/mcp/mcp-client.ts +++ b/src/mcp/mcp-client.ts @@ -17,6 +17,12 @@ type JsonRpcResponse = { error?: { code: number; message: string; data?: unknown }; }; +type JsonRpcNotification = { + jsonrpc: "2.0"; + method: string; + params?: Record; +}; + export type McpToolDefinition = { name: string; description?: string; @@ -24,6 +30,7 @@ export type McpToolDefinition = { type: "object"; properties: Record; required?: string[]; + additionalProperties?: boolean; }; }; @@ -37,6 +44,58 @@ type CallToolResult = { isError?: boolean; }; +export type McpPromptArgument = { + name: string; + description?: string; + required?: boolean; +}; + +export type McpPromptDefinition = { + name: string; + description?: string; + arguments?: McpPromptArgument[]; +}; + +type ListPromptsResult = { + prompts: McpPromptDefinition[]; + nextCursor?: string; +}; + +export type McpPromptMessage = { + role: "user" | "assistant"; + content: { type: string; text?: string }; +}; + +type GetPromptResult = { + description?: string; + messages: McpPromptMessage[]; +}; + +export type McpResourceDefinition = { + uri: string; + name: string; + description?: string; + mimeType?: string; +}; + +type ListResourcesResult = { + resources: McpResourceDefinition[]; + nextCursor?: string; +}; + +export type McpResourceContent = { + uri: string; + mimeType?: string; + text?: string; + blob?: string; +}; + +type ReadResourceResult = { + contents: McpResourceContent[]; +}; + +export type McpNotificationHandler = (method: string, params?: Record) => void; + export class McpClient { private process: ChildProcess | null = null; private reader: Interface | null = null; @@ -46,13 +105,17 @@ export class McpClient { { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout } >(); private stderrBuffer = ""; + private notificationHandler: McpNotificationHandler | null = null; constructor( private readonly serverName: string, private readonly command: string, private readonly args: string[] = [], - private readonly env?: Record - ) {} + private readonly env?: Record, + onNotification?: McpNotificationHandler + ) { + this.notificationHandler = onNotification ?? null; + } async connect(timeoutMs: number): Promise { return new Promise((resolve, reject) => { @@ -109,7 +172,7 @@ export class McpClient { this.sendRequest( "initialize", { - protocolVersion: "2024-11-05", + protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "deepcode-cli", version: "0.1.0" }, }, @@ -141,8 +204,50 @@ export class McpClient { throw this.withStderr(`MCP server "${this.serverName}" returned too many tools/list pages`); } - async callTool(name: string, args: Record): Promise { - return (await this.sendRequest("tools/call", { name, arguments: args })) as CallToolResult; + async callTool(name: string, args: Record, timeoutMs = 60_000): Promise { + return (await this.sendRequest("tools/call", { name, arguments: args }, timeoutMs)) as CallToolResult; + } + + async listPrompts(timeoutMs: number): Promise { + const prompts: McpPromptDefinition[] = []; + let cursor: string | undefined; + + for (let page = 0; page < 100; page++) { + const params = cursor ? { cursor } : {}; + const result = (await this.sendRequest("prompts/list", params, timeoutMs)) as ListPromptsResult; + prompts.push(...(result.prompts ?? [])); + cursor = typeof result.nextCursor === "string" && result.nextCursor ? result.nextCursor : undefined; + if (!cursor) { + return prompts; + } + } + + throw this.withStderr(`MCP server "${this.serverName}" returned too many prompts/list pages`); + } + + async getPrompt(name: string, args: Record, timeoutMs = 30_000): Promise { + return (await this.sendRequest("prompts/get", { name, arguments: args }, timeoutMs)) as GetPromptResult; + } + + async listResources(timeoutMs: number): Promise { + const resources: McpResourceDefinition[] = []; + let cursor: string | undefined; + + for (let page = 0; page < 100; page++) { + const params = cursor ? { cursor } : {}; + const result = (await this.sendRequest("resources/list", params, timeoutMs)) as ListResourcesResult; + resources.push(...(result.resources ?? [])); + cursor = typeof result.nextCursor === "string" && result.nextCursor ? result.nextCursor : undefined; + if (!cursor) { + return resources; + } + } + + throw this.withStderr(`MCP server "${this.serverName}" returned too many resources/list pages`); + } + + async readResource(uri: string, timeoutMs = 30_000): Promise { + return (await this.sendRequest("resources/read", { uri }, timeoutMs)) as ReadResourceResult; } disconnect(): void { @@ -195,7 +300,23 @@ export class McpClient { private handleLine(line: string): void { try { - const message = JSON.parse(line) as JsonRpcResponse; + const parsed: unknown = JSON.parse(line); + + // Handle notifications (no id field — server-initiated) + if (parsed && typeof parsed === "object" && !("id" in parsed)) { + const notification = parsed as JsonRpcNotification; + if (this.notificationHandler && typeof notification.method === "string") { + try { + this.notificationHandler(notification.method, notification.params); + } catch { + // Swallow handler errors to avoid crashing the reader loop + } + } + return; + } + + // Handle responses to our requests + const message = parsed as JsonRpcResponse; if (message.id !== undefined && this.pendingRequests.has(message.id)) { const pending = this.pendingRequests.get(message.id)!; this.pendingRequests.delete(message.id); diff --git a/src/mcp/mcp-manager.ts b/src/mcp/mcp-manager.ts index 030d0d3..8121dbc 100644 --- a/src/mcp/mcp-manager.ts +++ b/src/mcp/mcp-manager.ts @@ -1,7 +1,8 @@ -import { McpClient, type McpToolDefinition } from "./mcp-client"; +import { McpClient, type McpToolDefinition, type McpPromptDefinition, type McpResourceDefinition } from "./mcp-client"; import type { McpServerConfig } from "../settings"; const MCP_STARTUP_TIMEOUT_MS = 30_000; +const MCP_CALL_TOOL_TIMEOUT_MS = 60_000; type McpToolEntry = { serverName: string; @@ -18,15 +19,32 @@ export type McpServerStatus = { error?: string; toolCount: number; tools: string[]; + promptCount: number; + prompts: string[]; + resourceCount: number; + resources: string[]; }; export class McpManager { private clients: McpClient[] = []; private tools: McpToolEntry[] = []; + private prompts: Array<{ + serverName: string; + namespacedName: string; + definition: McpPromptDefinition; + client: McpClient; + }> = []; + private resources: Array<{ + serverName: string; + namespacedName: string; + definition: McpResourceDefinition; + client: McpClient; + }> = []; private initialized = false; private disposed = false; private configuredServerNames: string[] = []; private serverStatuses: McpServerStatus[] = []; + private onToolsListChanged: (() => void) | null = null; prepare(servers?: Record): void { if (!servers || Object.keys(servers).length === 0) return; @@ -48,6 +66,10 @@ export class McpManager { connected: false, toolCount: 0, tools: [], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], }); } } @@ -65,7 +87,13 @@ export class McpManager { if (this.disposed) break; let client: McpClient | null = null; try { - client = new McpClient(name, config.command, config.args ?? [], config.env); + client = new McpClient(name, config.command, config.args ?? [], config.env, (method) => { + if (method === "notifications/tools/list_changed") { + this.refreshServerTools(name, client!).catch(() => { + // swallow refresh errors + }); + } + }); await client.connect(MCP_STARTUP_TIMEOUT_MS); if (this.disposed) { client.disconnect(); @@ -73,6 +101,7 @@ export class McpManager { } this.clients.push(client); + // Discover tools const serverTools = await client.listTools(MCP_STARTUP_TIMEOUT_MS); if (this.disposed) break; const toolNamespacedNames: string[] = []; @@ -87,12 +116,57 @@ export class McpManager { }); toolNamespacedNames.push(namespacedName); } + + // Discover prompts + let serverPrompts: McpPromptDefinition[] = []; + try { + serverPrompts = await client.listPrompts(MCP_STARTUP_TIMEOUT_MS); + } catch { + // Server may not support prompts — safe to ignore + } + if (this.disposed) break; + const promptNamespacedNames: string[] = []; + for (const prompt of serverPrompts) { + const namespacedName = `mcp__${name}__${prompt.name}`; + this.prompts.push({ + serverName: name, + namespacedName, + definition: prompt, + client, + }); + promptNamespacedNames.push(namespacedName); + } + + // Discover resources + let serverResources: McpResourceDefinition[] = []; + try { + serverResources = await client.listResources(MCP_STARTUP_TIMEOUT_MS); + } catch { + // Server may not support resources — safe to ignore + } + if (this.disposed) break; + const resourceNamespacedNames: string[] = []; + for (const resource of serverResources) { + const namespacedName = `mcp__${name}__${resource.name}`; + this.resources.push({ + serverName: name, + namespacedName, + definition: resource, + client, + }); + resourceNamespacedNames.push(namespacedName); + } + this.setStatus({ name, status: "ready", connected: true, toolCount: serverTools.length, tools: toolNamespacedNames, + promptCount: serverPrompts.length, + prompts: promptNamespacedNames, + resourceCount: serverResources.length, + resources: resourceNamespacedNames, }); } catch (err) { if (this.disposed) break; @@ -106,6 +180,10 @@ export class McpManager { error: message, toolCount: 0, tools: [], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], }); } } @@ -122,6 +200,10 @@ export class McpManager { connected: false, toolCount: 0, tools: [], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], }); } } @@ -150,7 +232,9 @@ export class McpManager { type: "object" as const, properties: t.definition.inputSchema.properties, required: t.definition.inputSchema.required, - additionalProperties: false, + ...(t.definition.inputSchema.additionalProperties !== undefined + ? { additionalProperties: t.definition.inputSchema.additionalProperties } + : {}), }, }, })); @@ -162,7 +246,8 @@ export class McpManager { async executeMcpTool( name: string, - args: Record + args: Record, + timeoutMs = MCP_CALL_TOOL_TIMEOUT_MS ): Promise<{ ok: boolean; name: string; output?: string; error?: string }> { const tool = this.tools.find((t) => t.namespacedName === name); if (!tool) { @@ -170,7 +255,7 @@ export class McpManager { } try { - const result = await tool.client.callTool(tool.originalName, args); + const result = await tool.client.callTool(tool.originalName, args, timeoutMs); const text = result.content .filter((c) => c.type === "text" && c.text) .map((c) => c.text) @@ -189,6 +274,64 @@ export class McpManager { } } + async getMcpPrompt( + name: string, + args: Record + ): Promise<{ ok: boolean; name: string; output?: string; error?: string }> { + const prompt = this.prompts.find((p) => p.namespacedName === name); + if (!prompt) { + return { ok: false, name, error: `Unknown MCP prompt: ${name}` }; + } + + try { + const result = await prompt.client.getPrompt(prompt.definition.name, args); + const text = result.messages + .filter((m) => m.content.type === "text" && m.content.text) + .map((m) => `[${m.role}] ${m.content.text}`) + .join("\n"); + return { + ok: true, + name, + output: text || JSON.stringify(result), + }; + } catch (err) { + return { + ok: false, + name, + error: err instanceof Error ? err.message : String(err), + }; + } + } + + async readMcpResource( + name: string, + uri: string + ): Promise<{ ok: boolean; name: string; output?: string; error?: string }> { + const resource = this.resources.find((r) => r.namespacedName === name); + if (!resource) { + return { ok: false, name, error: `Unknown MCP resource: ${name}` }; + } + + try { + const result = await resource.client.readResource(uri); + const text = result.contents + .filter((c) => c.text) + .map((c) => c.text) + .join("\n"); + return { + ok: true, + name, + output: text || JSON.stringify(result.contents), + }; + } catch (err) { + return { + ok: false, + name, + error: err instanceof Error ? err.message : String(err), + }; + } + } + disconnect(): void { this.disposed = true; for (const client of this.clients) { @@ -196,11 +339,43 @@ export class McpManager { } this.clients = []; this.tools = []; + this.prompts = []; + this.resources = []; this.serverStatuses = []; this.configuredServerNames = []; this.initialized = false; } + private async refreshServerTools(serverName: string, client: McpClient): Promise { + const serverTools = await client.listTools(MCP_STARTUP_TIMEOUT_MS); + // Remove old tool entries for this server + this.tools = this.tools.filter((t) => t.serverName !== serverName); + const toolNamespacedNames: string[] = []; + for (const tool of serverTools) { + const namespacedName = `mcp__${serverName}__${tool.name}`; + this.tools.push({ + serverName, + originalName: tool.name, + namespacedName, + definition: tool, + client, + }); + toolNamespacedNames.push(namespacedName); + } + // Update status + const existing = this.serverStatuses.find((s) => s.name === serverName); + if (existing) { + existing.toolCount = serverTools.length; + existing.tools = toolNamespacedNames; + } + // Notify listener + this.onToolsListChanged?.(); + } + + setOnToolsListChanged(handler: () => void): void { + this.onToolsListChanged = handler; + } + private setStatus(status: McpServerStatus): void { if (this.disposed) return; const index = this.serverStatuses.findIndex((s) => s.name === status.name); diff --git a/src/session.ts b/src/session.ts index a174f9b..161ba98 100644 --- a/src/session.ts +++ b/src/session.ts @@ -203,6 +203,9 @@ export class SessionManager { } async initMcpServers(servers?: Record): Promise { + this.mcpManager.setOnToolsListChanged(() => { + this.mcpToolDefinitions = this.mcpManager.getMcpToolDefinitions(); + }); await this.mcpManager.initialize(servers); this.mcpToolDefinitions = this.mcpManager.getMcpToolDefinitions(); } diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 757b40c..ffe89e4 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -29,6 +29,7 @@ import { buildLoadingText } from "./loadingText"; import { findExpandedThinkingId } from "./thinkingState"; import { WelcomeScreen } from "./WelcomeScreen"; import { AskUserQuestionPrompt } from "./AskUserQuestionPrompt"; +import { McpStatusList } from "./McpStatusList"; import { findPendingAskUserQuestion, formatAskUserQuestionAnswers, @@ -39,7 +40,7 @@ import { buildExitSummaryText } from "./exitSummary"; const DEFAULT_MODEL = "deepseek-v4-pro"; const DEFAULT_BASE_URL = "https://api.deepseek.com"; -type View = "chat" | "session-list"; +type View = "chat" | "session-list" | "mcp-status"; type AppProps = { projectRoot: string; @@ -67,6 +68,7 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R const [welcomeNonce, setWelcomeNonce] = useState(0); const [resolvedSettings, setResolvedSettings] = useState(() => resolveCurrentSettings(projectRoot)); const [nowTick, setNowTick] = useState(0); + const [mcpStatuses, setMcpStatuses] = useState>([]); const messagesRef = useRef([]); messagesRef.current = messages; @@ -189,36 +191,9 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R return; } if (submission.command === "mcp") { - process.stdout.write("\n"); - process.stdout.write(chalk.bold.cyan("MCP Server Status\n")); - process.stdout.write(chalk.dim("─────────────────\n")); - const statuses = sessionManager.getMcpStatus(); - if (statuses.length === 0) { - process.stdout.write(chalk.dim(" No MCP servers configured.\n")); - } else { - for (const s of statuses) { - if (s.status === "starting") { - process.stdout.write(`${chalk.yellow("●")} ${chalk.bold(s.name)} - Starting...`); - } else if (s.status === "failed") { - process.stdout.write(`${chalk.red("✖")} ${chalk.bold(s.name)} - Failed (${s.error ?? "unknown error"})`); - } else { - process.stdout.write(`${chalk.green("✔")} ${chalk.bold(s.name)} - Ready (${s.toolCount} tools)`); - } - process.stdout.write("\n"); - if (s.status === "ready" && s.tools.length > 0) { - for (const tool of s.tools) { - process.stdout.write(chalk.dim(` - ${tool}\n`)); - } - } - } - } - process.stdout.write(chalk.dim("─────────────────\n")); - process.stdout.write( - chalk.dim(` Total: ${statuses.filter((s) => s.status === "ready").length} ready, `) + - chalk.dim(`${statuses.filter((s) => s.status === "starting").length} starting, `) + - chalk.dim(`${statuses.filter((s) => s.status === "failed").length} failed\n`) - ); - process.stdout.write("\n"); + setShowWelcome(false); + setMcpStatuses(sessionManager.getMcpStatus()); + setView("mcp-status"); return; } @@ -471,6 +446,8 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R onSelect={(id) => void handleSelectSession(id)} onCancel={() => setView("chat")} /> + ) : view === "mcp-status" ? ( + setView("chat")} /> ) : shouldShowQuestionPrompt && pendingQuestion && !busy ? ( void; +}; + +type FlatItem = + | { kind: "server"; status: McpServerStatus; serverIndex: number } + | { kind: "tool"; name: string; serverName: string } + | { kind: "prompt"; name: string; serverName: string } + | { kind: "resource"; name: string; serverName: string }; + +function buildFlatItems(statuses: McpServerStatus[]): FlatItem[] { + const items: FlatItem[] = []; + for (let i = 0; i < statuses.length; i++) { + const status = statuses[i]; + items.push({ kind: "server", status, serverIndex: i }); + if (status.status === "ready") { + for (const tool of status.tools) { + items.push({ kind: "tool", name: tool, serverName: status.name }); + } + for (const prompt of status.prompts) { + items.push({ kind: "prompt", name: prompt, serverName: status.name }); + } + for (const resource of status.resources) { + items.push({ kind: "resource", name: resource, serverName: status.name }); + } + } + } + return items; +} + +export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement { + const [index, setIndex] = useState(0); + const { columns, rows } = useWindowSize(); + + const flatItems = useMemo(() => buildFlatItems(statuses), [statuses]); + + const maxVisible = useMemo(() => { + const reservedLines = 8; + const linesPerItem = 2; + const availableLines = Math.max(0, Math.min(rows, 30) - reservedLines); + return Math.max(1, Math.floor(availableLines / linesPerItem)); + }, [rows]); + + const safeIndex = useMemo(() => { + if (flatItems.length === 0) return 0; + return Math.max(0, Math.min(index, flatItems.length - 1)); + }, [index, flatItems.length]); + + const scrollOffset = useMemo(() => { + if (safeIndex < maxVisible) return 0; + return safeIndex - maxVisible + 1; + }, [safeIndex, maxVisible]); + + const visibleItems = useMemo(() => { + return flatItems.slice(scrollOffset, scrollOffset + maxVisible); + }, [flatItems, scrollOffset, maxVisible]); + + useInput((input, key) => { + if (key.escape || (key.ctrl && (input === "c" || input === "C"))) { + onCancel(); + return; + } + if (flatItems.length === 0) { + return; + } + if (key.upArrow) { + setIndex((i) => Math.max(0, i - 1)); + return; + } + if (key.downArrow) { + setIndex((i) => Math.min(flatItems.length - 1, i + 1)); + return; + } + if (key.pageUp) { + setIndex((i) => Math.max(0, i - maxVisible)); + return; + } + if (key.pageDown) { + setIndex((i) => Math.min(flatItems.length - 1, i + maxVisible)); + return; + } + if (key.home) { + setIndex(0); + return; + } + if (key.end) { + setIndex(flatItems.length - 1); + } + }); + + const readyCount = statuses.filter((s) => s.status === "ready").length; + const startingCount = statuses.filter((s) => s.status === "starting").length; + const failedCount = statuses.filter((s) => s.status === "failed").length; + + if (statuses.length === 0) { + return ( + + Manage MCP servers + 0 servers + No MCP servers configured. + Add MCP servers to your settings to get started. + Esc to close + + ); + } + + return ( + + + {/* Header row */} + + + MCP Server Status + + + {" "} + ({readyCount} ready, {startingCount} starting, {failedCount} failed) + + + {/* Items list */} + + {visibleItems.map((item, i) => { + const actualIndex = scrollOffset + i; + const isSelected = actualIndex === safeIndex; + + if (item.kind === "server") { + return ; + } + return ( + + ); + })} + {scrollOffset > 0 || scrollOffset + maxVisible < flatItems.length ? ( + + {scrollOffset > 0 ? … {scrollOffset} items above. : null} + {scrollOffset + maxVisible < flatItems.length ? ( + … {flatItems.length - scrollOffset - maxVisible} items below. + ) : null} + + ) : null} + + {/* Footer */} + + ↑/↓ navigate · PgUp/PgDn page · Esc cancel + + + + ); +} + +function ServerRow({ status, selected }: { status: McpServerStatus; selected: boolean }): React.ReactElement { + const icon = status.status === "ready" ? "✔" : status.status === "failed" ? "✖" : "●"; + const color = status.status === "ready" ? "green" : status.status === "failed" ? "red" : "yellow"; + const detail = + status.status === "ready" + ? `Ready (${status.toolCount} tools, ${status.promptCount} prompts, ${status.resourceCount} resources)` + : status.status === "failed" + ? `Failed (${status.error ?? "unknown error"})` + : "Starting..."; + + return ( + + {selected ? "› " : " "} + + {icon} + {status.name} + — {detail} + + + ); +} + +function CapabilityRow({ + kind, + name, + selected, +}: { + kind: "tool" | "prompt" | "resource"; + name: string; + selected: boolean; +}): React.ReactElement { + const prefix = kind === "tool" ? "🔧" : kind === "prompt" ? "📝" : "📦"; + return ( + + {selected ? "› " : " "} + + {prefix} {name} + + + ); +} From 91e52406293ff1e8683e15ec00eac98bed175f7d Mon Sep 17 00:00:00 2001 From: hcyang Date: Thu, 14 May 2026 15:40:35 +0800 Subject: [PATCH 003/129] =?UTF-8?q?feat(ui):=20=E6=B7=BB=E5=8A=A0=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=99=A8=E9=94=99=E8=AF=AF=E4=BF=A1=E6=81=AF=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在FlatItem类型中添加错误信息项 - 失败状态的服务器添加对应错误消息 - 失败错误信息单独用ErrorRow组件渲染 - 更新无服务器时的提示样式,增强视觉层次感 - 为工具项添加左侧缩进优化排版布局 --- src/ui/McpStatusList.tsx | 43 ++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/src/ui/McpStatusList.tsx b/src/ui/McpStatusList.tsx index b04d7af..d3e9048 100644 --- a/src/ui/McpStatusList.tsx +++ b/src/ui/McpStatusList.tsx @@ -9,6 +9,7 @@ type Props = { type FlatItem = | { kind: "server"; status: McpServerStatus; serverIndex: number } + | { kind: "error"; error: string; serverName: string } | { kind: "tool"; name: string; serverName: string } | { kind: "prompt"; name: string; serverName: string } | { kind: "resource"; name: string; serverName: string }; @@ -18,6 +19,10 @@ function buildFlatItems(statuses: McpServerStatus[]): FlatItem[] { for (let i = 0; i < statuses.length; i++) { const status = statuses[i]; items.push({ kind: "server", status, serverIndex: i }); + // 为失败的服务添加错误消息 + if (status.status === "failed" && status.error) { + items.push({ kind: "error", error: status.error, serverName: status.name }); + } if (status.status === "ready") { for (const tool of status.tools) { items.push({ kind: "tool", name: tool, serverName: status.name }); @@ -99,11 +104,17 @@ export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement if (statuses.length === 0) { return ( - - Manage MCP servers - 0 servers - No MCP servers configured. - Add MCP servers to your settings to get started. + + + + Manage MCP servers + + 0 servers + + + No MCP servers configured. + Add MCP servers to your settings to get started. + Esc to close ); @@ -149,6 +160,9 @@ export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement if (item.kind === "server") { return ; } + if (item.kind === "error") { + return ; + } return ( + {selected ? "› " : " "} {prefix} {name} @@ -217,3 +231,20 @@ function CapabilityRow({ ); } + +function ErrorRow({ error }: { error: string }): React.ReactElement { + // 将错误消息按行分割,每行单独显示 + const lines = error.split("\n").filter((line) => line.trim().length > 0); + + return ( + + {lines.map((line, index) => ( + + + {line} + + + ))} + + ); +} From 40025e495a6c19aa34939be78a4ace696a966ed7 Mon Sep 17 00:00:00 2001 From: hcyang Date: Thu, 14 May 2026 17:59:52 +0800 Subject: [PATCH 004/129] =?UTF-8?q?feat(mcp):=20=E5=AE=9E=E6=97=B6?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=92=8C=E5=B1=95=E7=A4=BA=20MCP=20=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=99=A8=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 MCP 状态变更回调,支持 UI 实时刷新显示 - MCP 管理器中添加状态变更事件处理机制 - 调整 UI 组件以支持状态计数的高亮显示 - 移除 MCP 初始化失败的控制台错误输出,避免信息泄露 - 优化退出命令行提示颜色为灰色,提升可读性 --- src/mcp/mcp-manager.ts | 14 +++++++++++--- src/session.ts | 7 +++++++ src/ui/App.tsx | 6 +++++- src/ui/McpStatusList.tsx | 21 +++++++++++++++------ 4 files changed, 38 insertions(+), 10 deletions(-) diff --git a/src/mcp/mcp-manager.ts b/src/mcp/mcp-manager.ts index 8121dbc..5a9f553 100644 --- a/src/mcp/mcp-manager.ts +++ b/src/mcp/mcp-manager.ts @@ -45,6 +45,7 @@ export class McpManager { private configuredServerNames: string[] = []; private serverStatuses: McpServerStatus[] = []; private onToolsListChanged: (() => void) | null = null; + private onStatusChanged: (() => void) | null = null; prepare(servers?: Record): void { if (!servers || Object.keys(servers).length === 0) return; @@ -172,7 +173,8 @@ export class McpManager { if (this.disposed) break; client?.disconnect(); const message = err instanceof Error ? err.message : String(err); - process.stderr.write(`[deepcode] MCP server "${name}" failed to initialize: ${message}\n`); + // 不在控制台输出错误日志,避免暴露敏感信息 + // process.stderr.write(`[deepcode] MCP server "${name}" failed to initialize: ${message}\n`); this.setStatus({ name, status: "failed", @@ -376,13 +378,19 @@ export class McpManager { this.onToolsListChanged = handler; } + setOnStatusChanged(handler: () => void): void { + this.onStatusChanged = handler; + } + private setStatus(status: McpServerStatus): void { if (this.disposed) return; const index = this.serverStatuses.findIndex((s) => s.name === status.name); if (index === -1) { this.serverStatuses.push(status); - return; + } else { + this.serverStatuses[index] = status; } - this.serverStatuses[index] = status; + // 触发状态变更回调 + this.onStatusChanged?.(); } } diff --git a/src/session.ts b/src/session.ts index 161ba98..3f264b4 100644 --- a/src/session.ts +++ b/src/session.ts @@ -166,6 +166,7 @@ type SessionManagerOptions = { onAssistantMessage: (message: SessionMessage, shouldConnect: boolean) => void; onSessionEntryUpdated?: (entry: SessionEntry) => void; onLlmStreamProgress?: (progress: LlmStreamProgress) => void; + onMcpStatusChanged?: () => void; }; export type LlmStreamProgress = { @@ -184,6 +185,7 @@ export class SessionManager { private readonly onAssistantMessage: (message: SessionMessage, shouldConnect: boolean) => void; private readonly onSessionEntryUpdated?: (entry: SessionEntry) => void; private readonly onLlmStreamProgress?: (progress: LlmStreamProgress) => void; + private readonly onMcpStatusChanged?: () => void; private activeSessionId: string | null = null; private activePromptController: AbortController | null = null; private readonly sessionControllers = new Map(); @@ -198,6 +200,7 @@ export class SessionManager { this.onAssistantMessage = options.onAssistantMessage; this.onSessionEntryUpdated = options.onSessionEntryUpdated; this.onLlmStreamProgress = options.onLlmStreamProgress; + this.onMcpStatusChanged = options.onMcpStatusChanged; this.toolExecutor = new ToolExecutor(this.projectRoot, this.createOpenAIClient, this.mcpManager); this.mcpManager.prepare(this.getResolvedSettings().mcpServers); } @@ -206,6 +209,10 @@ export class SessionManager { this.mcpManager.setOnToolsListChanged(() => { this.mcpToolDefinitions = this.mcpManager.getMcpToolDefinitions(); }); + // 设置状态变更回调,通知 UI 更新 + this.mcpManager.setOnStatusChanged(() => { + this.onMcpStatusChanged?.(); + }); await this.mcpManager.initialize(servers); this.mcpToolDefinitions = this.mcpManager.getMcpToolDefinitions(); } diff --git a/src/ui/App.tsx b/src/ui/App.tsx index ffe89e4..709df67 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -94,6 +94,10 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R } setStreamProgress(progress); }, + onMcpStatusChanged: () => { + // 当 MCP 状态变更时,如果当前正在查看 MCP 状态页面,则更新显示 + setMcpStatuses(sessionManager.getMcpStatus()); + }, }); }, [projectRoot]); @@ -156,7 +160,7 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R const resolved = resolveCurrentSettings(projectRoot); const summary = buildExitSummaryText({ session, messages: allMessages, model: resolved.model }); process.stdout.write("\n"); - process.stdout.write(chalk.green("> /exit ")); + process.stdout.write(chalk.rgb(128, 128, 128)("> /exit ")); process.stdout.write("\n\n"); process.stdout.write(summary); process.stdout.write("\n\n"); diff --git a/src/ui/McpStatusList.tsx b/src/ui/McpStatusList.tsx index d3e9048..455c586 100644 --- a/src/ui/McpStatusList.tsx +++ b/src/ui/McpStatusList.tsx @@ -131,14 +131,23 @@ export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement > {/* Header row */} - - - MCP Server Status - + - {" "} - ({readyCount} ready, {startingCount} starting, {failedCount} failed) + Manage MCP servers + + ( + + {readyCount} ready, + + + {startingCount} starting, + + + {failedCount} failed + + ) + {/* Items list */} Date: Thu, 14 May 2026 23:26:21 +0800 Subject: [PATCH 005/129] =?UTF-8?q?refactor(ui):=20=E4=BC=98=E5=8C=96=20MC?= =?UTF-8?q?P=20=E7=8A=B6=E6=80=81=E5=88=97=E8=A1=A8=E8=A7=86=E5=9B=BE?= =?UTF-8?q?=E5=8F=8A=E7=95=8C=E9=9D=A2=E7=BB=86=E8=8A=82=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 MCP 状态列表拆分为服务器列表和服务器详情两种视图 - 支持通过方向键分页和滚动,确保选中项始终可见 - 服务器详情视图新增工具、提示和资源的详细列表展示及导航支持 - 为启动状态服务器添加动态加载动画,提升交互体验 - 错误信息使用带红色边框的样式包裹,更加醒目 - 统一界面中选中项前缀符号由 "› " 改为 "> " - 修正 DropdownMenu 和 SlashCommandMenu 的注释与前缀符号 - 调整 SessionList 中选中标识符,保持样式一致 - 优化行宽计算逻辑,提升标签列自适应能力 - 改善布局间距和边框样式,增强视觉层次感 --- src/ui/AskUserQuestionPrompt.tsx | 2 +- src/ui/DropdownMenu.tsx | 4 +- src/ui/McpStatusList.tsx | 482 ++++++++++++++++++++++++------- src/ui/PromptInput.tsx | 6 +- src/ui/SessionList.tsx | 2 +- src/ui/SlashCommandMenu.tsx | 6 +- 6 files changed, 380 insertions(+), 122 deletions(-) diff --git a/src/ui/AskUserQuestionPrompt.tsx b/src/ui/AskUserQuestionPrompt.tsx index 952f9cf..7c76ae3 100644 --- a/src/ui/AskUserQuestionPrompt.tsx +++ b/src/ui/AskUserQuestionPrompt.tsx @@ -184,7 +184,7 @@ export function AskUserQuestionPrompt({ questions, onSubmit, onCancel }: Props): return ( - {isCursor ? "› " : " "} + {isCursor ? "> " : " "} {marker} {option.label} {option.isOther ? ( diff --git a/src/ui/DropdownMenu.tsx b/src/ui/DropdownMenu.tsx index 3a963a5..d651720 100644 --- a/src/ui/DropdownMenu.tsx +++ b/src/ui/DropdownMenu.tsx @@ -82,7 +82,7 @@ const DropdownMenu = React.memo(function DropdownMenu({ // 计算每个 item 实际需要的最大宽度 const maxContentWidth = Math.max( ...visibleItems.map((item) => { - let width = 2; // prefix "› " or " " + let width = 2; // prefix "> " or " " if (item.selected !== undefined) { width += 2; // "● " or "○ " } @@ -152,7 +152,7 @@ const DropdownMenu = React.memo(function DropdownMenu({ - {isActive ? "› " : " "} + {isActive ? "> " : " "} {item.selected !== undefined ? (item.selected ? "●" : "○") : null} {item.label} {item.statusIndicator ? ( {item.statusIndicator.symbol} diff --git a/src/ui/McpStatusList.tsx b/src/ui/McpStatusList.tsx index 455c586..e448b5c 100644 --- a/src/ui/McpStatusList.tsx +++ b/src/ui/McpStatusList.tsx @@ -1,4 +1,4 @@ -import React, { useState, useMemo } from "react"; +import React, { useState, useMemo, useCallback, useEffect } from "react"; import { Box, Text, useInput, useWindowSize } from "ink"; import type { McpServerStatus } from "../mcp/mcp-manager"; @@ -7,94 +7,160 @@ type Props = { onCancel: () => void; }; -type FlatItem = - | { kind: "server"; status: McpServerStatus; serverIndex: number } - | { kind: "error"; error: string; serverName: string } - | { kind: "tool"; name: string; serverName: string } - | { kind: "prompt"; name: string; serverName: string } - | { kind: "resource"; name: string; serverName: string }; - -function buildFlatItems(statuses: McpServerStatus[]): FlatItem[] { - const items: FlatItem[] = []; - for (let i = 0; i < statuses.length; i++) { - const status = statuses[i]; - items.push({ kind: "server", status, serverIndex: i }); - // 为失败的服务添加错误消息 - if (status.status === "failed" && status.error) { - items.push({ kind: "error", error: status.error, serverName: status.name }); - } - if (status.status === "ready") { - for (const tool of status.tools) { - items.push({ kind: "tool", name: tool, serverName: status.name }); - } - for (const prompt of status.prompts) { - items.push({ kind: "prompt", name: prompt, serverName: status.name }); - } - for (const resource of status.resources) { - items.push({ kind: "resource", name: resource, serverName: status.name }); - } +export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement { + const { columns, rows } = useWindowSize(); + + // 视图模式:server-list(服务器列表) 或 server-detail(服务器详情) + const [viewMode, setViewMode] = useState<"server-list" | "server-detail">("server-list"); + // 选中的服务器索引 + const [selectedServerIndex, setSelectedServerIndex] = useState(0); + + // 返回服务器列表 + const goBack = useCallback(() => { + setViewMode("server-list"); + }, []); + + // 进入服务器详情 + const enterDetail = useCallback(() => { + const server = statuses[selectedServerIndex]; + if (server && server.status === "ready") { + setViewMode("server-detail"); } + }, [statuses, selectedServerIndex]); + + if (statuses.length === 0) { + return ( + + + + Manage MCP servers + + 0 servers + + + No MCP servers configured. + Add MCP servers to your settings to get started. + + Esc to close + + ); } - return items; -} -export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement { - const [index, setIndex] = useState(0); - const { columns, rows } = useWindowSize(); + if (viewMode === "server-detail") { + return ( + + ); + } - const flatItems = useMemo(() => buildFlatItems(statuses), [statuses]); + return ( + + ); +} + +// ==================== 服务器列表视图 ==================== +function ServerListView({ + statuses, + selectedIndex, + onSelect, + onEnter, + onCancel, + rows, + columns, +}: { + statuses: McpServerStatus[]; + selectedIndex: number; + onSelect: (index: number) => void; + onEnter: () => void; + onCancel: () => void; + rows: number; + columns: number; +}): React.ReactElement { + const [scrollOffset, setScrollOffset] = useState(0); + const serverCount = statuses.length; const maxVisible = useMemo(() => { - const reservedLines = 8; - const linesPerItem = 2; + const reservedLines = 8; // header + footer + borders const availableLines = Math.max(0, Math.min(rows, 30) - reservedLines); - return Math.max(1, Math.floor(availableLines / linesPerItem)); + // 每个服务器占用 1 行(标题)+ 1 行(错误信息或统计)+ 1 行(间隔) + return Math.max(1, Math.floor(availableLines / 3)); }, [rows]); + // 计算标签列宽度:找到最长的服务器名称,加上前缀和图标 + const labelColumnWidth = useMemo(() => { + if (serverCount === 0) return 0; + const longestName = Math.max(...statuses.map((s) => s.name.length)); + const contentWidth = longestName + 5; // +2 for prefix "> " or " ", +3 for icon "✓ " + const maxAllowed = Math.max(15, Math.floor((columns - 6) * 0.4)); // 容器40%宽度,至少15列 + return Math.min(contentWidth, maxAllowed); + }, [statuses, serverCount, columns]); + const safeIndex = useMemo(() => { - if (flatItems.length === 0) return 0; - return Math.max(0, Math.min(index, flatItems.length - 1)); - }, [index, flatItems.length]); + if (serverCount === 0) return 0; + return Math.max(0, Math.min(selectedIndex, serverCount - 1)); + }, [selectedIndex, serverCount]); - const scrollOffset = useMemo(() => { - if (safeIndex < maxVisible) return 0; - return safeIndex - maxVisible + 1; - }, [safeIndex, maxVisible]); + // 自动滚动确保选中项可见 + React.useEffect(() => { + if (safeIndex < scrollOffset) { + setScrollOffset(safeIndex); + } else if (safeIndex >= scrollOffset + maxVisible) { + setScrollOffset(safeIndex - maxVisible + 1); + } + }, [safeIndex, scrollOffset, maxVisible]); - const visibleItems = useMemo(() => { - return flatItems.slice(scrollOffset, scrollOffset + maxVisible); - }, [flatItems, scrollOffset, maxVisible]); + const visibleServers = useMemo(() => { + return statuses.slice(scrollOffset, scrollOffset + maxVisible); + }, [statuses, scrollOffset, maxVisible]); useInput((input, key) => { if (key.escape || (key.ctrl && (input === "c" || input === "C"))) { onCancel(); return; } - if (flatItems.length === 0) { + if (serverCount === 0) { return; } if (key.upArrow) { - setIndex((i) => Math.max(0, i - 1)); + onSelect(Math.max(0, selectedIndex - 1)); return; } if (key.downArrow) { - setIndex((i) => Math.min(flatItems.length - 1, i + 1)); + onSelect(Math.min(serverCount - 1, selectedIndex + 1)); return; } if (key.pageUp) { - setIndex((i) => Math.max(0, i - maxVisible)); + onSelect(Math.max(0, selectedIndex - maxVisible)); return; } if (key.pageDown) { - setIndex((i) => Math.min(flatItems.length - 1, i + maxVisible)); + onSelect(Math.min(serverCount - 1, selectedIndex + maxVisible)); return; } if (key.home) { - setIndex(0); + onSelect(0); return; } if (key.end) { - setIndex(flatItems.length - 1); + onSelect(serverCount - 1); + } + // Enter 键进入详情 + if (key.return) { + onEnter(); + return; } }); @@ -102,24 +168,6 @@ export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement const startingCount = statuses.filter((s) => s.status === "starting").length; const failedCount = statuses.filter((s) => s.status === "failed").length; - if (statuses.length === 0) { - return ( - - - - Manage MCP servers - - 0 servers - - - No MCP servers configured. - Add MCP servers to your settings to get started. - - Esc to close - - ); - } - return ( - {visibleItems.map((item, i) => { + {visibleServers.map((status, i) => { const actualIndex = scrollOffset + i; const isSelected = actualIndex === safeIndex; - if (item.kind === "server") { - return ; - } - if (item.kind === "error") { - return ; - } return ( - ); })} - {scrollOffset > 0 || scrollOffset + maxVisible < flatItems.length ? ( + {scrollOffset > 0 || scrollOffset + maxVisible < serverCount ? ( - {scrollOffset > 0 ? … {scrollOffset} items above. : null} - {scrollOffset + maxVisible < flatItems.length ? ( - … {flatItems.length - scrollOffset - maxVisible} items below. + {scrollOffset > 0 ? … {scrollOffset} servers above. : null} + {scrollOffset + maxVisible < serverCount ? ( + … {serverCount - scrollOffset - maxVisible} servers below. ) : null} ) : null} {/* Footer */} - - ↑/↓ navigate · PgUp/PgDn page · Esc cancel + + ↑/↓ navigate · Enter view details · Esc cancel ); } -function ServerRow({ status, selected }: { status: McpServerStatus; selected: boolean }): React.ReactElement { - const icon = status.status === "ready" ? "✔" : status.status === "failed" ? "✖" : "●"; +function ServerRow({ + status, + selected, + labelColumnWidth, +}: { + status: McpServerStatus; + selected: boolean; + labelColumnWidth: number; +}): React.ReactElement { + const icon = status.status === "ready" ? "✓" : status.status === "failed" ? "✗" : "●"; const color = status.status === "ready" ? "green" : status.status === "failed" ? "red" : "yellow"; + + // 加载动画:循环显示 (空) → . → .. → ... → (空) → ... + const [dots, setDots] = React.useState(0); + React.useEffect(() => { + if (status.status !== "starting") return; + const interval = setInterval(() => { + setDots((d) => (d + 1) % 4); // 0 → 1 → 2 → 3 → 0 ... + }, 500); + return () => clearInterval(interval); + }, [status.status]); + const detail = status.status === "ready" ? `Ready (${status.toolCount} tools, ${status.promptCount} prompts, ${status.resourceCount} resources)` : status.status === "failed" - ? `Failed (${status.error ?? "unknown error"})` - : "Starting..."; + ? `Failed` + : "Starting" + (dots > 0 ? ".".repeat(dots) : " "); // 动态显示 (空) / . / .. / ... return ( - - {selected ? "› " : " "} - - {icon} - {status.name} - — {detail} - + + {/* Server row */} + + + + {selected ? "> " : " "} + {icon} + {status.name} + + + + {detail} + + + + {/* Error message for failed servers */} + {status.status === "failed" && status.error ? : null} ); } -function CapabilityRow({ - kind, - name, - selected, +// ==================== 服务器详情视图 ==================== +function ServerDetailView({ + server, + onBack, + onCancel, + rows, + columns, }: { - kind: "tool" | "prompt" | "resource"; - name: string; - selected: boolean; + server: McpServerStatus; + onBack: () => void; + onCancel: () => void; + rows: number; + columns: number; }): React.ReactElement { - const prefix = kind === "tool" ? "🔧" : kind === "prompt" ? "📝" : "📦"; + const [activeIndex, setActiveIndex] = useState(0); + + // 合并所有 items(tools, prompts, resources) + const allItems = useMemo(() => { + const items: { type: string; name: string }[] = []; + server.tools.forEach((tool) => items.push({ type: "tool", name: tool })); + server.prompts.forEach((prompt) => items.push({ type: "prompt", name: prompt })); + server.resources.forEach((resource) => items.push({ type: "resource", name: resource })); + return items; + }, [server]); + + const totalItems = allItems.length; + + const maxVisible = useMemo(() => { + const reservedLines = 10; // header + title + stats + footer + borders + const availableLines = Math.max(0, Math.min(rows, 28) - reservedLines); + return Math.max(1, availableLines); + }, [rows]); + + // 使用 ref 跟踪 visibleStart,避免循环依赖 + const visibleStartRef = React.useRef(0); + + // 计算可见窗口起始位置:当 activeIndex 超出可见区域时才滚动(类似终端光标行为) + const visibleStart = useMemo(() => { + if (totalItems === 0) return 0; + + const currentStart = visibleStartRef.current; + let newStart = currentStart; + + // 如果 activeIndex 在当前可见窗口之前,滚动到 activeIndex + if (activeIndex < currentStart) { + newStart = activeIndex; + } + // 如果 activeIndex 在当前可见窗口之后,滚动到 activeIndex + else if (activeIndex >= currentStart + maxVisible) { + newStart = activeIndex - maxVisible + 1; + } + + console.log("maxVisible:", maxVisible); + + // 限制在合法范围内 + newStart = Math.max(0, Math.min(newStart, Math.max(0, totalItems - maxVisible))); + + // 更新 ref + visibleStartRef.current = newStart; + + return newStart; + }, [activeIndex, maxVisible, totalItems]); + + const visibleItems = allItems.slice(visibleStart, visibleStart + maxVisible); + + useInput((input, key) => { + if (key.escape || (key.ctrl && (input === "c" || input === "C"))) { + onCancel(); + return; + } + if (key.escape) { + onBack(); + return; + } + // Space 或 Enter 键返回一级菜单 + if (input === " " || key.return) { + onBack(); + return; + } + if (key.upArrow) { + setActiveIndex((prev) => Math.max(0, prev - 1)); + return; + } + if (key.downArrow) { + setActiveIndex((prev) => Math.min(totalItems - 1, prev + 1)); + return; + } + if (key.pageUp) { + setActiveIndex((prev) => Math.max(0, prev - maxVisible)); + return; + } + if (key.pageDown) { + setActiveIndex((prev) => Math.min(totalItems - 1, prev + maxVisible)); + return; + } + if (key.home) { + setActiveIndex(0); + return; + } + if (key.end) { + setActiveIndex(totalItems - 1); + } + }); + + const icon = "✓"; + const color = "green"; + + return ( + + + {/* Header row */} + + {icon} + + {server.name} + + — Details + + {activeIndex + 1}/{totalItems} + + + {/* Server info */} + + + {server.toolCount} tools, {server.promptCount} prompts, {server.resourceCount} resources + + + {/* Items list */} + + {visibleStart > 0 ? ( + + + + ) : ( + + )} + + {visibleItems.length === 0 ? ( + + No items available + + ) : ( + visibleItems.map((item, idx) => { + const actualIndex = visibleStart + idx; + const isSelected = actualIndex === activeIndex; + return ; + }) + )} + + {visibleStart > 0 || visibleStart + maxVisible < totalItems ? ( + + {totalItems - visibleStart - maxVisible > 0 ? : } + {visibleStart > 0 ? … {visibleStart} items above. : null} + {totalItems - visibleStart - maxVisible > 0 ? ( + … {totalItems - visibleStart - maxVisible} items below. + ) : null} + + ) : null} + + {/* Footer */} + + ↑/↓ scroll · Space/Enter back · Esc close + + + + ); +} + +function ItemRow({ item, selected }: { item: { type: string; name: string }; selected: boolean }): React.ReactElement { + const icon = item.type === "tool" ? "🔧" : item.type === "prompt" ? "📝" : "📦"; + return ( - - {selected ? "› " : " "} - - {prefix} {name} + + {icon} + + {item.name} ); @@ -246,7 +496,15 @@ function ErrorRow({ error }: { error: string }): React.ReactElement { const lines = error.split("\n").filter((line) => line.trim().length > 0); return ( - + {lines.map((line, index) => ( diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 6a11431..6c0f8ea 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -722,7 +722,7 @@ export const PromptInput = React.memo(function PromptInput({ ({ key: skill.path || skill.name, @@ -742,8 +742,8 @@ export const PromptInput = React.memo(function PromptInput({ title={modelDropdownStep === "model" ? "Select Model" : "Select Thinking Mode"} helpText={ modelDropdownStep === "model" - ? "space/enter select model · esc to cancel" - : "space/enter apply · esc to cancel" + ? "Space/Enter select model · Esc to cancel" + : "Space/Enter apply · Esc to cancel" } items={modelDropdownItems.map((item) => ({ key: item.label, diff --git a/src/ui/SessionList.tsx b/src/ui/SessionList.tsx index 67f2e10..fdbd1fe 100644 --- a/src/ui/SessionList.tsx +++ b/src/ui/SessionList.tsx @@ -126,7 +126,7 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac return ( - {actualIndex === safeIndex ? "› " : " "} + {actualIndex === safeIndex ? "> " : " "} diff --git a/src/ui/SlashCommandMenu.tsx b/src/ui/SlashCommandMenu.tsx index 9b79293..436be83 100644 --- a/src/ui/SlashCommandMenu.tsx +++ b/src/ui/SlashCommandMenu.tsx @@ -16,13 +16,13 @@ const SlashCommandMenu = React.memo(function SlashCommandMenu({ maxVisible = 6, width, }: SlashCommandMenuProps): React.ReactElement | null { - // 计算标签列最佳宽度:包含前缀"› "或" "(2字符),不超过容器一半(扣除gap) + // 计算标签列最佳宽度:包含前缀"> "或" "(2字符),不超过容器一半(扣除gap) const labelColumnWidth = React.useMemo(() => { if (items.length === 0) { return 0; } const longestLabel = Math.max(...items.map((s) => s.label.length)); - const contentWidth = longestLabel + 2; // +2 for prefix "› " or " " + const contentWidth = longestLabel + 2; // +2 for prefix "> " or " " const maxAllowed = Math.max(10, (width - 2) >> 1); // 容器50%宽度(减去gap),至少保留10列 return Math.min(contentWidth, maxAllowed); }, [items, width]); @@ -51,7 +51,7 @@ const SlashCommandMenu = React.memo(function SlashCommandMenu({ - {actualIndex === activeIndex ? "› " : " "} + {actualIndex === activeIndex ? "> " : " "} {formatSlashCommandLabel(item)} From b858c8755978480321f79dd8068376c7c45408d4 Mon Sep 17 00:00:00 2001 From: hcyang Date: Thu, 14 May 2026 23:58:18 +0800 Subject: [PATCH 006/129] chore: update McpStatusList --- src/ui/McpStatusList.tsx | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/ui/McpStatusList.tsx b/src/ui/McpStatusList.tsx index e448b5c..e7912d9 100644 --- a/src/ui/McpStatusList.tsx +++ b/src/ui/McpStatusList.tsx @@ -321,7 +321,7 @@ function ServerDetailView({ const maxVisible = useMemo(() => { const reservedLines = 10; // header + title + stats + footer + borders - const availableLines = Math.max(0, Math.min(rows, 28) - reservedLines); + const availableLines = Math.max(0, Math.min(rows, 30) - reservedLines); return Math.max(1, availableLines); }, [rows]); @@ -344,8 +344,6 @@ function ServerDetailView({ newStart = activeIndex - maxVisible + 1; } - console.log("maxVisible:", maxVisible); - // 限制在合法范围内 newStart = Math.max(0, Math.min(newStart, Math.max(0, totalItems - maxVisible))); @@ -412,7 +410,7 @@ function ServerDetailView({ {/* Header row */} {icon} - + {server.name} — Details @@ -422,7 +420,7 @@ function ServerDetailView({ {/* Server info */} - + {server.toolCount} tools, {server.promptCount} prompts, {server.resourceCount} resources @@ -455,7 +453,7 @@ function ServerDetailView({ visibleItems.map((item, idx) => { const actualIndex = visibleStart + idx; const isSelected = actualIndex === activeIndex; - return ; + return ; }) )} @@ -482,7 +480,7 @@ function ItemRow({ item, selected }: { item: { type: string; name: string }; sel const icon = item.type === "tool" ? "🔧" : item.type === "prompt" ? "📝" : "📦"; return ( - + {icon} {item.name} From f3554dfedc321c67fe676ce593f98c38e816576b Mon Sep 17 00:00:00 2001 From: dengmik-commits <270912164+dengmik-commits@users.noreply.github.com> Date: Fri, 15 May 2026 10:30:20 +0800 Subject: [PATCH 007/129] fix: add Kitty keyboard protocol Shift+Enter sequences for broader terminal compatibility SHIFT_RETURN_SEQUENCES now covers both xterm modifyOtherKeys (Shift=2) and Kitty keyboard protocol (Shift=1) encodings. Also clear input when key.return is true to prevent escape sequence artifacts from leaking into the text buffer. --- src/tests/promptInputKeys.test.ts | 2 +- src/ui/prompt/useTerminalInput.ts | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/tests/promptInputKeys.test.ts b/src/tests/promptInputKeys.test.ts index 69d2075..372dfc7 100644 --- a/src/tests/promptInputKeys.test.ts +++ b/src/tests/promptInputKeys.test.ts @@ -80,7 +80,7 @@ test("parseTerminalInput keeps BS payload for meta+backspace", () => { test("parseTerminalInput recognizes shifted return sequences", () => { const { input, key } = parseTerminalInput("\u001B\r"); - assert.equal(input, "\r"); + assert.equal(input, ""); assert.equal(key.return, true); assert.equal(key.shift, true); assert.equal(key.meta, false); diff --git a/src/ui/prompt/useTerminalInput.ts b/src/ui/prompt/useTerminalInput.ts index 8013ff6..ea368b5 100644 --- a/src/ui/prompt/useTerminalInput.ts +++ b/src/ui/prompt/useTerminalInput.ts @@ -26,7 +26,15 @@ const BACKSPACE_BYTES = new Set(["\u007F", "\b"]); const FORWARD_DELETE_SEQUENCES = new Set(["\u001B[3~", "\u001B[P"]); const HOME_SEQUENCES = new Set(["\u001B[H", "\u001B[1~", "\u001B[7~", "\u001BOH"]); const END_SEQUENCES = new Set(["\u001B[F", "\u001B[4~", "\u001B[8~", "\u001BOF"]); -const SHIFT_RETURN_SEQUENCES = new Set(["\u001B\r", "\u001B[13;2u", "\u001B[13;2~", "\u001B[27;2;13~"]); +const SHIFT_RETURN_SEQUENCES = new Set([ + "\u001B\r", + "\u001B[13;2u", // xterm modifyOtherKeys: keycode=13 (Enter), modifier=2 (Shift) + "\u001B[13;1u", // Kitty keyboard protocol: keycode=13, modifier=1 (Shift) + "\u001B[13;2~", + "\u001B[13;1~", // tmux / alternate terminals may use ~ terminator + "\u001B[27;2;13~", + "\u001B[27;1;13~", // extended format, Kitty encoding +]); const META_RETURN_SEQUENCES = new Set(["\u001B[13;3u", "\u001B[13;4u"]); const CTRL_LEFT_SEQUENCES = new Set(["\u001B[1;5D", "\u001B[5D"]); const CTRL_RIGHT_SEQUENCES = new Set(["\u001B[1;5C", "\u001B[5C"]); @@ -162,7 +170,7 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: key.shift = true; } - if (key.tab || key.backspace || key.delete) { + if (key.tab || key.backspace || key.delete || key.return) { input = ""; } From efde004299e5892b132412845d5a3f08e13242d2 Mon Sep 17 00:00:00 2001 From: dengmik-commits <270912164+dengmik-commits@users.noreply.github.com> Date: Fri, 15 May 2026 11:25:43 +0800 Subject: [PATCH 008/129] fix: use dynamic modifier parsing for Shift+Enter recognition MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace exact string matching in SHIFT_RETURN_SEQUENCES with CSI parameter parsing that checks modifier bits. Windows Terminal sends ESC[13;130u (modifier=128+2) where 128 is a terminal-specific flag — the old code only matched modifier=2 exactly. Also enable Kitty progressive enhancement (ESC[>1u) alongside xterm modifyOtherKeys, since Windows Terminal requires the Kitty protocol to report modified keys. --- src/tests/promptInputKeys.test.ts | 4 +-- src/ui/prompt/cursor.ts | 6 ++-- src/ui/prompt/useTerminalInput.ts | 52 +++++++++++++++++++++++++++---- 3 files changed, 52 insertions(+), 10 deletions(-) diff --git a/src/tests/promptInputKeys.test.ts b/src/tests/promptInputKeys.test.ts index 372dfc7..8952a3d 100644 --- a/src/tests/promptInputKeys.test.ts +++ b/src/tests/promptInputKeys.test.ts @@ -108,8 +108,8 @@ test("parseTerminalInput recognizes alternate shifted return sequences", () => { }); test("terminal extended key helpers request and restore modifyOtherKeys mode", () => { - assert.equal(enableTerminalExtendedKeys(), "\u001B[>4;1m"); - assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m"); + assert.equal(enableTerminalExtendedKeys(), "\u001B[>4;1m\u001B[>1u"); + assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m\u001B[ { diff --git a/src/ui/prompt/cursor.ts b/src/ui/prompt/cursor.ts index 2668470..5eff1de 100644 --- a/src/ui/prompt/cursor.ts +++ b/src/ui/prompt/cursor.ts @@ -40,12 +40,14 @@ function disableTerminalFocusReporting(): string { return "\u001B[?1004l"; } +// xterm modifyOtherKeys + Kitty progressive enhancement. +// Both are needed: some terminals (incl. Windows Terminal) only respond to Kitty. export function enableTerminalExtendedKeys(): string { - return "\u001B[>4;1m"; + return "\u001B[>4;1m\u001B[>1u"; } export function disableTerminalExtendedKeys(): string { - return "\u001B[>4;0m"; + return "\u001B[>4;0m\u001B[1u) sends plain Enter as ESC[13u +// or ESC[13;NUMBERu with extra flags; xterm sends ESC[13;2u for Shift. +const CSI_RETURN_RE = /^\u001B\[13;(\d+)[u~]$/; +const CSI_EXTENDED_RETURN_RE = /^\u001B\[27;(\d+);13~$/; + +function isReturn(raw: string): boolean { + if (raw === "\r") return true; + if (SHIFT_RETURN_SEQUENCES.has(raw)) return true; + if (META_RETURN_SEQUENCES.has(raw)) return true; + return CSI_RETURN_RE.test(raw) || CSI_EXTENDED_RETURN_RE.test(raw); +} const META_RETURN_SEQUENCES = new Set(["\u001B[13;3u", "\u001B[13;4u"]); const CTRL_LEFT_SEQUENCES = new Set(["\u001B[1;5D", "\u001B[5D"]); const CTRL_RIGHT_SEQUENCES = new Set(["\u001B[1;5C", "\u001B[5C"]); @@ -121,10 +161,10 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: end: END_SEQUENCES.has(raw), pageDown: raw === "\u001B[6~", pageUp: raw === "\u001B[5~", - return: raw === "\r" || SHIFT_RETURN_SEQUENCES.has(raw) || META_RETURN_SEQUENCES.has(raw), + return: isReturn(raw), escape: raw === "\u001B", ctrl: CTRL_LEFT_SEQUENCES.has(raw) || CTRL_RIGHT_SEQUENCES.has(raw), - shift: SHIFT_RETURN_SEQUENCES.has(raw), + shift: isShiftReturn(raw), tab: raw === "\t" || raw === "\u001B[Z", backspace: BACKSPACE_BYTES.has(raw), delete: FORWARD_DELETE_SEQUENCES.has(raw), From 35b686d55fa1a6fcd91f3845d49b17d5975fcd61 Mon Sep 17 00:00:00 2001 From: hcyang Date: Fri, 15 May 2026 13:34:27 +0800 Subject: [PATCH 009/129] =?UTF-8?q?test(session):=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E4=BB=A5=E5=8C=85=E6=8B=AC=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E5=92=8C=E8=B5=84=E6=BA=90=E8=AE=A1=E6=95=B0=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 getMcpStatus 的断言中添加 promptCount、prompts、resourceCount 和 resources 字段 - 确保各状态对象包含完整的提示和资源数组信息 - 维护现有工具和连接状态的正确性 - 扩展测试覆盖,支持提示和资源相关的状态字段验证 --- src/tests/session.test.ts | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 2ac6c29..60147ea 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -410,7 +410,17 @@ rl.on("line", (line) => { const initPromise = manager.initMcpServers({ smoke: { command: process.execPath, args: [serverPath] } }); assert.deepEqual(manager.getMcpStatus(), [ - { name: "smoke", status: "starting", connected: false, toolCount: 0, tools: [] }, + { + name: "smoke", + status: "starting", + connected: false, + toolCount: 0, + tools: [], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], + }, ]); await initPromise; @@ -422,6 +432,10 @@ rl.on("line", (line) => { connected: true, toolCount: 2, tools: ["mcp__smoke__echo", "mcp__smoke__count"], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], }, ]); const mcpManager = (manager as any).mcpManager; @@ -457,7 +471,17 @@ test("SessionManager reports configured MCP servers as starting before initializ }); assert.deepEqual(manager.getMcpStatus(), [ - { name: "playwright", status: "starting", connected: false, toolCount: 0, tools: [] }, + { + name: "playwright", + status: "starting", + connected: false, + toolCount: 0, + tools: [], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], + }, ]); }); From 5a996281dce9cb2ef6371374669aea304bdbec7c Mon Sep 17 00:00:00 2001 From: hcyang Date: Fri, 15 May 2026 13:37:13 +0800 Subject: [PATCH 010/129] =?UTF-8?q?refactor(ui):=20=E7=A7=BB=E9=99=A4McpSt?= =?UTF-8?q?atusList=E4=B8=AD=E4=B8=8D=E5=BF=85=E8=A6=81=E7=9A=84React?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E5=92=8C=E6=96=87=E6=9C=AC=E6=98=BE=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除了未使用的useEffect导入,简化依赖引入 - 移除了界面中显示的当前索引及总数文本,减少冗余信息显示 - 优化了McpStatusList组件代码的可读性和整洁度 --- src/ui/McpStatusList.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/ui/McpStatusList.tsx b/src/ui/McpStatusList.tsx index e7912d9..1f49bd6 100644 --- a/src/ui/McpStatusList.tsx +++ b/src/ui/McpStatusList.tsx @@ -1,4 +1,4 @@ -import React, { useState, useMemo, useCallback, useEffect } from "react"; +import React, { useState, useMemo, useCallback } from "react"; import { Box, Text, useInput, useWindowSize } from "ink"; import type { McpServerStatus } from "../mcp/mcp-manager"; @@ -414,9 +414,6 @@ function ServerDetailView({ {server.name} — Details - - {activeIndex + 1}/{totalItems} - {/* Server info */} From bee349bb8ca700eefe96615cba4b51352bdc907b Mon Sep 17 00:00:00 2001 From: hcyang Date: Fri, 15 May 2026 14:09:28 +0800 Subject: [PATCH 011/129] =?UTF-8?q?fix(mcp-client):=20=E5=A2=9E=E5=BC=BA?= =?UTF-8?q?=E5=8D=8F=E8=AE=AE=E7=89=88=E6=9C=AC=E6=A0=A1=E9=AA=8C=E5=92=8C?= =?UTF-8?q?JSON-RPC=E6=89=B9=E5=A4=84=E7=90=86=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在初始化时验证服务器返回的MCP协议版本,拒绝不支持的版本 - 支持处理JSON-RPC批量消息,逐条分发处理 - 抽离单条消息处理逻辑,统一处理通知和响应 - 防止通知处理器异常导致读取循环崩溃 fix(ui): 优化键盘交互提示与布局间距 - 移除Esc键作为取消操作,避免与Ctrl+C冲突 - 更新底部提示,明确Ctrl+C为关闭操作,Esc为返回操作 - 调整MessageView内容左边距,使间距更合理 --- src/mcp/mcp-client.ts | 70 ++++++++++++++++++++++++++++------------ src/ui/McpStatusList.tsx | 4 +-- src/ui/MessageView.tsx | 2 +- 3 files changed, 53 insertions(+), 23 deletions(-) diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts index a086c1d..f89e11d 100644 --- a/src/mcp/mcp-client.ts +++ b/src/mcp/mcp-client.ts @@ -178,7 +178,19 @@ export class McpClient { }, timeoutMs ) - .then(() => { + .then((result) => { + // Validate protocol version from server response (per MCP spec §4.2.1.2) + const initResult = result as { protocolVersion?: string } | undefined; + const serverVersion = initResult?.protocolVersion; + if (serverVersion && serverVersion !== "2025-03-26" && serverVersion !== "2024-11-05") { + reject( + new Error( + `Unsupported MCP protocol version "${serverVersion}" from server "${this.serverName}". ` + + `Client supports 2025-03-26 and 2024-11-05.` + ) + ); + return; + } // Send initialized notification this.sendNotification("notifications/initialized"); resolve(); @@ -302,36 +314,54 @@ export class McpClient { try { const parsed: unknown = JSON.parse(line); - // Handle notifications (no id field — server-initiated) - if (parsed && typeof parsed === "object" && !("id" in parsed)) { - const notification = parsed as JsonRpcNotification; - if (this.notificationHandler && typeof notification.method === "string") { - try { - this.notificationHandler(notification.method, notification.params); - } catch { - // Swallow handler errors to avoid crashing the reader loop + // Handle JSON-RPC batch (array of requests/notifications/responses) + // Per MCP 2025-03-26 §4.1.1.3: implementations MUST support receiving batches. + if (Array.isArray(parsed)) { + for (const item of parsed) { + if (item && typeof item === "object") { + this.handleSingleMessage(item); } } return; } - // Handle responses to our requests - const message = parsed as JsonRpcResponse; - if (message.id !== undefined && this.pendingRequests.has(message.id)) { - const pending = this.pendingRequests.get(message.id)!; - this.pendingRequests.delete(message.id); - clearTimeout(pending.timer); - if (message.error) { - pending.reject(this.withStderr(`MCP error: ${message.error.message}`)); - } else { - pending.resolve(message.result); - } + // Handle single message + if (parsed && typeof parsed === "object") { + this.handleSingleMessage(parsed); } } catch { // Ignore unparseable lines } } + private handleSingleMessage(msg: object): void { + // Handle notifications (no id field — server-initiated) + if (!("id" in msg)) { + const notification = msg as unknown as JsonRpcNotification; + if (this.notificationHandler && typeof notification.method === "string") { + try { + this.notificationHandler(notification.method, notification.params); + } catch { + // Swallow handler errors to avoid crashing the reader loop + } + } + return; + } + + // Handle responses to our requests + const message = msg as unknown as JsonRpcResponse; + if (message.id !== undefined && this.pendingRequests.has(message.id)) { + const pending = this.pendingRequests.get(message.id)!; + this.pendingRequests.delete(message.id); + clearTimeout(pending.timer); + if (message.error) { + pending.reject(this.withStderr(`MCP error: ${message.error.message}`)); + } else { + pending.resolve(message.result); + } + } + } + private withNpxYesArg(command: string, args: string[]): string[] { const executable = path .basename(command) diff --git a/src/ui/McpStatusList.tsx b/src/ui/McpStatusList.tsx index 1f49bd6..0f5f906 100644 --- a/src/ui/McpStatusList.tsx +++ b/src/ui/McpStatusList.tsx @@ -356,7 +356,7 @@ function ServerDetailView({ const visibleItems = allItems.slice(visibleStart, visibleStart + maxVisible); useInput((input, key) => { - if (key.escape || (key.ctrl && (input === "c" || input === "C"))) { + if (key.ctrl && (input === "c" || input === "C")) { onCancel(); return; } @@ -466,7 +466,7 @@ function ServerDetailView({ {/* Footer */} - ↑/↓ scroll · Space/Enter back · Esc close + ↑/↓ scroll · Space/Enter back · Esc back · Ctrl+C close diff --git a/src/ui/MessageView.tsx b/src/ui/MessageView.tsx index acdc645..c8793fc 100644 --- a/src/ui/MessageView.tsx +++ b/src/ui/MessageView.tsx @@ -47,7 +47,7 @@ export function MessageView({ message, collapsed, width = 80 }: Props): React.Re return ( - + {content ? {renderMarkdown(content)} : null} From c81937434575bee3eb734fcf28d9bec01bad4667 Mon Sep 17 00:00:00 2001 From: hcyang Date: Fri, 15 May 2026 15:10:15 +0800 Subject: [PATCH 012/129] =?UTF-8?q?feat(ui):=20=E6=B7=BB=E5=8A=A0=E6=97=A0?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=99=A8=E6=97=B6=E6=8C=89Esc=E9=94=AE?= =?UTF-8?q?=E9=80=80=E5=87=BA=E7=9A=84=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在McpStatusList组件中监听键盘输入事件 - 当服务器列表为空时,按Esc键或Ctrl+C触发退出操作 - 确保用户可通过快捷键安全退出无服务器状态界面 --- src/ui/McpStatusList.tsx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/ui/McpStatusList.tsx b/src/ui/McpStatusList.tsx index 0f5f906..bdb1854 100644 --- a/src/ui/McpStatusList.tsx +++ b/src/ui/McpStatusList.tsx @@ -28,6 +28,13 @@ export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement } }, [statuses, selectedServerIndex]); + // 当没有服务器时,监听 Esc 键退出 + useInput((input, key) => { + if (statuses.length === 0 && (key.escape || (key.ctrl && (input === "c" || input === "C")))) { + onCancel(); + } + }); + if (statuses.length === 0) { return ( From a094524e8fd4e939b93e71d56743b0fd1a50806d Mon Sep 17 00:00:00 2001 From: hcyang Date: Fri, 15 May 2026 16:37:15 +0800 Subject: [PATCH 013/129] fix(ui): update string --- src/ui/McpStatusList.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/McpStatusList.tsx b/src/ui/McpStatusList.tsx index bdb1854..a09039d 100644 --- a/src/ui/McpStatusList.tsx +++ b/src/ui/McpStatusList.tsx @@ -241,7 +241,7 @@ function ServerListView({ {/* Footer */} - ↑/↓ navigate · Enter view details · Esc cancel + ↑/↓ navigate · Enter view details · Esc close From 9a2188407e71a66a46b1937a6798c094ae2a486f Mon Sep 17 00:00:00 2001 From: hcyang Date: Fri, 15 May 2026 16:42:27 +0800 Subject: [PATCH 014/129] fix(ui): update string --- src/ui/App.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/App.tsx b/src/ui/App.tsx index eea8091..44d5a70 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -160,7 +160,7 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R const resolved = resolveCurrentSettings(projectRoot); const summary = buildExitSummaryText({ session, messages: allMessages, model: resolved.model }); process.stdout.write("\n"); - process.stdout.write(chalk.rgb(128, 128, 128)("> /exit ")); + process.stdout.write(chalk.rgb(34, 154, 195)("> /exit ")); process.stdout.write("\n\n"); process.stdout.write(summary); process.stdout.write("\n\n"); From d480486a650ace02305e45bb12bb0355a47e56be Mon Sep 17 00:00:00 2001 From: hcyang Date: Fri, 15 May 2026 17:10:13 +0800 Subject: [PATCH 015/129] =?UTF-8?q?style(DropdownMenu):=20=E8=B0=83?= =?UTF-8?q?=E6=95=B4=E5=86=85=E8=BE=B9=E8=B7=9D=E4=BC=98=E5=8C=96=E4=B8=8B?= =?UTF-8?q?=E6=8B=89=E8=8F=9C=E5=8D=95=E5=B8=83=E5=B1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 为标题和底部帮助文本添加水平内边距 - 为可见条目列表及每个条目增加水平内边距 - 用包含容器包装可见条目,优化布局结构 - 保持原有选中指示和状态指示符渲染逻辑不变 --- src/ui/DropdownMenu.tsx | 48 ++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/src/ui/DropdownMenu.tsx b/src/ui/DropdownMenu.tsx index 3a963a5..a3083aa 100644 --- a/src/ui/DropdownMenu.tsx +++ b/src/ui/DropdownMenu.tsx @@ -123,6 +123,7 @@ const DropdownMenu = React.memo(function DropdownMenu({ borderRight={false} borderTop={false} borderLeft={false} + paddingX={1} > {title} @@ -138,31 +139,33 @@ const DropdownMenu = React.memo(function DropdownMenu({ ) : null} {/* Visible items */} - {visibleItems.map((item, idx) => { - const actualIndex = visibleStart + idx; - const isActive = actualIndex === activeIndex; + + {visibleItems.map((item, idx) => { + const actualIndex = visibleStart + idx; + const isActive = actualIndex === activeIndex; - // Use custom renderer if provided - if (renderItem) { - return {renderItem(item, isActive)}; - } + // Use custom renderer if provided + if (renderItem) { + return {renderItem(item, isActive)}; + } - // Default rendering with selection indicator and optional features - return ( - - - - {isActive ? "› " : " "} - {item.selected !== undefined ? (item.selected ? "●" : "○") : null} {item.label} - {item.statusIndicator ? ( - {item.statusIndicator.symbol} - ) : null} - + // Default rendering with selection indicator and optional features + return ( + + + + {isActive ? "› " : " "} + {item.selected !== undefined ? (item.selected ? "●" : "○") : null} {item.label} + {item.statusIndicator ? ( + {item.statusIndicator.symbol} + ) : null} + + + {item.description ? {`${item.description}`} : null} - {item.description ? {`${item.description}`} : null} - - ); - })} + ); + })} + {/* Scroll indicator - bottom */} {visibleStart + visibleItems.length < items.length ? ( @@ -180,6 +183,7 @@ const DropdownMenu = React.memo(function DropdownMenu({ borderRight={false} borderTop={true} borderLeft={false} + paddingX={1} > {helpText} From 309a887c652589c9467316d3412ccff15a4aec3f Mon Sep 17 00:00:00 2001 From: rock-solid-sites Date: Fri, 15 May 2026 14:53:10 +0200 Subject: [PATCH 016/129] docs: restructure translations as _en.md siblings per maintainer request; sync mcp.md with upstream/main --- docs/configuration.md | 201 ++++++++++++++++++++------------------- docs/configuration_en.md | 172 +++++++++++++++++++++++++++++++++ docs/mcp.md | 133 +++++++++++++------------- docs/mcp_en.md | 200 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 537 insertions(+), 169 deletions(-) create mode 100644 docs/configuration_en.md create mode 100644 docs/mcp_en.md diff --git a/docs/configuration.md b/docs/configuration.md index 369f8e4..f8e52c3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,71 +1,71 @@ -# Deep Code Configuration +# Deep Code 配置 -## Configuration Hierarchy +## 配置层级 -Configuration is applied in the following priority order (lower-numbered sources are overridden by higher-numbered ones): +配置按以下优先级顺序应用(数字较小的会被数字较大的覆盖): -| Layer | Configuration Source | Description | -| ----- | -------------------- | ---------------------------------------------- | -| 1 | Defaults | Hardcoded defaults within the application | -| 2 | User settings file | Global settings for the current user | -| 3 | Project settings file| Project-specific settings | -| 4 | Environment variables| System-wide or session-specific variables | +| 层级 | 配置来源 | 说明 | +| ---- | ------------ | ------------------------------------------- | +| 1 | 默认值 | 应用程序内硬编码的默认值 | +| 2 | 用户设置文件 | 当前用户的全局设置 | +| 3 | 项目设置文件 | 项目特定的设置 | +| 4 | 环境变量 | 系统范围或会话特定的变量 | -## Settings File +## 设置文件 -Deep Code uses the `settings.json` file for persistent configuration, supporting two storage locations: +Deep Code 使用 `settings.json` 设置文件进行持久化配置,支持两个层级的存放位置: -| File Type | Location | Scope | -| ------------------- | ----------------------------------------- | --------------------------------------------------------------------- | -| User settings file | `~/.deepcode/settings.json` | Applies to all Deep Code sessions for the current user. | -| Project settings file | `/.deepcode/settings.json` | Takes effect only when running Deep Code in that specific project. Project settings override user settings. | +| 文件类型 | 位置 | 作用范围 | +| ------------ | ---------------------------------- | ---------------------------------------------------- | +| 用户设置文件 | `~/.deepcode/settings.json` | 适用于当前用户的所有 Deep Code 会话。 | +| 项目设置文件 | `项目根目录/.deepcode/settings.json` | 仅在该特定项目中运行 Deep Code 时生效。项目设置会覆盖用户设置。 | -### Available Settings in `settings.json` +### `settings.json` 中的可用设置 -The following are all the top-level fields supported in `settings.json`, along with the sub-fields inside `env`: +以下是 `settings.json` 支持的全部顶层字段,以及 `env` 内部支持的子字段: -| Field | Type | Description | -| ------------------ | ------- | --------------------------------------------------------------------------- | -| `env` | object | Group of environment variables (see sub-field table below) | -| `model` | string | Model name. Takes precedence over `env.MODEL` | -| `thinkingEnabled` | boolean | Whether to enable thinking mode (enabled by default for DeepSeek V4 series)| -| `reasoningEffort` | string | Reasoning intensity, either `"high"` or `"max"` (default `"max"`) | -| `debugLogEnabled` | boolean | Enable debug log output (default `false`) | -| `notify` | string | Full path to a task-completion notification script (e.g., Slack notification script) | -| `webSearchTool` | string | Full path to a custom web search script | -| `mcpServers` | object | MCP server configurations (keys are service names, values are McpServerConfig objects) | +| 字段 | 类型 | 说明 | +| -------------------- | --------- | ------------------------------------------------------------------- | +| `env` | object | 环境变量分组(见下方子字段表) | +| `model` | string | 模型名称。优先级高于 `env.MODEL` | +| `thinkingEnabled` | boolean | 是否启用思考模式(DeepSeek V4 系列默认启用) | +| `reasoningEffort` | string | 推理强度,可选 `"high"` 或 `"max"`(默认 `"max"`) | +| `debugLogEnabled` | boolean | 是否启用调试日志输出(默认 `false`) | +| `notify` | string | 任务完成通知脚本的完整路径(如 Slack 通知脚本) | +| `webSearchTool` | string | 自定义联网搜索脚本的完整路径 | +| `mcpServers` | object | MCP 服务器配置(键为服务名,值为 McpServerConfig 对象) | -#### `env` Sub-fields +#### `env` 子字段 -| Field | Type | Description | -| ----------------- | ------ | ---------------------------------------------------------------- | -| `MODEL` | string | Model name, e.g. `"deepseek-v4-pro"`, `"deepseek-v4-flash"` | -| `BASE_URL` | string | Base URL for API requests, e.g. `"https://api.deepseek.com"` | -| `API_KEY` | string | API key | -| `THINKING_ENABLED`| string | Enable thinking mode | -| `REASONING_EFFORT`| string | Reasoning intensity | -| `DEBUG_LOG_ENABLED`| string| Enable debug log output | -| `` | string | Custom environment variable | +| 字段 | 类型 | 说明 | +| ---------- | ------ | ------------------------------------------------------------------ | +| `MODEL` | string | 模型名称。例如 `"deepseek-v4-pro"`、`"deepseek-v4-flash"` | +| `BASE_URL` | string | API 请求的基础 URL。例如 `"https://api.deepseek.com"` | +| `API_KEY` | string | API 密钥 | +| `THINKING_ENABLED` | string | 是否启用思考模式 | +| `REASONING_EFFORT` | string | 推理强度 | +| `DEBUG_LOG_ENABLED` | string | 是否启用调试日志输出 | +| `<其他任意KEY>` | string | 自定义环境变量 | -#### `thinkingEnabled` — Thinking Mode +#### `thinkingEnabled` — 思考模式 -Whether to enable DeepSeek thinking mode. Set to `true` to enable, `false` to disable. +是否启用 DeepSeek 思考模式。设置为 `true` 启用、`false` 禁用。 -- For `deepseek-v4-pro` and `deepseek-v4-flash`, thinking mode is **enabled by default**. -- For other models, thinking mode is **disabled by default**. +- 对于 `deepseek-v4-pro` 和 `deepseek-v4-flash`,思考模式**默认启用**。 +- 对于其他模型,思考模式**默认关闭**。 -#### `reasoningEffort` — Reasoning Intensity +#### `reasoningEffort` — 推理强度 -When thinking mode is enabled, controls the depth of the model’s reasoning: +当思考模式启用时,控制模型思考的深度: -| Value | Description | -| ------ | --------------------------------------------------------- | -| `max` | Maximum reasoning depth (default) | -| `high` | Higher reasoning depth with relatively lower token usage | +| 值 | 说明 | +| ------ | --------------------------------- | +| `max` | 最大推理深度(默认值) | +| `high` | 较高推理深度,token消耗相对较小 | -#### `notify` — Task Completion Notification +#### `notify` — 任务完成通知 -Set a full path to a shell script. When the AI assistant finishes a round of tasks, the script is executed automatically, which can be used to send notifications (e.g., a Slack message). +设置一个 Shell 脚本的完整路径。当 AI 助手完成一轮任务后,会自动执行该脚本,可用于发送通知(如 Slack 消息)。 ```json { @@ -73,9 +73,9 @@ Set a full path to a shell script. When the AI assistant finishes a round of tas } ``` -#### `webSearchTool` — Custom Web Search +#### `webSearchTool` — 自定义联网搜索 -Deep Code has a built-in, free-to-use Web Search tool. If you need custom search logic, set `webSearchTool` to the full path of an executable script: +Deep Code 内置免费可用的 Web Search 工具。如果需要自定义搜索逻辑,可将 `webSearchTool` 设为一个可执行脚本的完整路径: ```json { @@ -83,16 +83,16 @@ Deep Code has a built-in, free-to-use Web Search tool. If you need custom search } ``` -The script receives a search query as an argument and outputs results in JSON format for the AI. +脚本接收一个搜索查询参数,输出 JSON 格式的结果供 AI 使用。 -#### `mcpServers` — MCP Servers +#### `mcpServers` — MCP 服务器 -Configuration for MCP (Model Context Protocol) servers. The value is a key-value pair, where the key is the service name and the value is a server configuration object. +MCP(Model Context Protocol)服务器配置。值是键值对,键为服务名称,值为服务器配置对象。 ```json { "mcpServers": { - "": { + "<服务名>": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { @@ -103,70 +103,71 @@ Configuration for MCP (Model Context Protocol) servers. The value is a key-value } ``` -| McpServerConfig field | Type | Required | Description | -| --------------------- | -------- | -------- | ------------------------------------------------------------------------ | -| `command` | string | Yes | Executable path or command (e.g. `npx`, `node`, `python`) | -| `args` | string[] | No | List of arguments passed to the command | -| `env` | object | No | Environment variables passed to the MCP server process | +| McpServerConfig 字段 | 类型 | 必填 | 说明 | +| -------------------- | -------- | ---- | -------------------------------------------------------------------- | +| `command` | string | 是 | 可执行文件路径或命令(如 `npx`、`node`、`python`) | +| `args` | string[] | 否 | 传递给命令的参数列表 | +| `env` | object | 否 | 传递给 MCP 服务器进程的环境变量 | -> When `command` is `npx`, Deep Code automatically prepends `-y` to the arguments. +> 当 `command` 为 `npx` 时,Deep Code 会自动在参数前补充 `-y`。 -For detailed MCP usage instructions, refer to [mcp.md](mcp.md). +详细 MCP 使用说明请参考 [mcp.md](mcp.md)。 -#### `debugLogEnabled` — Debug Log -Set to `true` to enable detailed debug logging (default `false`), useful for troubleshooting API calls and tool execution. +#### `debugLogEnabled` — 调试日志 -## Environment Variable Priority +设为 `true` 可让程序输出详细的调试日志(默认 `false`),用于排查 API 调用和工具执行的问题。 -Environment variables are a common way to configure applications, especially for sensitive information (such as api-key) or settings that may change between environments. +## 环境变量优先级 -### Priority Principle +环境变量是配置应用程序的常用方式,尤其适用于敏感信息(如 api-key)或可能在不同环境之间更改的设置。 -Environment variable priority follows the logic of “the more specific and localized the configuration, the higher the priority”, and the override rule of “env files protect existing environment by default, system variables override env files”. (The `env` object in settings.json can be thought of as a type of env file.) +### 优先级原则 -Priority levels (from lowest to highest): -1. `env` defined at the top level of `settings.json` – this is a general configuration for the entire tool and all its subprocesses (global variables). Can be overridden by outer environment variables, but the environment variable KEY has the `DEEPCODE_` prefix removed. -2. `env` defined inside `mcpServers` in `settings.json` – this is the most specific configuration for a particular MCP service (local variables). Can be overridden by outer environment variables, but the KEY has the `MCP_` prefix removed. -3. Shell/system environment variables – operating system level. +环境变量优先级遵循“越具体、越局部的配置,优先级越高”和“env文件默认保护现有环境,系统变量高于env文件”的覆盖逻辑。(settings.json的env对象可以认为是一种env文件) -### Scenarios +优先级层级 (由低到高) +1. settings.json 外层的 env:这是针对整个工具及其所有子进程的通用配置(全局变量)。可被外层环境变量覆盖,但环境变量KEY会移除`DEEPCODE_`前缀。 +2. settings.json mcpServers 内定义的 env:这是针对特定 MCP 服务的最具体配置(局部变量)。可被外层环境变量覆盖,但环境变量KEY会移除`MCP_`前缀。 +3. Shell 环境系统变量:操作系统层面的环境变量。 -#### 1. Setting the model’s api_key and base_url +### 场景 -Applied in the following priority order (lower-numbered sources are overridden by higher-numbered ones) – using api_key as an example: +#### 一、设置模型的api_key, base_url -1. Hardcoded default: `""` -2. User-level settings.json: `{"env": {"API_KEY": "abc123"}}` -3. Project-level settings.json: `{"env": {"API_KEY": "abc123"}}` -4. System environment variable: `DEEPCODE_API_KEY=abc123 deepcode` +按以下优先级顺序应用(数字较小的会被数字较大的覆盖)(以api_key为例): -#### 2. Setting model, thinkingEnabled, and reasoningEffort +1. 硬编码默认值: `""` +2. 用户级settings.json: `{"env": {"API_KEY": "abc123"}}` +3. 项目级settings.json: `{"env": {"API_KEY": "abc123"}}` +4. 系统环境变量: `DEEPCODE_API_KEY=abc123 deepcode` -Applied in the following priority order (lower-numbered overridden by higher-numbered) – using thinkingEnabled as an example: +#### 二、设置模型的model, thinkingEnabled, reasoningEffort -1. Hardcoded default: `true` -2. User-level settings.json: `{"env": {"THINKING_ENABLED": "true"}}` -3. User-level settings.json: `{"thinkingEnabled": true}` -4. Project-level settings.json: `{"env": {"THINKING_ENABLED": "true"}}` -5. Project-level settings.json: `{"thinkingEnabled": true}` -6. System environment variable: `DEEPCODE_THINKING_ENABLED=true deepcode` +按以下优先级顺序应用(数字较小的会被数字较大的覆盖)(以thinkingEnabled为例): -#### 3. Setting environment variables for external scripts like notify and webSearchTool +1. 硬编码默认值: `true` +2. 用户级settings.json: `{"env": {"THINKING_ENABLED": "true"}}` +3. 用户级settings.json: `{"thinkingEnabled": true}` +4. 项目级settings.json: `{"env": {"THINKING_ENABLED": "true"}}` +5. 项目级settings.json: `{"thinkingEnabled": true}` +6. 系统环境变量: `DEEPCODE_THINKING_ENABLED=true deepcode` -Applied in the following priority order (lower-numbered overridden by higher-numbered) – using notify as an example: +#### 三、设置启动notify, webSearchTool等外挂脚本的环境变量 -1. Hardcoded default: `os.environ.get('WEBHOOK', '...') # notify script code` -2. User-level settings.json: `{"env": {"WEBHOOK": "..."}}` -3. Project-level settings.json: `{"env": {"WEBHOOK": "true"}}` -4. System environment variable: `DEEPCODE_WEBHOOK=... deepcode` +按以下优先级顺序应用(数字较小的会被数字较大的覆盖)(以notify为例): -#### 4. Setting environment variables for an MCP Service +1. 硬编码默认值:`os.environ.get('WEBHOOK', '...') # notify脚本代码` +2. 用户级settings.json: `{"env": {"WEBHOOK": "..."}}` +3. 项目级settings.json: `{"env": {"WEBHOOK": "true"}}` +4. 系统环境变量: `DEEPCODE_WEBHOOK=... deepcode` -Applied in the following priority order (lower-numbered overridden by higher-numbered) – using a GitHub MCP server as an example: +#### 四、设置MCP Service的环境变量 -1. User-level settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` -2. User-level settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` -3. Project-level settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` -4. Project-level settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` -5. System environment variable: `DEEPCODE_MCP_GITHUB_PERSONAL_ACCESS_TOKEN=... deepcode` \ No newline at end of file +按以下优先级顺序应用(数字较小的会被数字较大的覆盖)(以github MCP server为例): + +1. 用户级settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` +2. 用户级settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` +3. 项目级settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` +4. 项目级settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` +5. 系统环境变量: `DEEPCODE_MCP_GITHUB_PERSONAL_ACCESS_TOKEN=... deepcode` diff --git a/docs/configuration_en.md b/docs/configuration_en.md new file mode 100644 index 0000000..369f8e4 --- /dev/null +++ b/docs/configuration_en.md @@ -0,0 +1,172 @@ +# Deep Code Configuration + +## Configuration Hierarchy + +Configuration is applied in the following priority order (lower-numbered sources are overridden by higher-numbered ones): + +| Layer | Configuration Source | Description | +| ----- | -------------------- | ---------------------------------------------- | +| 1 | Defaults | Hardcoded defaults within the application | +| 2 | User settings file | Global settings for the current user | +| 3 | Project settings file| Project-specific settings | +| 4 | Environment variables| System-wide or session-specific variables | + +## Settings File + +Deep Code uses the `settings.json` file for persistent configuration, supporting two storage locations: + +| File Type | Location | Scope | +| ------------------- | ----------------------------------------- | --------------------------------------------------------------------- | +| User settings file | `~/.deepcode/settings.json` | Applies to all Deep Code sessions for the current user. | +| Project settings file | `/.deepcode/settings.json` | Takes effect only when running Deep Code in that specific project. Project settings override user settings. | + +### Available Settings in `settings.json` + +The following are all the top-level fields supported in `settings.json`, along with the sub-fields inside `env`: + +| Field | Type | Description | +| ------------------ | ------- | --------------------------------------------------------------------------- | +| `env` | object | Group of environment variables (see sub-field table below) | +| `model` | string | Model name. Takes precedence over `env.MODEL` | +| `thinkingEnabled` | boolean | Whether to enable thinking mode (enabled by default for DeepSeek V4 series)| +| `reasoningEffort` | string | Reasoning intensity, either `"high"` or `"max"` (default `"max"`) | +| `debugLogEnabled` | boolean | Enable debug log output (default `false`) | +| `notify` | string | Full path to a task-completion notification script (e.g., Slack notification script) | +| `webSearchTool` | string | Full path to a custom web search script | +| `mcpServers` | object | MCP server configurations (keys are service names, values are McpServerConfig objects) | + +#### `env` Sub-fields + +| Field | Type | Description | +| ----------------- | ------ | ---------------------------------------------------------------- | +| `MODEL` | string | Model name, e.g. `"deepseek-v4-pro"`, `"deepseek-v4-flash"` | +| `BASE_URL` | string | Base URL for API requests, e.g. `"https://api.deepseek.com"` | +| `API_KEY` | string | API key | +| `THINKING_ENABLED`| string | Enable thinking mode | +| `REASONING_EFFORT`| string | Reasoning intensity | +| `DEBUG_LOG_ENABLED`| string| Enable debug log output | +| `` | string | Custom environment variable | + +#### `thinkingEnabled` — Thinking Mode + +Whether to enable DeepSeek thinking mode. Set to `true` to enable, `false` to disable. + +- For `deepseek-v4-pro` and `deepseek-v4-flash`, thinking mode is **enabled by default**. +- For other models, thinking mode is **disabled by default**. + +#### `reasoningEffort` — Reasoning Intensity + +When thinking mode is enabled, controls the depth of the model’s reasoning: + +| Value | Description | +| ------ | --------------------------------------------------------- | +| `max` | Maximum reasoning depth (default) | +| `high` | Higher reasoning depth with relatively lower token usage | + +#### `notify` — Task Completion Notification + +Set a full path to a shell script. When the AI assistant finishes a round of tasks, the script is executed automatically, which can be used to send notifications (e.g., a Slack message). + +```json +{ + "notify": "/path/to/slack-notify.sh" +} +``` + +#### `webSearchTool` — Custom Web Search + +Deep Code has a built-in, free-to-use Web Search tool. If you need custom search logic, set `webSearchTool` to the full path of an executable script: + +```json +{ + "webSearchTool": "/path/to/my-search-script.sh" +} +``` + +The script receives a search query as an argument and outputs results in JSON format for the AI. + +#### `mcpServers` — MCP Servers + +Configuration for MCP (Model Context Protocol) servers. The value is a key-value pair, where the key is the service name and the value is a server configuration object. + +```json +{ + "mcpServers": { + "": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx" + } + } + } +} +``` + +| McpServerConfig field | Type | Required | Description | +| --------------------- | -------- | -------- | ------------------------------------------------------------------------ | +| `command` | string | Yes | Executable path or command (e.g. `npx`, `node`, `python`) | +| `args` | string[] | No | List of arguments passed to the command | +| `env` | object | No | Environment variables passed to the MCP server process | + +> When `command` is `npx`, Deep Code automatically prepends `-y` to the arguments. + +For detailed MCP usage instructions, refer to [mcp.md](mcp.md). + +#### `debugLogEnabled` — Debug Log + +Set to `true` to enable detailed debug logging (default `false`), useful for troubleshooting API calls and tool execution. + +## Environment Variable Priority + +Environment variables are a common way to configure applications, especially for sensitive information (such as api-key) or settings that may change between environments. + +### Priority Principle + +Environment variable priority follows the logic of “the more specific and localized the configuration, the higher the priority”, and the override rule of “env files protect existing environment by default, system variables override env files”. (The `env` object in settings.json can be thought of as a type of env file.) + +Priority levels (from lowest to highest): +1. `env` defined at the top level of `settings.json` – this is a general configuration for the entire tool and all its subprocesses (global variables). Can be overridden by outer environment variables, but the environment variable KEY has the `DEEPCODE_` prefix removed. +2. `env` defined inside `mcpServers` in `settings.json` – this is the most specific configuration for a particular MCP service (local variables). Can be overridden by outer environment variables, but the KEY has the `MCP_` prefix removed. +3. Shell/system environment variables – operating system level. + +### Scenarios + +#### 1. Setting the model’s api_key and base_url + +Applied in the following priority order (lower-numbered sources are overridden by higher-numbered ones) – using api_key as an example: + +1. Hardcoded default: `""` +2. User-level settings.json: `{"env": {"API_KEY": "abc123"}}` +3. Project-level settings.json: `{"env": {"API_KEY": "abc123"}}` +4. System environment variable: `DEEPCODE_API_KEY=abc123 deepcode` + +#### 2. Setting model, thinkingEnabled, and reasoningEffort + +Applied in the following priority order (lower-numbered overridden by higher-numbered) – using thinkingEnabled as an example: + +1. Hardcoded default: `true` +2. User-level settings.json: `{"env": {"THINKING_ENABLED": "true"}}` +3. User-level settings.json: `{"thinkingEnabled": true}` +4. Project-level settings.json: `{"env": {"THINKING_ENABLED": "true"}}` +5. Project-level settings.json: `{"thinkingEnabled": true}` +6. System environment variable: `DEEPCODE_THINKING_ENABLED=true deepcode` + +#### 3. Setting environment variables for external scripts like notify and webSearchTool + +Applied in the following priority order (lower-numbered overridden by higher-numbered) – using notify as an example: + +1. Hardcoded default: `os.environ.get('WEBHOOK', '...') # notify script code` +2. User-level settings.json: `{"env": {"WEBHOOK": "..."}}` +3. Project-level settings.json: `{"env": {"WEBHOOK": "true"}}` +4. System environment variable: `DEEPCODE_WEBHOOK=... deepcode` + +#### 4. Setting environment variables for an MCP Service + +Applied in the following priority order (lower-numbered overridden by higher-numbered) – using a GitHub MCP server as an example: + +1. User-level settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` +2. User-level settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` +3. Project-level settings.json: `{"mcpServers":{"github":{"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"..."}}}}` +4. Project-level settings.json: `{"env": {"MCP_GITHUB_PERSONAL_ACCESS_TOKEN": "..."}}` +5. System environment variable: `DEEPCODE_MCP_GITHUB_PERSONAL_ACCESS_TOKEN=... deepcode` \ No newline at end of file diff --git a/docs/mcp.md b/docs/mcp.md index 11adda5..73034a3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,22 +1,22 @@ -# Deep Code CLI MCP Configuration Guide +# Deep Code CLI MCP 配置指南 -Deep Code CLI supports MCP (Model Context Protocol), enabling AI assistants to connect with external tools and services such as GitHub, browsers, databases, and more. +Deep Code CLI 支持 MCP(Model Context Protocol),让 AI 助手能够连接外部工具和服务,如 GitHub、浏览器、数据库等。 -## Overview +## 概述 -Once MCP is configured, Deep Code can: +配置 MCP 后,Deep Code 可以: -- Operate on GitHub repositories (view issues, create PRs, search code, etc.) -- Control browsers (screenshots, clicks, form filling, etc.) -- Access the file system -- Connect to databases and APIs -- ...and any external service compatible with the MCP protocol +- 操作 GitHub 仓库(查看 Issues、创建 PR、搜索代码等) +- 操控浏览器(截图、点击、填表单等) +- 访问文件系统 +- 连接数据库和 API +- ...以及任何兼容 MCP 协议的外部服务 -MCP tools are named in Deep Code using the format `mcp____`, for example `mcp__github__search_code`. +MCP 工具在 Deep Code 中的命名格式为 `mcp__<服务名>__<工具名>`,例如 `mcp__github__search_code`。 -## Configuring MCP Servers +## 配置 MCP 服务器 -Edit `~/.deepcode/settings.json` and add the `mcpServers` field: +编辑 `~/.deepcode/settings.json`,添加 `mcpServers` 字段: ```json { @@ -28,30 +28,30 @@ Edit `~/.deepcode/settings.json` and add the `mcpServers` field: "thinkingEnabled": true, "reasoningEffort": "max", "mcpServers": { - "": { - "command": "", - "args": ["", ""], + "<服务名称>": { + "command": "<可执行文件>", + "args": ["<参数1>", "<参数2>"], "env": { - "": "" + "<环境变量>": "<值>" } } } } ``` -### Configuration Fields +### 配置项说明 -| Field | Type | Required | Description | -| --------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `command` | string | Yes | Path or command of the MCP server executable (e.g., `npx`, `node`, `python`). When the command is `npx`, Deep Code automatically prepends `-y` to the arguments. | -| `args` | string[] | No | List of arguments to pass to the command | -| `env` | object | No | Environment variables (e.g., API keys) to pass to the MCP server process | +| 字段 | 类型 | 必填 | 说明 | +| --------- | -------- | ---- | ---------------------------------------------------------------------------------------------------------------------- | +| `command` | string | 是 | MCP 服务器的可执行文件路径或命令(如 `npx`、`node`、`python`)。当命令是 `npx` 时,Deep Code 会自动在参数前补充 `-y`。 | +| `args` | string[] | 否 | 传递给命令的参数列表 | +| `env` | object | 否 | 传递给 MCP 服务器进程的环境变量(如 API Key) | -## Common MCP Examples +## 常用 MCP 示例 ### GitHub MCP -Allows Deep Code to directly operate on GitHub repositories (search code, manage issues/PRs, read/write files, etc.): +让 Deep Code 直接操作 GitHub 仓库(搜索代码、管理 Issue/PR、读写文件等): ```json { @@ -67,11 +67,11 @@ Allows Deep Code to directly operate on GitHub repositories (search code, manage } ``` -> Generate a GitHub Personal Access Token at [GitHub Settings > Developer settings > Personal access tokens](https://github.com/settings/tokens). +> GitHub Personal Access Token 可在 [GitHub Settings > Developer settings > Personal access tokens](https://github.com/settings/tokens) 生成。 -### Browser Control (Playwright) +### 浏览器控制(Playwright) -Lets Deep Code control a browser for screenshots, page interactions, etc.: +让 Deep Code 操控浏览器进行截图、页面操作等: ```json { @@ -84,9 +84,9 @@ Lets Deep Code control a browser for screenshots, page interactions, etc.: } ``` -### File System +### 文件系统 -Enables Deep Code to read and write files within a specified directory: +让 Deep Code 在指定目录中读写文件: ```json { @@ -99,7 +99,7 @@ Enables Deep Code to read and write files within a specified directory: } ``` -### Custom Python MCP +### 自定义 Python MCP ```json { @@ -115,9 +115,9 @@ Enables Deep Code to read and write files within a specified directory: } ``` -## Full Configuration Example +## 完整配置示例 -Below is a complete `~/.deepcode/settings.json` with both GitHub and Playwright MCP servers configured: +以下是一个配置了 GitHub 和 Playwright 两个 MCP 服务器的完整 `~/.deepcode/settings.json`: ```json { @@ -144,62 +144,57 @@ Below is a complete `~/.deepcode/settings.json` with both GitHub and Playwright } ``` -## Using MCP +## 使用 MCP -After configuration, start `deepcode` and use the `/mcp` command to manage MCP connections: +配置完成后,启动 `deepcode`,在聊天中输入 `/mcp` 即可查看所有已配置的 MCP 服务器状态以及每个服务器提供的工具列表。 -- `/mcp` — View the status of configured MCP servers -- `/mcp add` — Add a new MCP server -- `/mcp remove` — Remove an MCP server -- `/mcp list` — List all connected MCP servers and their tools - -Simply use the MCP tool name in your conversation to invoke it, for example: +在对话中直接使用 MCP 工具名称即可调用,例如: ``` -Help me search for issues in the deepcode-cli repository on GitHub +帮我搜索 GitHub 上 deepcode-cli 仓库的 issues ``` -The AI will automatically invoke the `mcp__github__search_issues` tool to complete the action. +AI 会自动调用 `mcp__github__search_issues` 工具完成操作。 -## Tool Naming Convention +## 工具命名规则 -An MCP tool name consists of three parts: `mcp____` +MCP 工具名称由三部分组成:`mcp__<服务名>__<工具名>` -| Service | Tool Name | Full Invocation Name | -| ---------- | ----------------------- | ------------------------------------------- | -| github | search_code | `mcp__github__search_code` | -| github | create_pull_request | `mcp__github__create_pull_request` | -| playwright | browser_navigate | `mcp__playwright__browser_navigate` | -| playwright | browser_take_screenshot | `mcp__playwright__browser_take_screenshot` | +| 服务名 | 工具名 | 完整调用名 | +| ---------- | ----------------------- | ------------------------------------------ | +| github | search_code | `mcp__github__search_code` | +| github | create_pull_request | `mcp__github__create_pull_request` | +| playwright | browser_navigate | `mcp__playwright__browser_navigate` | +| playwright | browser_take_screenshot | `mcp__playwright__browser_take_screenshot` | -You can view the list of tools provided by each server using `/mcp list`. +你可以通过 `/mcp` 查看每个服务器提供的具体工具列表。 -## Troubleshooting +## 故障排查 -### Startup Failure +### 启动失败 -If an MCP server fails to start, check: +如果 MCP 服务器无法启动,检查: -1. Whether `command` is installed (e.g., `npx` requires Node.js) -2. Whether environment variables in `env` are correct (e.g., `GITHUB_PERSONAL_ACCESS_TOKEN`) -3. Whether the terminal running `deepcode` has network access +1. `command` 是否已安装(如 `npx` 需要 Node.js) +2. `env` 中的环境变量是否正确(如 `GITHUB_PERSONAL_ACCESS_TOKEN`) +3. 运行 `deepcode` 的终端是否有网络访问权限 -### Tools Not Showing Up +### 工具不显示 -1. Verify that the `mcpServers` field in `settings.json` is correctly formatted -2. After starting deepcode, use `/mcp` to check server status -3. If the server status shows an error, debug based on the error message +1. 确认 `settings.json` 中的 `mcpServers` 字段格式正确 +2. 启动 deepcode 后使用 `/mcp` 查看服务器状态 +3. 如果服务器状态显示错误,根据错误信息排查 -### Windows Users +### Windows 用户 -On Windows, Deep Code CLI automatically adds shell support for `.cmd` commands. If your MCP command is a batch script, ensure the filename ends with `.cmd`. +在 Windows 上,Deep Code CLI 会自动为 `.cmd` 命令添加 shell 支持。如果你的 MCP 命令是批处理脚本,确保文件名以 `.cmd` 结尾。 -## Writing Your Own MCP Server +## 编写你自己的 MCP 服务器 -MCP servers follow the [Model Context Protocol](https://modelcontextprotocol.io/) specification and communicate using JSON‑RPC 2.0. You can write an MCP server in any language as long as it implements the following methods: +MCP 服务器遵循 [Model Context Protocol](https://modelcontextprotocol.io/) 规范,使用 JSON-RPC 2.0 通信。你可以用任何语言编写 MCP 服务器,只要实现以下协议即可: -1. `initialize` — Handshake and protocol negotiation -2. `tools/list` — Return the list of available tools -3. `tools/call` — Execute a tool call +1. `initialize` — 握手和协议协商 +2. `tools/list` — 返回可用工具列表 +3. `tools/call` — 执行工具调用 -For more information, see the [official MCP documentation](https://modelcontextprotocol.io/). \ No newline at end of file +更多参考:[MCP 官方文档](https://modelcontextprotocol.io/) diff --git a/docs/mcp_en.md b/docs/mcp_en.md new file mode 100644 index 0000000..03c4b30 --- /dev/null +++ b/docs/mcp_en.md @@ -0,0 +1,200 @@ +# Deep Code CLI MCP Configuration Guide + +Deep Code CLI supports MCP (Model Context Protocol), enabling AI assistants to connect with external tools and services such as GitHub, browsers, databases, and more. + +## Overview + +Once MCP is configured, Deep Code can: + +- Operate on GitHub repositories (view issues, create PRs, search code, etc.) +- Control browsers (screenshots, clicks, form filling, etc.) +- Access the file system +- Connect to databases and APIs +- ...and any external service compatible with the MCP protocol + +MCP tools are named in Deep Code using the format `mcp____`, for example `mcp__github__search_code`. + +## Configuring MCP Servers + +Edit `~/.deepcode/settings.json` and add the `mcpServers` field: + +```json +{ + "env": { + "MODEL": "deepseek-v4-pro", + "BASE_URL": "https://api.deepseek.com", + "API_KEY": "sk-..." + }, + "thinkingEnabled": true, + "reasoningEffort": "max", + "mcpServers": { + "": { + "command": "", + "args": ["", ""], + "env": { + "": "" + } + } + } +} +``` + +### Configuration Fields + +| Field | Type | Required | Description | +| --------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `command` | string | Yes | Path or command of the MCP server executable (e.g., `npx`, `node`, `python`). When the command is `npx`, Deep Code automatically prepends `-y` to the arguments. | +| `args` | string[] | No | List of arguments to pass to the command | +| `env` | object | No | Environment variables (e.g., API keys) to pass to the MCP server process | + +## Common MCP Examples + +### GitHub MCP + +Allows Deep Code to directly operate on GitHub repositories (search code, manage issues/PRs, read/write files, etc.): + +```json +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx" + } + } + } +} +``` + +> Generate a GitHub Personal Access Token at [GitHub Settings > Developer settings > Personal access tokens](https://github.com/settings/tokens). + +### Browser Control (Playwright) + +Lets Deep Code control a browser for screenshots, page interactions, etc.: + +```json +{ + "mcpServers": { + "playwright": { + "command": "npx", + "args": ["@playwright/mcp@latest"] + } + } +} +``` + +### File System + +Enables Deep Code to read and write files within a specified directory: + +```json +{ + "mcpServers": { + "filesystem": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"] + } + } +} +``` + +### Custom Python MCP + +```json +{ + "mcpServers": { + "my-tool": { + "command": "python", + "args": ["-m", "my_mcp_server"], + "env": { + "API_KEY": "xxx" + } + } + } +} +``` + +## Full Configuration Example + +Below is a complete `~/.deepcode/settings.json` with both GitHub and Playwright MCP servers configured: + +```json +{ + "env": { + "MODEL": "deepseek-v4-pro", + "BASE_URL": "https://api.deepseek.com", + "API_KEY": "sk-xxxxxxxxxxxx" + }, + "thinkingEnabled": true, + "reasoningEffort": "max", + "mcpServers": { + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx" + } + }, + "playwright": { + "command": "npx", + "args": ["@playwright/mcp@latest"] + } + } +} +``` + +## Using MCP + +After configuration, start `deepcode` and type `/mcp` in the chat to view the status of all configured MCP servers and the list of tools each server provides. + +Simply use the MCP tool name in your conversation to invoke it, for example: + +``` +Help me search for issues in the deepcode-cli repository on GitHub +``` + +The AI will automatically invoke the `mcp__github__search_issues` tool to complete the action. + +## Tool Naming Convention + +An MCP tool name consists of three parts: `mcp____` + +| Service | Tool Name | Full Invocation Name | +| ---------- | ----------------------- | ------------------------------------------- | +| github | search_code | `mcp__github__search_code` | +| github | create_pull_request | `mcp__github__create_pull_request` | +| playwright | browser_navigate | `mcp__playwright__browser_navigate` | +| playwright | browser_take_screenshot | `mcp__playwright__browser_take_screenshot` | + +You can view the list of tools provided by each server using `/mcp`. + +## Troubleshooting + +### Startup Failure + +If an MCP server fails to start, check: + +1. Whether `command` is installed (e.g., `npx` requires Node.js) +2. Whether environment variables in `env` are correct (e.g., `GITHUB_PERSONAL_ACCESS_TOKEN`) +3. Whether the terminal running `deepcode` has network access + +### Tools Not Showing Up + +1. Verify that the `mcpServers` field in `settings.json` is correctly formatted +2. After starting deepcode, use `/mcp` to check server status +3. If the server status shows an error, debug based on the error message + +### Windows Users + +On Windows, Deep Code CLI automatically adds shell support for `.cmd` commands. If your MCP command is a batch script, ensure the filename ends with `.cmd`. + +## Writing Your Own MCP Server + +MCP servers follow the [Model Context Protocol](https://modelcontextprotocol.io/) specification and communicate using JSON‑RPC 2.0. You can write an MCP server in any language as long as it implements the following methods: + +1. `initialize` — Handshake and protocol negotiation +2. `tools/list` — Return the list of available tools +3. `tools/call` — Execute a tool call + +For more information, see the [official MCP documentation](https://modelcontextprotocol.io/). \ No newline at end of file From dbe859e588300c7b4309d78cc60508f0abc5e18c Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Fri, 15 May 2026 22:50:00 +0800 Subject: [PATCH 017/129] refactor: update usage types to ModelUsage in session --- src/session.ts | 29 ++++++++++++++++++++--------- src/tests/exitSummary.test.ts | 4 ++-- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/session.ts b/src/session.ts index 894ff80..9295ff2 100644 --- a/src/session.ts +++ b/src/session.ts @@ -65,11 +65,11 @@ function addUsageValue(current: unknown, next: unknown): unknown { return next; } -function accumulateUsage(current: unknown | null, next: unknown | null | undefined): unknown | null { +function accumulateUsage(current: ModelUsage | null, next: unknown | null | undefined): ModelUsage | null { if (next == null) { return current ?? null; } - return addUsageValue(current, next); + return addUsageValue(current, next) as ModelUsage; } function getExtensionRoot(): string { @@ -81,7 +81,7 @@ function getExtensionRoot(): string { return path.resolve(path.dirname(currentFilePath), ".."); } -function getTotalTokens(usage: unknown | null | undefined): number { +function getTotalTokens(usage: ModelUsage | null | undefined): number { if (!isUsageRecord(usage)) { return 0; } @@ -91,6 +91,17 @@ function getTotalTokens(usage: unknown | null | undefined): number { export type SessionStatus = "failed" | "pending" | "processing" | "waiting_for_user" | "completed" | "interrupted"; +export type ModelUsage = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + completion_tokens_details?: Record; + prompt_tokens_details?: Record; + prompt_cache_hit_tokens?: number; + prompt_cache_miss_tokens?: number; + total_reqs?: number; +}; + export type SessionEntry = { id: string; summary: string | null; @@ -100,7 +111,7 @@ export type SessionEntry = { toolCalls: unknown[] | null; status: SessionStatus; failReason: string | null; - usage: unknown | null; + usage: ModelUsage | null; activeTokens: number; createTime: string; updateTime: string; @@ -286,7 +297,7 @@ export class SessionManager { debug?: ChatCompletionDebugOptions ): Promise<{ choices?: Array<{ message?: Record }>; - usage?: unknown; + usage?: ModelUsage | null; }> { const requestId = crypto.randomUUID(); const startedAt = new Date().toISOString(); @@ -355,13 +366,13 @@ export class SessionManager { request: streamRequest, response, }); - return response as { choices?: Array<{ message?: Record }>; usage?: unknown }; + return response as { choices?: Array<{ message?: Record }>; usage?: ModelUsage | null }; } let content = ""; let reasoningContent = ""; let refusal: string | null = null; - let usage: unknown = null; + let usage: ModelUsage | null = null; const responseChunks: unknown[] = []; const toolCallsByIndex = new Map< number, @@ -386,7 +397,7 @@ export class SessionManager { responseChunks.push(chunk); } if ("usage" in chunk && chunk.usage != null) { - usage = chunk.usage; + usage = chunk.usage as ModelUsage; } const choices = Array.isArray(chunk.choices) ? chunk.choices : []; @@ -2096,7 +2107,7 @@ ${skillMd} toolCalls: Array.isArray(value.toolCalls) ? value.toolCalls : null, status: this.normalizeSessionStatus(value.status), failReason: typeof value.failReason === "string" ? value.failReason : null, - usage: value.usage ?? null, + usage: (value.usage as ModelUsage) ?? null, activeTokens: typeof value.activeTokens === "number" ? value.activeTokens : 0, createTime: typeof value.createTime === "string" ? value.createTime : new Date().toISOString(), updateTime: typeof value.updateTime === "string" ? value.updateTime : new Date().toISOString(), diff --git a/src/tests/exitSummary.test.ts b/src/tests/exitSummary.test.ts index 9cff34b..0257bf2 100644 --- a/src/tests/exitSummary.test.ts +++ b/src/tests/exitSummary.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { buildExitSummaryText } from "../ui"; -import type { SessionEntry, SessionMessage } from "../session"; +import type { SessionEntry, SessionMessage, ModelUsage } from "../session"; const stripAnsi = (text: string): string => text.replace(/\u001b\[[0-9;]*m/g, ""); @@ -33,7 +33,7 @@ test("buildExitSummaryText only shows Goodbye and model usage with cached tokens assert.doesNotMatch(summary, /Reasoning Tokens/); }); -function buildSession(usage: unknown): SessionEntry { +function buildSession(usage: ModelUsage | null): SessionEntry { return { id: "session-1", summary: null, From 3ef5b8e7e293d80095edcd1e8f91d5b2b1b7ad4f Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Fri, 15 May 2026 23:18:27 +0800 Subject: [PATCH 018/129] feat: add usage tracking per model and update exit summary display --- src/session.ts | 45 +++++++++++++++++ src/tests/exitSummary.test.ts | 93 +++++++++++++++++++++++++---------- src/tests/session.test.ts | 89 +++++++++++++++++++++++++++++++++ src/ui/App.tsx | 8 +-- src/ui/exitSummary.ts | 60 +++++++++++++--------- 5 files changed, 241 insertions(+), 54 deletions(-) diff --git a/src/session.ts b/src/session.ts index 9295ff2..97bc3ab 100644 --- a/src/session.ts +++ b/src/session.ts @@ -72,6 +72,29 @@ function accumulateUsage(current: ModelUsage | null, next: unknown | null | unde return addUsageValue(current, next) as ModelUsage; } +function usageWithRequestCount(usage: ModelUsage): ModelUsage { + const totalReqs = typeof usage.total_reqs === "number" ? usage.total_reqs + 1 : 1; + return { + ...usage, + total_reqs: totalReqs, + }; +} + +function accumulateUsagePerModel( + current: Record | null | undefined, + model: string, + next: ModelUsage | null | undefined +): Record | null { + if (next == null) { + return current ?? null; + } + + const usagePerModel = { ...(current ?? {}) }; + const modelName = model.trim() || "unknown"; + usagePerModel[modelName] = accumulateUsage(usagePerModel[modelName] ?? null, usageWithRequestCount(next))!; + return usagePerModel; +} + function getExtensionRoot(): string { if (typeof __dirname !== "undefined") { return path.resolve(__dirname, ".."); @@ -112,6 +135,7 @@ export type SessionEntry = { status: SessionStatus; failReason: string | null; usage: ModelUsage | null; + usagePerModel: Record | null; activeTokens: number; createTime: string; updateTime: string; @@ -847,6 +871,7 @@ The candidate skills are as follows:\n\n`; status: "pending", failReason: null, usage: null, + usagePerModel: null, activeTokens: 0, createTime: now, updateTime: now, @@ -1087,6 +1112,7 @@ ${skillMd} assistantRefusal: refusal, toolCalls, usage: accumulateUsage(entry.usage, responseUsage), + usagePerModel: accumulateUsagePerModel(entry.usagePerModel, model, responseUsage), activeTokens: getTotalTokens(responseUsage), status: refusal ? "failed" : waitingForUser ? "waiting_for_user" : toolCalls ? "processing" : "completed", failReason: refusal ? refusal : entry.failReason, @@ -1196,6 +1222,7 @@ ${skillMd} this.updateSessionEntry(sessionId, (entry) => ({ ...entry, usage: accumulateUsage(entry.usage, responseUsage), + usagePerModel: accumulateUsagePerModel(entry.usagePerModel, model, responseUsage), activeTokens: getTotalTokens(responseUsage), updateTime: now, })); @@ -2108,6 +2135,7 @@ ${skillMd} status: this.normalizeSessionStatus(value.status), failReason: typeof value.failReason === "string" ? value.failReason : null, usage: (value.usage as ModelUsage) ?? null, + usagePerModel: this.normalizeUsagePerModel(value), activeTokens: typeof value.activeTokens === "number" ? value.activeTokens : 0, createTime: typeof value.createTime === "string" ? value.createTime : new Date().toISOString(), updateTime: typeof value.updateTime === "string" ? value.updateTime : new Date().toISOString(), @@ -2129,6 +2157,23 @@ ${skillMd} return "pending"; } + private normalizeUsagePerModel(entry: Record): Record | null { + if (!Object.prototype.hasOwnProperty.call(entry, "usagePerModel")) { + return null; + } + if (!isUsageRecord(entry.usagePerModel)) { + return null; + } + const usagePerModel: Record = {}; + for (const [model, usage] of Object.entries(entry.usagePerModel)) { + if (!model || !isUsageRecord(usage)) { + continue; + } + usagePerModel[model] = usage as ModelUsage; + } + return usagePerModel; + } + private deserializeProcesses(value: unknown): Map | null { if (!value || typeof value !== "object") { return null; diff --git a/src/tests/exitSummary.test.ts b/src/tests/exitSummary.test.ts index 0257bf2..5ea4b57 100644 --- a/src/tests/exitSummary.test.ts +++ b/src/tests/exitSummary.test.ts @@ -1,22 +1,23 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { buildExitSummaryText } from "../ui"; -import type { SessionEntry, SessionMessage, ModelUsage } from "../session"; +import type { ModelUsage, SessionEntry } from "../session"; const stripAnsi = (text: string): string => text.replace(/\u001b\[[0-9;]*m/g, ""); test("buildExitSummaryText only shows Goodbye and model usage with cached tokens", () => { const summary = stripAnsi( buildExitSummaryText({ - session: buildSession({ - prompt_tokens: 11_966, - completion_tokens: 236, - total_tokens: 12_202, - prompt_tokens_details: { cached_tokens: 11_776 }, - completion_tokens_details: { reasoning_tokens: 144 }, + session: buildSession(null, { + "mimo-v2.5-pro": { + prompt_tokens: 11_966, + completion_tokens: 236, + total_tokens: 12_202, + prompt_tokens_details: { cached_tokens: 11_776 }, + completion_tokens_details: { reasoning_tokens: 144 }, + total_reqs: 2, + }, }), - messages: [buildAssistantMessage("assistant-1"), buildAssistantMessage("assistant-2")], - model: "mimo-v2.5-pro", }) ); @@ -33,7 +34,63 @@ test("buildExitSummaryText only shows Goodbye and model usage with cached tokens assert.doesNotMatch(summary, /Reasoning Tokens/); }); -function buildSession(usage: ModelUsage | null): SessionEntry { +test("buildExitSummaryText shows all usagePerModel rows sorted by request count", () => { + const summary = stripAnsi( + buildExitSummaryText({ + session: buildSession( + { + prompt_tokens: 999, + completion_tokens: 999, + total_tokens: 1_998, + }, + { + "deepseek-v4-pro": { + prompt_tokens: 100, + completion_tokens: 10, + total_tokens: 110, + total_reqs: 1, + }, + "deepseek-v4-flash": { + prompt_tokens: 300, + completion_tokens: 30, + total_tokens: 330, + prompt_cache_hit_tokens: 111, + total_reqs: 3, + }, + } + ), + }) + ); + + const flashIndex = summary.indexOf("deepseek-v4-flash"); + const proIndex = summary.indexOf("deepseek-v4-pro"); + + assert.notEqual(flashIndex, -1); + assert.notEqual(proIndex, -1); + assert.ok(flashIndex < proIndex); + assert.match(summary, /deepseek-v4-flash\s+3\s+300\s+30\s+111/); + assert.match(summary, /deepseek-v4-pro\s+1\s+100\s+10\s+0/); + assert.doesNotMatch(summary, /999/); +}); + +test("buildExitSummaryText does not derive usage rows from legacy aggregate usage", () => { + const summary = stripAnsi( + buildExitSummaryText({ + session: buildSession({ + prompt_tokens: 11_966, + completion_tokens: 236, + total_tokens: 12_202, + total_reqs: 2, + }), + }) + ); + + assert.match(summary, /Goodbye!/); + assert.doesNotMatch(summary, /Model Usage/); + assert.doesNotMatch(summary, /11,966/); +}); + +function buildSession(usage: ModelUsage | null, usagePerModel: Record | null = null): SessionEntry { return { id: "session-1", summary: null, @@ -44,24 +101,10 @@ function buildSession(usage: ModelUsage | null): SessionEntry { status: "completed", failReason: null, usage, + usagePerModel, activeTokens: 0, createTime: "2026-01-01T00:00:00.000Z", updateTime: "2026-01-01T00:00:01.000Z", processes: null, }; } - -function buildAssistantMessage(id: string): SessionMessage { - return { - id, - sessionId: "session-1", - role: "assistant", - content: "", - contentParams: null, - messageParams: null, - compacted: false, - visible: true, - createTime: "2026-01-01T00:00:00.000Z", - updateTime: "2026-01-01T00:00:00.000Z", - }; -} diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 2ac6c29..1e5e5ce 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -275,6 +275,20 @@ test("SessionManager normalizes legacy sessions without activeTokens to zero", ( const manager = createSessionManager(workspace, "machine-id-legacy"); assert.equal(manager.getSession("legacy-session")?.activeTokens, 0); + assert.equal(manager.getSession("legacy-session")?.usagePerModel, null); +}); + +test("SessionManager keeps usagePerModel null until response usage is available", async () => { + const workspace = createTempDir("deepcode-null-usage-per-model-workspace-"); + const home = createTempDir("deepcode-null-usage-per-model-home-"); + process.env.HOME = home; + + const manager = createMockedClientSessionManager(workspace, [{ choices: [{ message: { content: "no usage" } }] }]); + + const sessionId = await manager.createSession({ text: "" }); + + assert.equal(manager.getSession(sessionId)?.usage, null); + assert.equal(manager.getSession(sessionId)?.usagePerModel, null); }); test("SessionManager marks skills loaded from existing session messages", async () => { @@ -1122,6 +1136,7 @@ test("SessionManager accumulates response usage while active tokens track the la const session = manager.getSession(sessionId); const usage = session?.usage as Record; + const usagePerModel = session?.usagePerModel?.["test-model"] as Record; assert.equal(session?.activeTokens, 27); assert.equal(usage.prompt_tokens, 30); assert.equal(usage.completion_tokens, 12); @@ -1130,6 +1145,75 @@ test("SessionManager accumulates response usage while active tokens track the la assert.equal(usage.completion_tokens_details.reasoning_tokens, 7); assert.equal(usage.prompt_cache_hit_tokens, 18); assert.equal(usage.prompt_cache_miss_tokens, 12); + assert.equal(usagePerModel.prompt_tokens, 30); + assert.equal(usagePerModel.completion_tokens, 12); + assert.equal(usagePerModel.total_tokens, 42); + assert.equal(usagePerModel.prompt_tokens_details.cached_tokens, 18); + assert.equal(usagePerModel.completion_tokens_details.reasoning_tokens, 7); + assert.equal(usagePerModel.prompt_cache_hit_tokens, 18); + assert.equal(usagePerModel.prompt_cache_miss_tokens, 12); + assert.equal(usagePerModel.total_reqs, 2); +}); + +test("SessionManager stores usage per model across model changes", async () => { + const workspace = createTempDir("deepcode-usage-per-model-workspace-"); + const home = createTempDir("deepcode-usage-per-model-home-"); + process.env.HOME = home; + + let currentModel = "deepseek-v4-pro"; + const responses = [ + createChatResponse("pro response", { + prompt_tokens: 10, + completion_tokens: 5, + total_tokens: 15, + }), + createChatResponse("flash response", { + prompt_tokens: 20, + completion_tokens: 7, + total_tokens: 27, + prompt_cache_hit_tokens: 6, + }), + ]; + const client = { + chat: { + completions: { + create: async () => { + const response = responses.shift(); + assert.ok(response, "expected a queued chat response"); + return response; + }, + }, + }, + }; + const manager = new SessionManager({ + projectRoot: workspace, + createOpenAIClient: () => ({ + client: client as any, + model: currentModel, + baseURL: "https://api.deepseek.com", + thinkingEnabled: false, + }), + getResolvedSettings: () => ({ model: currentModel }), + renderMarkdown: (text) => text, + onAssistantMessage: () => {}, + }); + + const sessionId = await manager.createSession({ text: "" }); + currentModel = "deepseek-v4-flash"; + await manager.replySession(sessionId, { text: "" }); + + const session = manager.getSession(sessionId); + assert.deepEqual(Object.keys(session?.usagePerModel ?? {}).sort(), ["deepseek-v4-flash", "deepseek-v4-pro"]); + assert.equal(session?.usagePerModel?.["deepseek-v4-pro"]?.prompt_tokens, 10); + assert.equal(session?.usagePerModel?.["deepseek-v4-pro"]?.completion_tokens, 5); + assert.equal(session?.usagePerModel?.["deepseek-v4-pro"]?.total_reqs, 1); + assert.equal(session?.usagePerModel?.["deepseek-v4-flash"]?.prompt_tokens, 20); + assert.equal(session?.usagePerModel?.["deepseek-v4-flash"]?.completion_tokens, 7); + assert.equal(session?.usagePerModel?.["deepseek-v4-flash"]?.prompt_cache_hit_tokens, 6); + assert.equal(session?.usagePerModel?.["deepseek-v4-flash"]?.total_reqs, 1); + assert.equal(session?.usage?.prompt_tokens, 30); + assert.equal(session?.usage?.completion_tokens, 12); + assert.equal(session?.usage?.total_tokens, 42); }); test("SessionManager resets active tokens to latest post-compaction response usage", async () => { @@ -1163,10 +1247,15 @@ test("SessionManager resets active tokens to latest post-compaction response usa const session = manager.getSession(sessionId); const usage = session?.usage as Record; + const usagePerModel = session?.usagePerModel?.["test-model"] as Record; assert.equal(session?.activeTokens, 7); assert.equal(usage.prompt_tokens, 140_095); assert.equal(usage.completion_tokens, 35); assert.equal(usage.total_tokens, 140_130); + assert.equal(usagePerModel.prompt_tokens, 140_095); + assert.equal(usagePerModel.completion_tokens, 35); + assert.equal(usagePerModel.total_tokens, 140_130); + assert.equal(usagePerModel.total_reqs, 3); }); test("SessionManager streams chat completions and counts reasoning progress", async () => { diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 3f32f56..25671ce 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -148,11 +148,7 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R setTimeout(() => { const activeSessionId = sessionManager.getActiveSessionId(); const session = activeSessionId ? sessionManager.getSession(activeSessionId) : null; - const allMessages = activeSessionId - ? sessionManager.listSessionMessages(activeSessionId) - : messagesRef.current; - const resolved = resolveCurrentSettings(projectRoot); - const summary = buildExitSummaryText({ session, messages: allMessages, model: resolved.model }); + const summary = buildExitSummaryText({ session }); process.stdout.write("\n"); process.stdout.write(chalk.green("> /exit ")); process.stdout.write("\n\n"); @@ -256,7 +252,7 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R setRunningProcesses(null); } }, - [exit, onRestart, projectRoot, sessionManager, refreshSkills, refreshSessionsList] + [exit, onRestart, sessionManager, refreshSkills, refreshSessionsList] ); const handleInterrupt = useCallback(() => { diff --git a/src/ui/exitSummary.ts b/src/ui/exitSummary.ts index 910cceb..c55d9ce 100644 --- a/src/ui/exitSummary.ts +++ b/src/ui/exitSummary.ts @@ -1,11 +1,9 @@ import chalk from "chalk"; import gradientString from "gradient-string"; -import type { SessionEntry, SessionMessage } from "../session"; +import type { ModelUsage, SessionEntry } from "../session"; type ExitSummaryInput = { session: SessionEntry | null; - messages: SessionMessage[]; - model?: string; }; const ANSI_RE = /\u001b\[[0-9;]*[a-zA-Z]/g; @@ -32,13 +30,15 @@ type UsageFields = { promptTokens: number; completionTokens: number; cachedTokens: number; + totalReqs: number; }; -function extractUsageFields(usage: unknown | null): UsageFields { +function extractUsageFields(usage: ModelUsage | null): UsageFields { const empty: UsageFields = { promptTokens: 0, completionTokens: 0, cachedTokens: 0, + totalReqs: 0, }; if (!usage || typeof usage !== "object" || Array.isArray(usage)) { return empty; @@ -61,14 +61,13 @@ function extractUsageFields(usage: unknown | null): UsageFields { cachedTokens = record.prompt_cache_hit_tokens; } - return { promptTokens, completionTokens, cachedTokens }; + const totalReqs = typeof record.total_reqs === "number" ? record.total_reqs : 0; + + return { promptTokens, completionTokens, cachedTokens, totalReqs }; } export function buildExitSummaryText(input: ExitSummaryInput): string { - const { session, messages, model } = input; - - // Count assistant messages as the request count shown in the usage table. - const assistantCount = messages.filter((m) => m.role === "assistant").length; + const { session } = input; const innerWidth = 98; const contentWidth = innerWidth - 4; // "│ " prefix + " │" suffix → 4 chars padding @@ -81,9 +80,22 @@ export function buildExitSummaryText(input: ExitSummaryInput): string { const rows: string[] = ["", `${header}`, ""]; - const usage = extractUsageFields(session?.usage ?? null); - const modelName = model ?? "unknown"; - const hasUsage = usage.promptTokens > 0 || usage.completionTokens > 0; + const usageRows = Object.entries(session?.usagePerModel ?? {}) + .map(([modelName, usage]) => ({ + modelName, + usage: extractUsageFields(usage), + })) + .filter( + (row) => + row.usage.totalReqs > 0 || + row.usage.promptTokens > 0 || + row.usage.completionTokens > 0 || + row.usage.cachedTokens > 0 + ) + .sort( + (left, right) => right.usage.totalReqs - left.usage.totalReqs || left.modelName.localeCompare(right.modelName) + ); + const hasUsage = usageRows.length > 0; if (hasUsage) { const colModel = 34; @@ -103,17 +115,19 @@ export function buildExitSummaryText(input: ExitSummaryInput): string { rows.push(chalk.bold(headerRow)); rows.push(divider); - const reqsStr = String(assistantCount).padStart(colReqs); - const inputStr = formatNumber(usage.promptTokens).padStart(colInput); - const outputStr = formatNumber(usage.completionTokens).padStart(colOutput); - const cachedStr = formatNumber(usage.cachedTokens).padStart(colCached); - const dataRow = - padRight(modelName, colModel) + - padRight(reqsStr, colReqs) + - padRight(chalk.yellow(inputStr), colInput) + - padRight(chalk.yellow(outputStr), colOutput) + - padRight(chalk.yellow(cachedStr), colCached); - rows.push(dataRow); + for (const { modelName, usage } of usageRows) { + const reqsStr = formatNumber(usage.totalReqs).padStart(colReqs); + const inputStr = formatNumber(usage.promptTokens).padStart(colInput); + const outputStr = formatNumber(usage.completionTokens).padStart(colOutput); + const cachedStr = formatNumber(usage.cachedTokens).padStart(colCached); + const dataRow = + padRight(modelName, colModel) + + padRight(reqsStr, colReqs) + + padRight(chalk.yellow(inputStr), colInput) + + padRight(chalk.yellow(outputStr), colOutput) + + padRight(chalk.yellow(cachedStr), colCached); + rows.push(dataRow); + } rows.push(""); } From 0aa3f0dfbc2549e0c507a5e2e3f71a94aab145f8 Mon Sep 17 00:00:00 2001 From: Lellansin Date: Sat, 16 May 2026 09:52:39 +0800 Subject: [PATCH 019/129] feat: add GitHub CI workflow with multi-version Node.js and cross-platform matrix --- .github/workflows/ci.yml | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..11cf1a3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,47 @@ +name: CI + +on: + pull_request: + branches: [main] + push: + branches: [main] + +jobs: + build-and-test: + name: Node ${{ matrix.node-version }} / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - windows-latest + - macos-latest + node-version: + - "18" + - "20" + - "22" + - "24" + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: npm + + - name: Install dependencies + run: npm ci + + - name: TypeCheck + Lint + Format Check + run: npm run check + + - name: Bundle + run: npm run bundle + + - name: Test + run: npm test From 9fc53984975c15b726d56fe4e45b40cdb3170aac Mon Sep 17 00:00:00 2001 From: Lellansin Date: Sat, 16 May 2026 09:55:37 +0800 Subject: [PATCH 020/129] fix(ci): trigger CI on all push events so PRs can verify before merge --- .github/workflows/ci.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 11cf1a3..0b214bf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,8 @@ name: CI on: - pull_request: - branches: [main] push: + pull_request: branches: [main] jobs: From 21a3add40b6ca57aed401aa0348d5bfd4815db09 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Sat, 16 May 2026 11:12:55 +0800 Subject: [PATCH 021/129] feat: align the project to Node >=22, because the direct dependency ink@7.0.1 already declares node >=22. --- .github/workflows/ci.yml | 2 -- package-lock.json | 2 +- package.json | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b214bf..de8600c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,6 @@ jobs: - windows-latest - macos-latest node-version: - - "18" - - "20" - "22" - "24" diff --git a/package-lock.json b/package-lock.json index dd029a3..17fa96f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -40,7 +40,7 @@ "typescript-eslint": "^8.59.2" }, "engines": { - "node": ">=18.17.0" + "node": ">=22" } }, "node_modules/@alcalzone/ansi-tokenize": { diff --git a/package.json b/package.json index 0564936..5405b26 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "LICENSE" ], "engines": { - "node": ">=18.17.0" + "node": ">=22" }, "scripts": { "typecheck": "tsc -p ./ --noEmit", From f1e696834d9f3a1eda2c88c9f6a093d13d6affbb Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 11:32:30 +0800 Subject: [PATCH 022/129] fix: add .gitattributes to enforce LF line endings on Windows --- .gitattributes | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..18f5c60 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# Normalize line endings to LF across all platforms +* text=auto eol=lf + +# Binary files should not be normalized +*.png binary +*.jpg binary +*.gif binary +*.ico binary +*.woff binary +*.woff2 binary +*.eot binary +*.ttf binary From f62b1ce2286ac86a7a604e49ac22a5b25b4b5a40 Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 11:40:13 +0800 Subject: [PATCH 023/129] fix: resolve Windows CI failures (CRLF, MCP spawn, test skips) --- src/mcp/mcp-client.ts | 8 +-- src/tests/clipboard.test.ts | 72 ++++++++++++++------------ src/tests/settings-and-notify.test.ts | 74 ++++++++++++++------------- src/tests/web-search-handler.test.ts | 68 ++++++++++++------------ src/tests/welcomeScreen.test.ts | 15 ++++-- 5 files changed, 129 insertions(+), 108 deletions(-) diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts index f89e11d..9636732 100644 --- a/src/mcp/mcp-client.ts +++ b/src/mcp/mcp-client.ts @@ -128,10 +128,10 @@ export class McpClient { const isWindows = os.platform() === "win32"; if (isWindows) { - // On Windows, .cmd files require shell: true to be spawned. - // Build a single command string so cmd.exe handles quoting correctly. - const cmd = [this.command + ".cmd", ...args].join(" "); - this.process = spawn(cmd, [], { + // On Windows, shell: true lets cmd.exe resolve the command via + // PATHEXT (npx → npx.cmd, etc.) without blindly appending .cmd, + // which would break absolute paths like process.execPath. + this.process = spawn(this.command, args, { stdio: ["pipe", "pipe", "pipe"], env: childEnv, shell: true, diff --git a/src/tests/clipboard.test.ts b/src/tests/clipboard.test.ts index 022b2f8..dbe9ff9 100644 --- a/src/tests/clipboard.test.ts +++ b/src/tests/clipboard.test.ts @@ -36,40 +36,44 @@ test("readClipboardImage returns null when no clipboard helpers are installed", assert.equal(result, null); }); -test("readClipboardImage uses osascript fallback on macOS when pngpaste is missing", async () => { - const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-clipboard-test-bin-")); - try { - fs.writeFileSync(path.join(binDir, "pngpaste"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); - fs.writeFileSync( - path.join(binDir, "osascript"), - [ - "#!/bin/sh", - 'for arg in "$@"; do', - ' case "$arg" in', - " *'open for access POSIX file " + '"' + "'*)", - ' path_part=${arg#*POSIX file \\"}', - ' out_path=${path_part%%\\"*}', - ' printf fakepng > "$out_path"', - " exit 0", - " ;;", - " esac", - "done", - "exit 1", - "", - ].join("\n"), - { mode: 0o755 } - ); +test( + "readClipboardImage uses osascript fallback on macOS when pngpaste is missing", + { skip: process.platform === "win32" }, + async () => { + const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-clipboard-test-bin-")); + try { + fs.writeFileSync(path.join(binDir, "pngpaste"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + fs.writeFileSync( + path.join(binDir, "osascript"), + [ + "#!/bin/sh", + 'for arg in "$@"; do', + ' case "$arg" in', + " *'open for access POSIX file " + '"' + "'*)", + ' path_part=${arg#*POSIX file \\"}', + ' out_path=${path_part%%\\"*}', + ' printf fakepng > "$out_path"', + " exit 0", + " ;;", + " esac", + "done", + "exit 1", + "", + ].join("\n"), + { mode: 0o755 } + ); - const moduleUrl = new URL(`../ui/clipboard.ts?t=${Date.now()}`, import.meta.url).href; - const { readClipboardImage } = (await import(moduleUrl)) as ClipboardModule; + const moduleUrl = new URL(`../ui/clipboard.ts?t=${Date.now()}`, import.meta.url).href; + const { readClipboardImage } = (await import(moduleUrl)) as ClipboardModule; - process.env.PATH = binDir; - const result = withPlatform("darwin", () => readClipboardImage()); - assert.equal(result?.mimeType, "image/png"); - assert.equal(result?.dataUrl, `data:image/png;base64,${Buffer.from("fakepng").toString("base64")}`); - } finally { - process.env.PATH = ORIGINAL_PATH; - Object.defineProperty(process, "platform", { value: ORIGINAL_PLATFORM }); - fs.rmSync(binDir, { recursive: true, force: true }); + process.env.PATH = binDir; + const result = withPlatform("darwin", () => readClipboardImage()); + assert.equal(result?.mimeType, "image/png"); + assert.equal(result?.dataUrl, `data:image/png;base64,${Buffer.from("fakepng").toString("base64")}`); + } finally { + process.env.PATH = ORIGINAL_PATH; + Object.defineProperty(process, "platform", { value: ORIGINAL_PLATFORM }); + fs.rmSync(binDir, { recursive: true, force: true }); + } } -}); +); diff --git a/src/tests/settings-and-notify.test.ts b/src/tests/settings-and-notify.test.ts index 69b939f..6990288 100644 --- a/src/tests/settings-and-notify.test.ts +++ b/src/tests/settings-and-notify.test.ts @@ -364,39 +364,43 @@ test("buildNotifyEnv injects DURATION", () => { assert.equal(env.DURATION, "2"); }); -test("launchNotifyScript passes DURATION and falls back to /bin/sh for non-executable scripts", () => { - const calls: Array<{ - command: string; - args: string[]; - options: { cwd?: string | URL; env?: NodeJS.ProcessEnv }; - }> = []; - - const spawnProcess: NotifySpawn = (command, args, options) => { - calls.push({ command, args, options: { cwd: options.cwd, env: options.env } }); - - return { - once(event, listener) { - if (event === "error" && calls.length === 1) { - listener({ code: "EACCES" } as NodeJS.ErrnoException); - } - return this; - }, - unref() { - return undefined; - }, +test( + "launchNotifyScript passes DURATION and falls back to /bin/sh for non-executable scripts", + { skip: process.platform === "win32" }, + () => { + const calls: Array<{ + command: string; + args: string[]; + options: { cwd?: string | URL; env?: NodeJS.ProcessEnv }; + }> = []; + + const spawnProcess: NotifySpawn = (command, args, options) => { + calls.push({ command, args, options: { cwd: options.cwd, env: options.env } }); + + return { + once(event, listener) { + if (event === "error" && calls.length === 1) { + listener({ code: "EACCES" } as NodeJS.ErrnoException); + } + return this; + }, + unref() { + return undefined; + }, + }; }; - }; - - launchNotifyScript("/tmp/notify.sh", 2750, "/tmp/project", spawnProcess, { WEBHOOK: "configured" }); - - assert.equal(calls.length, 2); - assert.equal(calls[0]?.command, "/tmp/notify.sh"); - assert.deepEqual(calls[0]?.args, []); - assert.equal(calls[0]?.options.cwd, "/tmp/project"); - assert.equal(calls[0]?.options.env?.DURATION, "2"); - assert.equal(calls[0]?.options.env?.WEBHOOK, "configured"); - assert.equal(calls[1]?.command, "/bin/sh"); - assert.deepEqual(calls[1]?.args, ["/tmp/notify.sh"]); - assert.equal(calls[1]?.options.cwd, "/tmp/project"); - assert.equal(calls[1]?.options.env?.DURATION, "2"); -}); + + launchNotifyScript("/tmp/notify.sh", 2750, "/tmp/project", spawnProcess, { WEBHOOK: "configured" }); + + assert.equal(calls.length, 2); + assert.equal(calls[0]?.command, "/tmp/notify.sh"); + assert.deepEqual(calls[0]?.args, []); + assert.equal(calls[0]?.options.cwd, "/tmp/project"); + assert.equal(calls[0]?.options.env?.DURATION, "2"); + assert.equal(calls[0]?.options.env?.WEBHOOK, "configured"); + assert.equal(calls[1]?.command, "/bin/sh"); + assert.deepEqual(calls[1]?.args, ["/tmp/notify.sh"]); + assert.equal(calls[1]?.options.cwd, "/tmp/project"); + assert.equal(calls[1]?.options.env?.DURATION, "2"); + } +); diff --git a/src/tests/web-search-handler.test.ts b/src/tests/web-search-handler.test.ts index 576a1cb..417c6c4 100644 --- a/src/tests/web-search-handler.test.ts +++ b/src/tests/web-search-handler.test.ts @@ -20,40 +20,44 @@ afterEach(() => { } }); -test("WebSearch executes the configured script with the query as one argument", async () => { - const workspace = createTempWorkspace(); - const scriptPath = path.join(workspace, "web-search.sh"); - fs.writeFileSync( - scriptPath, - [ - "#!/bin/sh", - "printf 'query=%s\\n' \"$1\"", - "printf 'cwd=%s\\n' \"$PWD\"", - "printf 'webhook=%s\\n' \"$WEBHOOK\"", - ].join("\n"), - "utf8" - ); - fs.chmodSync(scriptPath, 0o755); +test( + "WebSearch executes the configured script with the query as one argument", + { skip: process.platform === "win32" }, + async () => { + const workspace = createTempWorkspace(); + const scriptPath = path.join(workspace, "web-search.sh"); + fs.writeFileSync( + scriptPath, + [ + "#!/bin/sh", + "printf 'query=%s\\n' \"$1\"", + "printf 'cwd=%s\\n' \"$PWD\"", + "printf 'webhook=%s\\n' \"$WEBHOOK\"", + ].join("\n"), + "utf8" + ); + fs.chmodSync(scriptPath, 0o755); - const starts: Array<{ id: string | number; command: string }> = []; - const exits: Array = []; - const result = await handleWebSearchTool( - { query: "latest node release" }, - createContext(workspace, { - webSearchTool: scriptPath, - env: { WEBHOOK: "configured" }, - onProcessStart: (id, command) => starts.push({ id, command }), - onProcessExit: (id) => exits.push(id), - }) - ); - const realWorkspace = fs.realpathSync(workspace); + const starts: Array<{ id: string | number; command: string }> = []; + const exits: Array = []; + const result = await handleWebSearchTool( + { query: "latest node release" }, + createContext(workspace, { + webSearchTool: scriptPath, + env: { WEBHOOK: "configured" }, + onProcessStart: (id, command) => starts.push({ id, command }), + onProcessExit: (id) => exits.push(id), + }) + ); + const realWorkspace = fs.realpathSync(workspace); - assert.equal(result.ok, true); - assert.equal(result.output, `query=latest node release\ncwd=${realWorkspace}\nwebhook=configured\n`); - assert.equal(starts.length, 1); - assert.match(starts[0].command, /^WebSearch: latest node release$/); - assert.deepEqual(exits, [starts[0].id]); -}); + assert.equal(result.ok, true); + assert.equal(result.output, `query=latest node release\ncwd=${realWorkspace}\nwebhook=configured\n`); + assert.equal(starts.length, 1); + assert.match(starts[0].command, /^WebSearch: latest node release$/); + assert.deepEqual(exits, [starts[0].id]); + } +); test("WebSearch uses the default API when no script is configured", async () => { const workspace = createTempWorkspace(); diff --git a/src/tests/welcomeScreen.test.ts b/src/tests/welcomeScreen.test.ts index 1e5bc19..df7e109 100644 --- a/src/tests/welcomeScreen.test.ts +++ b/src/tests/welcomeScreen.test.ts @@ -1,17 +1,26 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +import * as os from "os"; +import * as path from "path"; import { buildWelcomeTips, formatHomeRelativePath } from "../ui"; test("formatHomeRelativePath returns tilde for the home directory", () => { - assert.equal(formatHomeRelativePath("/Users/example", "/Users/example"), "~"); + const home = path.resolve("/Users/example"); + assert.equal(formatHomeRelativePath(home, home), "~"); }); test("formatHomeRelativePath shortens paths inside the home directory", () => { - assert.equal(formatHomeRelativePath("/Users/example/dev/project", "/Users/example"), "~/dev/project"); + const home = path.resolve("/Users/example"); + const result = formatHomeRelativePath(path.resolve("/Users/example/dev/project"), home); + assert.equal(result, `~${path.sep}dev${path.sep}project`); }); test("formatHomeRelativePath keeps paths outside the home directory absolute", () => { - assert.equal(formatHomeRelativePath("/tmp/project", "/Users/example"), "/tmp/project"); + const home = path.resolve("/Users/example"); + const other = path.resolve("/tmp/project"); + // The result should be the absolute path since it's outside home + const result = formatHomeRelativePath(other, home); + assert.equal(result, other); }); test("buildWelcomeTips includes built-in slash commands and loaded skills", () => { From cdce3ca6470e0b5768cba308c8d44453fa30e440 Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 11:43:22 +0800 Subject: [PATCH 024/129] fix: cross-platform homedir in tests, skip Windows-incompatible npx test --- src/tests/session.test.ts | 84 ++++++++++++++++++++++++--------------- 1 file changed, 51 insertions(+), 33 deletions(-) diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index ff684a3..3dad6df 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -7,8 +7,17 @@ import { SessionManager, type SessionMessage } from "../session"; const originalFetch = globalThis.fetch; const originalHome = process.env.HOME; +const originalUserProfile = process.env.USERPROFILE; const tempDirs: string[] = []; +/** Set homedir in a cross-platform way (HOME on Unix, USERPROFILE on Windows). */ +function setHomeDir(dir: string): void { + process.env.HOME = dir; + if (process.platform === "win32") { + process.env.USERPROFILE = dir; + } +} + afterEach(() => { globalThis.fetch = originalFetch; if (originalHome === undefined) { @@ -16,6 +25,11 @@ afterEach(() => { } else { process.env.HOME = originalHome; } + if (originalUserProfile === undefined) { + delete process.env.USERPROFILE; + } else { + process.env.USERPROFILE = originalUserProfile; + } while (tempDirs.length > 0) { const dir = tempDirs.pop(); @@ -249,7 +263,7 @@ test("SessionManager replays normal assistant messages with reasoning content in test("SessionManager normalizes legacy sessions without activeTokens to zero", () => { const workspace = createTempDir("deepcode-legacy-active-tokens-workspace-"); const home = createTempDir("deepcode-legacy-active-tokens-home-"); - process.env.HOME = home; + setHomeDir(home); const projectCode = workspace.replace(/[\\/]/g, "-").replace(/:/g, ""); const projectDir = path.join(home, ".deepcode", "projects", projectCode); @@ -281,7 +295,7 @@ test("SessionManager normalizes legacy sessions without activeTokens to zero", ( test("SessionManager keeps usagePerModel null until response usage is available", async () => { const workspace = createTempDir("deepcode-null-usage-per-model-workspace-"); const home = createTempDir("deepcode-null-usage-per-model-home-"); - process.env.HOME = home; + setHomeDir(home); const manager = createMockedClientSessionManager(workspace, [{ choices: [{ message: { content: "no usage" } }] }]); @@ -294,7 +308,7 @@ test("SessionManager keeps usagePerModel null until response usage is available" test("SessionManager marks skills loaded from existing session messages", async () => { const workspace = createTempDir("deepcode-loaded-skills-workspace-"); const home = createTempDir("deepcode-loaded-skills-home-"); - process.env.HOME = home; + setHomeDir(home); const skillDir = path.join(home, ".agents", "skills", "lessweb-starter"); fs.mkdirSync(skillDir, { recursive: true }); @@ -341,7 +355,7 @@ test("SessionManager marks skills loaded from existing session messages", async test("SessionManager lists project skills from .agents with legacy .deepcode compatibility", async () => { const workspace = createTempDir("deepcode-project-skills-workspace-"); const home = createTempDir("deepcode-project-skills-home-"); - process.env.HOME = home; + setHomeDir(home); const userSkillDir = path.join(home, ".agents", "skills", "shared"); fs.mkdirSync(userSkillDir, { recursive: true }); @@ -514,13 +528,16 @@ test("SessionManager reports MCP startup stderr on failure", async () => { assert.match(status?.error ?? "", /mcp startup boom/); }); -test("SessionManager adds -y when launching MCP servers through npx", async () => { - const workspace = createTempDir("deepcode-mcp-npx-workspace-"); - const argsPath = path.join(workspace, "args.json"); - const fakeNpxPath = path.join(workspace, "npx"); - fs.writeFileSync( - fakeNpxPath, - `#!/usr/bin/env node +test( + "SessionManager adds -y when launching MCP servers through npx", + { skip: process.platform === "win32" }, + async () => { + const workspace = createTempDir("deepcode-mcp-npx-workspace-"); + const argsPath = path.join(workspace, "args.json"); + const fakeNpxPath = path.join(workspace, "npx"); + fs.writeFileSync( + fakeNpxPath, + `#!/usr/bin/env node const fs = require("fs"); const readline = require("readline"); fs.writeFileSync(process.env.ARGS_PATH, JSON.stringify(process.argv.slice(2))); @@ -544,23 +561,24 @@ rl.on("line", (line) => { send({ jsonrpc: "2.0", id: request.id, result: { content: [] } }); }); `, - "utf8" - ); - fs.chmodSync(fakeNpxPath, 0o755); + "utf8" + ); + fs.chmodSync(fakeNpxPath, 0o755); - const manager = createSessionManager(workspace, "machine-id-mcp-npx"); - await manager.initMcpServers({ - npxed: { command: fakeNpxPath, args: ["@playwright/mcp@latest"], env: { ARGS_PATH: argsPath } }, - }); + const manager = createSessionManager(workspace, "machine-id-mcp-npx"); + await manager.initMcpServers({ + npxed: { command: fakeNpxPath, args: ["@playwright/mcp@latest"], env: { ARGS_PATH: argsPath } }, + }); - assert.deepEqual(JSON.parse(fs.readFileSync(argsPath, "utf8")) as string[], ["-y", "@playwright/mcp@latest"]); - manager.dispose(); -}); + assert.deepEqual(JSON.parse(fs.readFileSync(argsPath, "utf8")) as string[], ["-y", "@playwright/mcp@latest"]); + manager.dispose(); + } +); test("createSession stores /init and sends the active .deepcode project AGENTS path to the LLM", async () => { const workspace = createTempDir("deepcode-init-deepcode-workspace-"); const home = createTempDir("deepcode-init-deepcode-home-"); - process.env.HOME = home; + setHomeDir(home); globalThis.fetch = (async () => ({ ok: true, text: async () => "" }) as Response) as typeof fetch; fs.mkdirSync(path.join(workspace, ".deepcode"), { recursive: true }); @@ -592,7 +610,7 @@ test("createSession stores /init and sends the active .deepcode project AGENTS p test("replySession stores /init and sends the active root project AGENTS path to the LLM", async () => { const workspace = createTempDir("deepcode-init-root-workspace-"); const home = createTempDir("deepcode-init-root-home-"); - process.env.HOME = home; + setHomeDir(home); globalThis.fetch = (async () => ({ ok: true, text: async () => "" }) as Response) as typeof fetch; fs.writeFileSync(path.join(workspace, "AGENTS.md"), "root project instructions", "utf8"); @@ -619,7 +637,7 @@ test("replySession stores /init and sends the active root project AGENTS path to test("createSession stores /init and sends generate prompt when no project AGENTS file is effective", async () => { const workspace = createTempDir("deepcode-init-generate-workspace-"); const home = createTempDir("deepcode-init-generate-home-"); - process.env.HOME = home; + setHomeDir(home); globalThis.fetch = (async () => ({ ok: true, text: async () => "" }) as Response) as typeof fetch; fs.mkdirSync(path.join(home, ".deepcode"), { recursive: true }); @@ -645,7 +663,7 @@ test("createSession stores /init and sends generate prompt when no project AGENT test("createSession reports a new prompt with the machineId token", async () => { const workspace = createTempDir("deepcode-session-workspace-"); const home = createTempDir("deepcode-session-home-"); - process.env.HOME = home; + setHomeDir(home); const fetchCalls: Array<{ input: string | URL; init?: RequestInit }> = []; globalThis.fetch = (async (input: string | URL, init?: RequestInit) => { @@ -677,7 +695,7 @@ test("createSession reports a new prompt with the machineId token", async () => test("replySession reports a new prompt with the machineId token", async () => { const workspace = createTempDir("deepcode-reply-workspace-"); const home = createTempDir("deepcode-reply-home-"); - process.env.HOME = home; + setHomeDir(home); const fetchCalls: Array<{ input: string | URL; init?: RequestInit }> = []; globalThis.fetch = (async (input: string | URL, init?: RequestInit) => { @@ -708,7 +726,7 @@ test("replySession reports a new prompt with the machineId token", async () => { test("replySession preserves raw session messages when a previous tool call is pending", async () => { const workspace = createTempDir("deepcode-pending-tool-workspace-"); const home = createTempDir("deepcode-pending-tool-home-"); - process.env.HOME = home; + setHomeDir(home); globalThis.fetch = (async () => ({ @@ -1131,7 +1149,7 @@ test("buildOpenAIMessages ignores tool messages that appear before their assista test("SessionManager accumulates response usage while active tokens track the latest response", async () => { const workspace = createTempDir("deepcode-usage-workspace-"); const home = createTempDir("deepcode-usage-home-"); - process.env.HOME = home; + setHomeDir(home); const responses = [ createChatResponse("first", { @@ -1182,7 +1200,7 @@ test("SessionManager accumulates response usage while active tokens track the la test("SessionManager stores usage per model across model changes", async () => { const workspace = createTempDir("deepcode-usage-per-model-workspace-"); const home = createTempDir("deepcode-usage-per-model-home-"); - process.env.HOME = home; + setHomeDir(home); let currentModel = "deepseek-v4-pro"; const responses = [ @@ -1243,7 +1261,7 @@ test("SessionManager stores usage per model across model changes", async () => { test("SessionManager resets active tokens to latest post-compaction response usage", async () => { const workspace = createTempDir("deepcode-compact-usage-workspace-"); const home = createTempDir("deepcode-compact-usage-home-"); - process.env.HOME = home; + setHomeDir(home); const responses = [ createChatResponse("large", { @@ -1285,7 +1303,7 @@ test("SessionManager resets active tokens to latest post-compaction response usa test("SessionManager streams chat completions and counts reasoning progress", async () => { const workspace = createTempDir("deepcode-stream-workspace-"); const home = createTempDir("deepcode-stream-home-"); - process.env.HOME = home; + setHomeDir(home); const progressEvents: Array<{ phase: string; @@ -1352,7 +1370,7 @@ test("SessionManager streams chat completions and counts reasoning progress", as test("SessionManager cancels skill matching before a session is created", async () => { const workspace = createTempDir("deepcode-skill-abort-workspace-"); const home = createTempDir("deepcode-skill-abort-home-"); - process.env.HOME = home; + setHomeDir(home); const skillDir = path.join(home, ".agents", "skills", "demo"); fs.mkdirSync(skillDir, { recursive: true }); @@ -1384,7 +1402,7 @@ test("SessionManager cancels skill matching before a session is created", async test("SessionManager treats OpenAI APIUserAbortError as interrupted", async () => { const workspace = createTempDir("deepcode-api-abort-workspace-"); const home = createTempDir("deepcode-api-abort-home-"); - process.env.HOME = home; + setHomeDir(home); let manager: SessionManager; const client = { From a21e907ddcd61fee119272dadd81bdf35d40f13a Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 11:57:36 +0800 Subject: [PATCH 025/129] fix: restore Node 20 in CI matrix --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index de8600c..4dc891f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,7 @@ jobs: - windows-latest - macos-latest node-version: + - "20" - "22" - "24" From 64bf782fb3ebbbcc7964e7df413cf2bc22bb6559 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Sat, 16 May 2026 11:59:48 +0800 Subject: [PATCH 026/129] feat: update getCurrentDateAndModelPrompt --- src/prompt.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/prompt.ts b/src/prompt.ts index b854860..4774725 100644 --- a/src/prompt.ts +++ b/src/prompt.ts @@ -281,14 +281,17 @@ function readToolDocs(extensionRoot: string, options: PromptToolOptions = {}): s return docs.join("\n\n"); } -function getCurrentDatePrompt(date = new Date()): string { - return `今天是${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日。随着对话的进行,时间在流逝。`; +function getCurrentDateAndModelPrompt(model?: string): string { + const date = new Date(); + let prompt = `今天是${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日。随着对话的进行,时间在流逝。`; + prompt += model ? `\n当前LLM模型为${model},对话中可通过/model命令切换模型。` : ""; + return prompt; } export function getSystemPrompt(projectRoot: string, options: PromptToolOptions = {}): string { const toolDocs = readToolDocs(getExtensionRoot(), options); const basePrompt = toolDocs ? `${SYSTEM_PROMPT_BASE}\n\n# Available Tools\n\n${toolDocs}` : SYSTEM_PROMPT_BASE; - return `${basePrompt}\n\n${getCurrentDatePrompt()}\n\n${getRuntimeContext(projectRoot)}`; + return `${basePrompt}\n\n${getCurrentDateAndModelPrompt(options.model)}\n\n${getRuntimeContext(projectRoot)}`; } export function getCompactPrompt(sessionMessages: SessionMessage[]): string { From cf56131cbbd5c57b2079730754d3fd658f6eae71 Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 12:00:52 +0800 Subject: [PATCH 027/129] fix: quote test glob pattern for Node 20 Windows --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5405b26..ae125e0 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "format:check": "prettier --check 'src/**/*.{ts,tsx}'", "check": "npm run typecheck && npm run lint && npm run format:check", "build": "npm run check && npm run bundle && node -e \"require('fs').chmodSync('dist/cli.js', 0o755)\"", - "test": "tsx --test src/tests/*.test.ts", + "test": "tsx --test \"src/tests/*.test.ts\"", "test:single": "tsx --test", "prepack": "npm run build", "prepare": "husky" From 16e6810875d0b4782a6ee937b8e4df39712c1bb1 Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 12:04:42 +0800 Subject: [PATCH 028/129] fix: add cross-platform test runner for Node 20 compatibility --- package.json | 2 +- src/tests/run-tests.mjs | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 src/tests/run-tests.mjs diff --git a/package.json b/package.json index ae125e0..aceb496 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "format:check": "prettier --check 'src/**/*.{ts,tsx}'", "check": "npm run typecheck && npm run lint && npm run format:check", "build": "npm run check && npm run bundle && node -e \"require('fs').chmodSync('dist/cli.js', 0o755)\"", - "test": "tsx --test \"src/tests/*.test.ts\"", + "test": "node src/tests/run-tests.mjs", "test:single": "tsx --test", "prepack": "npm run build", "prepare": "husky" diff --git a/src/tests/run-tests.mjs b/src/tests/run-tests.mjs new file mode 100644 index 0000000..653ca66 --- /dev/null +++ b/src/tests/run-tests.mjs @@ -0,0 +1,26 @@ +// Cross-platform test runner: finds all *.test.ts files and runs them via tsx. +// Needed because glob expansion in npm scripts behaves differently across +// shells and Node versions (particularly Node 20 on Windows). +/* eslint-disable */ + +import { spawnSync } from "child_process"; +import { readdirSync } from "fs"; +import { fileURLToPath } from "url"; +import { dirname, join } from "path"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +const testFiles = readdirSync(__dirname) + .filter((f) => f.endsWith(".test.ts")) + .map((f) => join(__dirname, f)) + .sort(); + +// Resolve tsx from the project root +const tsx = new URL("../../node_modules/.bin/tsx", import.meta.url).pathname; + +const result = spawnSync(process.execPath, [tsx, "--test", ...testFiles], { + stdio: "inherit", + cwd: join(__dirname, "../.."), +}); + +process.exit(result.status ?? 1); From 9dba13688051cf2b8fffe0e9ed8221bd2ecc0464 Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 12:07:06 +0800 Subject: [PATCH 029/129] fix: use npx for cross-platform tsx resolution in test runner --- src/tests/run-tests.mjs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/tests/run-tests.mjs b/src/tests/run-tests.mjs index 653ca66..3a8465f 100644 --- a/src/tests/run-tests.mjs +++ b/src/tests/run-tests.mjs @@ -15,10 +15,7 @@ const testFiles = readdirSync(__dirname) .map((f) => join(__dirname, f)) .sort(); -// Resolve tsx from the project root -const tsx = new URL("../../node_modules/.bin/tsx", import.meta.url).pathname; - -const result = spawnSync(process.execPath, [tsx, "--test", ...testFiles], { +const result = spawnSync("npx", ["--no-install", "tsx", "--test", ...testFiles], { stdio: "inherit", cwd: join(__dirname, "../.."), }); From 20add1c8deaab468f1802f9d1b56bfe209b0942f Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 12:09:31 +0800 Subject: [PATCH 030/129] fix: resolve tsx binary path cross-platform in test runner --- src/tests/run-tests.mjs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/tests/run-tests.mjs b/src/tests/run-tests.mjs index 3a8465f..ed1fe16 100644 --- a/src/tests/run-tests.mjs +++ b/src/tests/run-tests.mjs @@ -4,20 +4,35 @@ /* eslint-disable */ import { spawnSync } from "child_process"; -import { readdirSync } from "fs"; +import { readdirSync, existsSync } from "fs"; import { fileURLToPath } from "url"; import { dirname, join } from "path"; const __dirname = dirname(fileURLToPath(import.meta.url)); +const projectRoot = join(__dirname, "../.."); const testFiles = readdirSync(__dirname) .filter((f) => f.endsWith(".test.ts")) .map((f) => join(__dirname, f)) .sort(); -const result = spawnSync("npx", ["--no-install", "tsx", "--test", ...testFiles], { +// Cross-platform resolution of the local tsx binary +function findTsx() { + const candidates = [ + join(projectRoot, "node_modules", ".bin", "tsx"), + join(projectRoot, "node_modules", ".bin", "tsx.cmd"), + ]; + for (const c of candidates) { + if (existsSync(c)) return c; + } + return candidates[0]; +} + +const tsx = findTsx(); + +const result = spawnSync(tsx, ["--test", ...testFiles], { stdio: "inherit", - cwd: join(__dirname, "../.."), + cwd: projectRoot, }); process.exit(result.status ?? 1); From abe5190ccc11243e10c20a11e5209ccf04b813d3 Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 12:12:54 +0800 Subject: [PATCH 031/129] fix: use node --import tsx --test with native glob expansion for cross-platform --- package.json | 2 +- src/tests/run-tests.mjs | 38 -------------------------------------- 2 files changed, 1 insertion(+), 39 deletions(-) delete mode 100644 src/tests/run-tests.mjs diff --git a/package.json b/package.json index aceb496..1bff1df 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "format:check": "prettier --check 'src/**/*.{ts,tsx}'", "check": "npm run typecheck && npm run lint && npm run format:check", "build": "npm run check && npm run bundle && node -e \"require('fs').chmodSync('dist/cli.js', 0o755)\"", - "test": "node src/tests/run-tests.mjs", + "test": "node --import tsx --test src/tests/*.test.ts", "test:single": "tsx --test", "prepack": "npm run build", "prepare": "husky" diff --git a/src/tests/run-tests.mjs b/src/tests/run-tests.mjs deleted file mode 100644 index ed1fe16..0000000 --- a/src/tests/run-tests.mjs +++ /dev/null @@ -1,38 +0,0 @@ -// Cross-platform test runner: finds all *.test.ts files and runs them via tsx. -// Needed because glob expansion in npm scripts behaves differently across -// shells and Node versions (particularly Node 20 on Windows). -/* eslint-disable */ - -import { spawnSync } from "child_process"; -import { readdirSync, existsSync } from "fs"; -import { fileURLToPath } from "url"; -import { dirname, join } from "path"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const projectRoot = join(__dirname, "../.."); - -const testFiles = readdirSync(__dirname) - .filter((f) => f.endsWith(".test.ts")) - .map((f) => join(__dirname, f)) - .sort(); - -// Cross-platform resolution of the local tsx binary -function findTsx() { - const candidates = [ - join(projectRoot, "node_modules", ".bin", "tsx"), - join(projectRoot, "node_modules", ".bin", "tsx.cmd"), - ]; - for (const c of candidates) { - if (existsSync(c)) return c; - } - return candidates[0]; -} - -const tsx = findTsx(); - -const result = spawnSync(tsx, ["--test", ...testFiles], { - stdio: "inherit", - cwd: projectRoot, -}); - -process.exit(result.status ?? 1); From d5da01e848a724534b22763daf6db1e64e7f191c Mon Sep 17 00:00:00 2001 From: lellansin Date: Sat, 16 May 2026 12:15:53 +0800 Subject: [PATCH 032/129] fix: add glob package, use cross-platform test runner --- package-lock.json | 95 +++++++++++++++++++++++++++++++++++++++++ package.json | 3 +- src/tests/run-tests.mjs | 13 ++++++ 3 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 src/tests/run-tests.mjs diff --git a/package-lock.json b/package-lock.json index 17fa96f..958eed7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -32,6 +32,7 @@ "eslint": "^9.39.4", "eslint-config-prettier": "^10.1.8", "eslint-plugin-react-hooks": "^7.1.1", + "glob": "^13.0.6", "husky": "^9.1.7", "lint-staged": "^17.0.4", "prettier": "^3.8.3", @@ -2249,6 +2250,24 @@ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" } }, + "node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmmirror.com/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-6.0.2.tgz", @@ -2262,6 +2281,45 @@ "node": ">=10.13.0" } }, + "node_modules/glob/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "5.0.6", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-5.0.6.tgz", + "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/globals": { "version": "14.0.0", "resolved": "https://registry.npmmirror.com/globals/-/globals-14.0.0.tgz", @@ -2911,6 +2969,16 @@ "node": "*" } }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmmirror.com/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", @@ -3060,6 +3128,33 @@ "node": ">=8" } }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "11.3.6", + "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-11.3.6.tgz", + "integrity": "sha512-Gf/KoL3C/MlI7Bt0PGI9I+TeTC/I6r/csU58N4BSNc4lppLBeKsOdFYkK+dX0ABDUMJNfCHTyPpzwwO21Awd3A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", diff --git a/package.json b/package.json index 1bff1df..f1fd660 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "format:check": "prettier --check 'src/**/*.{ts,tsx}'", "check": "npm run typecheck && npm run lint && npm run format:check", "build": "npm run check && npm run bundle && node -e \"require('fs').chmodSync('dist/cli.js', 0o755)\"", - "test": "node --import tsx --test src/tests/*.test.ts", + "test": "node src/tests/run-tests.mjs", "test:single": "tsx --test", "prepack": "npm run build", "prepare": "husky" @@ -58,6 +58,7 @@ "eslint": "^9.39.4", "eslint-config-prettier": "^10.1.8", "eslint-plugin-react-hooks": "^7.1.1", + "glob": "^13.0.6", "husky": "^9.1.7", "lint-staged": "^17.0.4", "prettier": "^3.8.3", diff --git a/src/tests/run-tests.mjs b/src/tests/run-tests.mjs new file mode 100644 index 0000000..4d09f5b --- /dev/null +++ b/src/tests/run-tests.mjs @@ -0,0 +1,13 @@ +// Cross-platform test runner: finds all *.test.ts files and runs them via tsx. +// Uses the glob package for reliable cross-platform pattern expansion (Node 20+). +/* eslint-disable */ + +import { globSync } from "glob"; +import { spawnSync } from "child_process"; + +const cwd = new URL("../..", import.meta.url); +const testFiles = globSync("src/tests/*.test.ts", { cwd }); + +const result = spawnSync(process.execPath, ["--import", "tsx", "--test", ...testFiles], { stdio: "inherit", cwd }); + +process.exit(result.status ?? 1); From be6d66f19eaabfc370776336557abf414a89af79 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Sat, 16 May 2026 13:33:07 +0800 Subject: [PATCH 033/129] revert: undo PR #70 --- src/tests/promptInputKeys.test.ts | 6 ++-- src/ui/prompt/cursor.ts | 6 ++-- src/ui/prompt/useTerminalInput.ts | 56 +++---------------------------- 3 files changed, 9 insertions(+), 59 deletions(-) diff --git a/src/tests/promptInputKeys.test.ts b/src/tests/promptInputKeys.test.ts index 8952a3d..69d2075 100644 --- a/src/tests/promptInputKeys.test.ts +++ b/src/tests/promptInputKeys.test.ts @@ -80,7 +80,7 @@ test("parseTerminalInput keeps BS payload for meta+backspace", () => { test("parseTerminalInput recognizes shifted return sequences", () => { const { input, key } = parseTerminalInput("\u001B\r"); - assert.equal(input, ""); + assert.equal(input, "\r"); assert.equal(key.return, true); assert.equal(key.shift, true); assert.equal(key.meta, false); @@ -108,8 +108,8 @@ test("parseTerminalInput recognizes alternate shifted return sequences", () => { }); test("terminal extended key helpers request and restore modifyOtherKeys mode", () => { - assert.equal(enableTerminalExtendedKeys(), "\u001B[>4;1m\u001B[>1u"); - assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m\u001B[4;1m"); + assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m"); }); test("parseTerminalInput recognizes terminal focus events", () => { diff --git a/src/ui/prompt/cursor.ts b/src/ui/prompt/cursor.ts index 5eff1de..2668470 100644 --- a/src/ui/prompt/cursor.ts +++ b/src/ui/prompt/cursor.ts @@ -40,14 +40,12 @@ function disableTerminalFocusReporting(): string { return "\u001B[?1004l"; } -// xterm modifyOtherKeys + Kitty progressive enhancement. -// Both are needed: some terminals (incl. Windows Terminal) only respond to Kitty. export function enableTerminalExtendedKeys(): string { - return "\u001B[>4;1m\u001B[>1u"; + return "\u001B[>4;1m"; } export function disableTerminalExtendedKeys(): string { - return "\u001B[>4;0m\u001B[4;0m"; } export function getPromptCursorPlacement( diff --git a/src/ui/prompt/useTerminalInput.ts b/src/ui/prompt/useTerminalInput.ts index e6e0e28..8013ff6 100644 --- a/src/ui/prompt/useTerminalInput.ts +++ b/src/ui/prompt/useTerminalInput.ts @@ -26,55 +26,7 @@ const BACKSPACE_BYTES = new Set(["\u007F", "\b"]); const FORWARD_DELETE_SEQUENCES = new Set(["\u001B[3~", "\u001B[P"]); const HOME_SEQUENCES = new Set(["\u001B[H", "\u001B[1~", "\u001B[7~", "\u001BOH"]); const END_SEQUENCES = new Set(["\u001B[F", "\u001B[4~", "\u001B[8~", "\u001BOF"]); -// Known exact Shift+Enter sequences (both xterm modifyOtherKeys and Kitty protocol). -const SHIFT_RETURN_SEQUENCES = new Set([ - "\u001B\r", - "\u001B[13;2u", - "\u001B[13;1u", - "\u001B[13;2~", - "\u001B[13;1~", - "\u001B[27;2;13~", - "\u001B[27;1;13~", -]); - -// CSI u format: ESC [ keycode ; modifier u -// CSI ~ format: ESC [ keycode ; modifier ~ -// Extended: ESC [ 27 ; modifier ; keycode ~ -const CSI_SHIFT_RETURN_RE = /^\u001B\[13;(\d+)[u~]$/; -const CSI_EXTENDED_SHIFT_RETURN_RE = /^\u001B\[27;(\d+);13~$/; - -// Check whether a raw sequence represents Shift+Enter by parsing the modifier -// parameter dynamically. This handles terminals (e.g. Windows Terminal) that -// set extra flags on the modifier (e.g. 130 = 128 + 2) while the existing -// SHIFT_RETURN_SEQUENCES Set only covers the canonical values (2 and 1). -function isShiftReturn(raw: string): boolean { - if (SHIFT_RETURN_SEQUENCES.has(raw)) return true; - - let m: RegExpMatchArray | null; - if ((m = raw.match(CSI_SHIFT_RETURN_RE)) !== null) { - const mod = parseInt(m[1], 10); - // xterm: Shift=2 (bit 1); Kitty: Shift=1 (bit 0) - return (mod & 2) !== 0 || (mod & 1) !== 0; - } - if ((m = raw.match(CSI_EXTENDED_SHIFT_RETURN_RE)) !== null) { - const mod = parseInt(m[1], 10); - return (mod & 2) !== 0 || (mod & 1) !== 0; - } - return false; -} - -// Any CSI sequence with keycode=13 (Enter) — with or without modifiers. -// Kitty progressive enhancement (ESC[>1u) sends plain Enter as ESC[13u -// or ESC[13;NUMBERu with extra flags; xterm sends ESC[13;2u for Shift. -const CSI_RETURN_RE = /^\u001B\[13;(\d+)[u~]$/; -const CSI_EXTENDED_RETURN_RE = /^\u001B\[27;(\d+);13~$/; - -function isReturn(raw: string): boolean { - if (raw === "\r") return true; - if (SHIFT_RETURN_SEQUENCES.has(raw)) return true; - if (META_RETURN_SEQUENCES.has(raw)) return true; - return CSI_RETURN_RE.test(raw) || CSI_EXTENDED_RETURN_RE.test(raw); -} +const SHIFT_RETURN_SEQUENCES = new Set(["\u001B\r", "\u001B[13;2u", "\u001B[13;2~", "\u001B[27;2;13~"]); const META_RETURN_SEQUENCES = new Set(["\u001B[13;3u", "\u001B[13;4u"]); const CTRL_LEFT_SEQUENCES = new Set(["\u001B[1;5D", "\u001B[5D"]); const CTRL_RIGHT_SEQUENCES = new Set(["\u001B[1;5C", "\u001B[5C"]); @@ -161,10 +113,10 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: end: END_SEQUENCES.has(raw), pageDown: raw === "\u001B[6~", pageUp: raw === "\u001B[5~", - return: isReturn(raw), + return: raw === "\r" || SHIFT_RETURN_SEQUENCES.has(raw) || META_RETURN_SEQUENCES.has(raw), escape: raw === "\u001B", ctrl: CTRL_LEFT_SEQUENCES.has(raw) || CTRL_RIGHT_SEQUENCES.has(raw), - shift: isShiftReturn(raw), + shift: SHIFT_RETURN_SEQUENCES.has(raw), tab: raw === "\t" || raw === "\u001B[Z", backspace: BACKSPACE_BYTES.has(raw), delete: FORWARD_DELETE_SEQUENCES.has(raw), @@ -210,7 +162,7 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: key.shift = true; } - if (key.tab || key.backspace || key.delete || key.return) { + if (key.tab || key.backspace || key.delete) { input = ""; } From 5e3540c2d503b0bfb3d6405b8b37832363e74226 Mon Sep 17 00:00:00 2001 From: Lellansin Date: Sat, 16 May 2026 15:20:08 +0800 Subject: [PATCH 034/129] feat: add Ctrl+O to view live process stdout in fullscreen overlay MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add onProcessStdout callback chain through executor → bash-handler → session → App - Stream real-time stdout/stderr from bash commands to UI ref (capped at 1MB) - Add ProcessStdoutView fullscreen overlay with scroll support - Bind Ctrl+O in PromptInput to toggle the stdout view - Footer hint shows 'ctrl+o view output' when a process is running --- package-lock.json | 814 +++++++---------------------------- src/session.ts | 4 + src/tools/bash-handler.ts | 4 + src/tools/executor.ts | 3 + src/ui/App.tsx | 37 +- src/ui/ProcessStdoutView.tsx | 109 +++++ src/ui/PromptInput.tsx | 21 +- 7 files changed, 327 insertions(+), 665 deletions(-) create mode 100644 src/ui/ProcessStdoutView.tsx diff --git a/package-lock.json b/package-lock.json index 958eed7..f9caecd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -846,13 +846,6 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/@eslint/eslintrc/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" - }, "node_modules/@eslint/eslintrc/node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmmirror.com/ignore/-/ignore-5.3.2.tgz", @@ -863,19 +856,6 @@ "node": ">= 4" } }, - "node_modules/@eslint/eslintrc/node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, "node_modules/@eslint/js": { "version": "9.39.4", "resolved": "https://registry.npmmirror.com/@eslint/js/-/js-9.39.4.tgz", @@ -1060,13 +1040,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "25.6.0", - "resolved": "https://registry.npmmirror.com/@types/node/-/node-25.6.0.tgz", - "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", + "version": "25.8.0", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-25.8.0.tgz", + "integrity": "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~7.19.0" + "undici-types": ">=7.24.0 <7.24.7" } }, "node_modules/@types/react": { @@ -1086,17 +1066,17 @@ "license": "MIT" }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.2.tgz", - "integrity": "sha512-j/bwmkBvHUtPNxzuWe5z6BEk3q54YRyGlBXkSsmfoih7zNrBvl5A9A98anlp/7JbyZcWIJ8KXo/3Tq/DjFLtuQ==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.3.tgz", + "integrity": "sha512-PwFvSKsXGShKGW6n5bZOhGHEcCZXM8HofLK9fNsEwZXzFRjoY+XT1Vsf1zgyXdwTr0ZYz1/2tkZ0DBTT9jZjhw==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.59.2", - "@typescript-eslint/type-utils": "8.59.2", - "@typescript-eslint/utils": "8.59.2", - "@typescript-eslint/visitor-keys": "8.59.2", + "@typescript-eslint/scope-manager": "8.59.3", + "@typescript-eslint/type-utils": "8.59.3", + "@typescript-eslint/utils": "8.59.3", + "@typescript-eslint/visitor-keys": "8.59.3", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" @@ -1109,22 +1089,22 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.59.2", + "@typescript-eslint/parser": "^8.59.3", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "node_modules/@typescript-eslint/parser": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-8.59.2.tgz", - "integrity": "sha512-plR3pp6D+SSUn1HM7xvSkx12/DhoHInI2YF35KAcVFNZvlC0gtrWqx7Qq1oH2Ssgi0vlFRCTbP+DZc7B9+TtsQ==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-8.59.3.tgz", + "integrity": "sha512-HPwA+hVkfcriajbNvTmZv4VRauibay+cWArYUYq7u7W7PmGShMxbPxLvrwDme55a6d5alG3nrYfhyJ/G28XlLg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.59.2", - "@typescript-eslint/types": "8.59.2", - "@typescript-eslint/typescript-estree": "8.59.2", - "@typescript-eslint/visitor-keys": "8.59.2", + "@typescript-eslint/scope-manager": "8.59.3", + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/typescript-estree": "8.59.3", + "@typescript-eslint/visitor-keys": "8.59.3", "debug": "^4.4.3" }, "engines": { @@ -1140,14 +1120,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/project-service/-/project-service-8.59.2.tgz", - "integrity": "sha512-+2hqvEkeyf/0FBor67duF0Ll7Ot8jyKzDQOSrxazF/danillRq2DwR9dLptsXpoZQqxE1UisSmoZewrlPas9Vw==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/project-service/-/project-service-8.59.3.tgz", + "integrity": "sha512-ECiUWa/KYRGDFUqTNehaRgzDshnJfkTABJxVemHk4ko22gcr0ukloKjWvyQ64g8YCV/UI47kN1dbmjf/GaQYng==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.59.2", - "@typescript-eslint/types": "^8.59.2", + "@typescript-eslint/tsconfig-utils": "^8.59.3", + "@typescript-eslint/types": "^8.59.3", "debug": "^4.4.3" }, "engines": { @@ -1162,14 +1142,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-8.59.2.tgz", - "integrity": "sha512-JzfyEpEtOU89CcFSwyNS3mu4MLvLSXqnmX05+aKBDM+TdR5jzcGOEBwxwGNxrEQ7p/z6kK2WyioCGBf2zZBnvg==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-8.59.3.tgz", + "integrity": "sha512-t2LvZnoEfzKtnPjgeEu41xw5gxq9mQVfYy4OoZ4Vlt0sk3JwxmhCca/AR7DwOiHrjWgjAj6as4AhRLKSDfvZIA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.59.2", - "@typescript-eslint/visitor-keys": "8.59.2" + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/visitor-keys": "8.59.3" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1180,9 +1160,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.59.2.tgz", - "integrity": "sha512-BKK4alN7oi4C/zv4VqHQ+uRU+lTa6JGIZ7s1juw7b3RHo9OfKB+bKX3u0iVZetdsUCBBkSbdWbarJbmN0fTeSw==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.59.3.tgz", + "integrity": "sha512-PcIJHjmaREXLgIAIzLnSY9VucEzz8FKXsRgFa1DmdGCK/5tJpW03TKJF01Q6VZd1lLdz2sIKPWaDUZN9dp//dw==", "dev": true, "license": "MIT", "engines": { @@ -1197,15 +1177,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/type-utils/-/type-utils-8.59.2.tgz", - "integrity": "sha512-nhqaj1nmTdVVl/BP5omXNRGO38jn5iosis2vbdmupF2txCf8ylWT8lx+JlvMYYVqzGVKtjojUFoQ3JRWK+mfzQ==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/type-utils/-/type-utils-8.59.3.tgz", + "integrity": "sha512-g71d8QD8UaiHGvrJwyIS1hCX5r63w6Jll+4VEYhEAHXTDIqX1JgxhTAbEHtKntL9kuc4jRo7/GWw5xfCepSccQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.59.2", - "@typescript-eslint/typescript-estree": "8.59.2", - "@typescript-eslint/utils": "8.59.2", + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/typescript-estree": "8.59.3", + "@typescript-eslint/utils": "8.59.3", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, @@ -1222,9 +1202,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/types/-/types-8.59.2.tgz", - "integrity": "sha512-e82GVOE8Ps3E++Egvb6Y3Dw0S10u8NkQ9KXmtRhCWJJ8kDhOJTvtMAWnFL16kB1583goCWXsr0NieKCZMs2/0Q==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/types/-/types-8.59.3.tgz", + "integrity": "sha512-ePFoH0g4ludssdRFqqDxQePCxU4WQyRa9+XVwjm7yLn0FKhMeoetC+qBEEI1Eyb1pGSDveTIT09Bvw2WhlGayg==", "dev": true, "license": "MIT", "engines": { @@ -1236,16 +1216,16 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.59.2.tgz", - "integrity": "sha512-o0XPGNwcWw+FIwStOWn+BwBuEmL6QXP0rsvAFg7ET1dey1Nr6Wb1ac8p5HEsK0ygO/6mUxlk+YWQD9xcb/nnXg==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.59.3.tgz", + "integrity": "sha512-CbRjVRAf7Lr9Kr8RopKcbY45p2VfmmHrm0ygOCYFi7oU8q19m0Fs/6iHS7kNOmwpp+ob07ZVcAqlxUod9lYdmg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.59.2", - "@typescript-eslint/tsconfig-utils": "8.59.2", - "@typescript-eslint/types": "8.59.2", - "@typescript-eslint/visitor-keys": "8.59.2", + "@typescript-eslint/project-service": "8.59.3", + "@typescript-eslint/tsconfig-utils": "8.59.3", + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/visitor-keys": "8.59.3", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", @@ -1316,16 +1296,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/utils/-/utils-8.59.2.tgz", - "integrity": "sha512-Juw3EinkXqjaffxz6roowvV7GZT/kET5vSKKZT6upl5TXdWkLkYmNPXwDDL2Vkt2DPn0nODIS4egC/0AGxKo/Q==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/utils/-/utils-8.59.3.tgz", + "integrity": "sha512-JAvT14goBzRzzzZyqq3P9BLArIxTtQURUtFgQ/V7FO+eU+Gg6ES+5ymOPP1wRxXcxAYeivCk4uS3jCKWI1K8Zg==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.59.2", - "@typescript-eslint/types": "8.59.2", - "@typescript-eslint/typescript-estree": "8.59.2" + "@typescript-eslint/scope-manager": "8.59.3", + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/typescript-estree": "8.59.3" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1340,13 +1320,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.59.2.tgz", - "integrity": "sha512-NwjLUnGy8/Zfx23fl50tRC8rYaYnM52xNRYFAXvmiil9yh1+K6aRVQMnzW6gQB/1DLgWt977lYQn7C+wtgXZiA==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.59.3.tgz", + "integrity": "sha512-f1UQF7ggd42YiwI5wGrRaPsa+P0CINBlrkLPmGfpq/u/I/oVtecoEIfFR9ag/oa1sLOsRNZ6xehf6qMZhQGBDg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.59.2", + "@typescript-eslint/types": "8.59.3", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -1450,13 +1430,11 @@ } }, "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmmirror.com/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "license": "MIT", - "dependencies": { - "sprintf-js": "~1.0.2" - } + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" }, "node_modules/auto-bind": { "version": "5.0.1", @@ -1725,7 +1703,7 @@ }, "node_modules/ejs": { "version": "5.0.2", - "resolved": "https://registry.npmjs.org/ejs/-/ejs-5.0.2.tgz", + "resolved": "https://registry.npmmirror.com/ejs/-/ejs-5.0.2.tgz", "integrity": "sha512-IpbUaI/CAW86l3f+T8zN0iggSc0LmMZLcIW5eRVStLVNCoTXkE0YlncbbH50fp8Cl6zHIky0sW2uUbhBqGw0Jw==", "license": "Apache-2.0", "bin": { @@ -1736,9 +1714,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.353", - "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.5.353.tgz", - "integrity": "sha512-kOrWphBi8TOZyiJZqsgqIle0lw+tzmnQK83pV9dZUd01Nm2POECSyFQMAuarzZdYqQW7FH9RaYOuaRo3h+bQ3w==", + "version": "1.5.356", + "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.5.356.tgz", + "integrity": "sha512-9NgFd7m5t5MCJ5rUSjJITUXAH9mEGlrlofnMf4YEr+pz6JlP7cWmTAH+JFmbPnaSW8koVTkuW7pacORWAnA5Yw==", "dev": true, "license": "ISC" }, @@ -1824,12 +1802,16 @@ } }, "node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, "license": "MIT", "engines": { - "node": ">=8" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/eslint": { @@ -1991,19 +1973,6 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/eslint/node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/eslint/node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmmirror.com/ignore/-/ignore-5.3.2.tgz", @@ -2226,9 +2195,9 @@ } }, "node_modules/get-east-asian-width": { - "version": "1.5.0", - "resolved": "https://registry.npmmirror.com/get-east-asian-width/-/get-east-asian-width-1.5.0.tgz", - "integrity": "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==", + "version": "1.6.0", + "resolved": "https://registry.npmmirror.com/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", + "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", "license": "MIT", "engines": { "node": ">=18" @@ -2237,22 +2206,9 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/get-tsconfig": { - "version": "4.14.0", - "resolved": "https://registry.npmmirror.com/get-tsconfig/-/get-tsconfig-4.14.0.tgz", - "integrity": "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==", - "dev": true, - "license": "MIT", - "dependencies": { - "resolve-pkg-maps": "^1.0.0" - }, - "funding": { - "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" - } - }, "node_modules/glob": { "version": "13.0.6", - "resolved": "https://registry.npmmirror.com/glob/-/glob-13.0.6.tgz", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", "dev": true, "license": "BlueOak-1.0.0", @@ -2283,7 +2239,7 @@ }, "node_modules/glob/node_modules/balanced-match": { "version": "4.0.4", - "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", "dev": true, "license": "MIT", @@ -2293,7 +2249,7 @@ }, "node_modules/glob/node_modules/brace-expansion": { "version": "5.0.6", - "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-5.0.6.tgz", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", "dev": true, "license": "MIT", @@ -2306,7 +2262,7 @@ }, "node_modules/glob/node_modules/minimatch": { "version": "10.2.5", - "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-10.2.5.tgz", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", "dev": true, "license": "BlueOak-1.0.0", @@ -2361,6 +2317,28 @@ "node": ">=6.0" } }, + "node_modules/gray-matter/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmmirror.com/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/gray-matter/node_modules/js-yaml": { + "version": "3.14.2", + "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz", @@ -2453,9 +2431,9 @@ } }, "node_modules/ink": { - "version": "7.0.1", - "resolved": "https://registry.npmmirror.com/ink/-/ink-7.0.1.tgz", - "integrity": "sha512-o6LAC268PLawlGVYrXTyaTfke4VtJftEheuwbgkQf7yvSXyWp1nRwBbAyKEkWXFZZsW/la5wrMuNbuBvZK2C1w==", + "version": "7.0.3", + "resolved": "https://registry.npmmirror.com/ink/-/ink-7.0.3.tgz", + "integrity": "sha512-5kxHkIj9+RuqCU3zyvP4qvYWNOSHP2TW/SHayHGHOmk87KwfVcZwvJGemi9ch+ci2gXUqerK/Eh2DGEDt5q45g==", "license": "MIT", "dependencies": { "@alcalzone/ansi-tokenize": "^0.3.0", @@ -2598,13 +2576,13 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "version": "4.1.1", + "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, "license": "MIT", "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" @@ -2971,7 +2949,7 @@ }, "node_modules/minipass": { "version": "7.1.3", - "resolved": "https://registry.npmmirror.com/minipass/-/minipass-7.1.3.tgz", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", "dev": true, "license": "BlueOak-1.0.0", @@ -2994,9 +2972,9 @@ "license": "MIT" }, "node_modules/node-releases": { - "version": "2.0.38", - "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.38.tgz", - "integrity": "sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==", + "version": "2.0.44", + "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.44.tgz", + "integrity": "sha512-5WUyunoPMsvvEhS8AxHtRzP+oA8UCkJ7YRxatWKjngndhDGLiqEVAQKWjFAiAiuL8zMRGzGSJxFnLetoa43qGQ==", "dev": true, "license": "MIT" }, @@ -3016,9 +2994,9 @@ } }, "node_modules/openai": { - "version": "6.35.0", - "resolved": "https://registry.npmmirror.com/openai/-/openai-6.35.0.tgz", - "integrity": "sha512-L/skwIGnt5xQZHb0UfTu9uAUKbis3ehKypOuJKi20QvG7UStV6C8IC3myGYHcdiF4kms/bAvOJ9UqqNWqi8x/Q==", + "version": "6.37.0", + "resolved": "https://registry.npmmirror.com/openai/-/openai-6.37.0.tgz", + "integrity": "sha512-0H5dEGFmmLv6KSd0W1w2nyL8WsLkX6yoLeQpU+dZAOuGcany5qkYQMmj35ZrKgb6yiyYqpUzFOpR8mZQkgqeEQ==", "license": "Apache-2.0", "bin": { "openai": "bin/cli" @@ -3130,7 +3108,7 @@ }, "node_modules/path-scurry": { "version": "2.0.2", - "resolved": "https://registry.npmmirror.com/path-scurry/-/path-scurry-2.0.2.tgz", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", "dev": true, "license": "BlueOak-1.0.0", @@ -3147,7 +3125,7 @@ }, "node_modules/path-scurry/node_modules/lru-cache": { "version": "11.3.6", - "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-11.3.6.tgz", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.3.6.tgz", "integrity": "sha512-Gf/KoL3C/MlI7Bt0PGI9I+TeTC/I6r/csU58N4BSNc4lppLBeKsOdFYkK+dX0ABDUMJNfCHTyPpzwwO21Awd3A==", "dev": true, "license": "BlueOak-1.0.0", @@ -3212,9 +3190,9 @@ } }, "node_modules/react": { - "version": "19.2.5", - "resolved": "https://registry.npmmirror.com/react/-/react-19.2.5.tgz", - "integrity": "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==", + "version": "19.2.6", + "resolved": "https://registry.npmmirror.com/react/-/react-19.2.6.tgz", + "integrity": "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==", "license": "MIT", "engines": { "node": ">=0.10.0" @@ -3245,16 +3223,6 @@ "node": ">=4" } }, - "node_modules/resolve-pkg-maps": { - "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", - "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" - } - }, "node_modules/restore-cursor": { "version": "4.0.0", "resolved": "https://registry.npmmirror.com/restore-cursor/-/restore-cursor-4.0.0.tgz", @@ -3370,6 +3338,15 @@ "node": ">=10" } }, + "node_modules/stack-utils/node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/string-argv": { "version": "0.3.2", "resolved": "https://registry.npmmirror.com/string-argv/-/string-argv-0.3.2.tgz", @@ -3527,14 +3504,13 @@ } }, "node_modules/tsx": { - "version": "4.21.0", - "resolved": "https://registry.npmmirror.com/tsx/-/tsx-4.21.0.tgz", - "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", + "version": "4.22.0", + "resolved": "https://registry.npmmirror.com/tsx/-/tsx-4.22.0.tgz", + "integrity": "sha512-8ccZMPD69s1AbKXx0C5ddTNZfNjwV04iIKgjZmKfKxMynEtSYcK0Lh7iQFh53fI5Yu4pb9usgAiqyPmEONaALg==", "dev": true, "license": "MIT", "dependencies": { - "esbuild": "~0.27.0", - "get-tsconfig": "^4.7.5" + "esbuild": "~0.28.0" }, "bin": { "tsx": "dist/cli.mjs" @@ -3546,490 +3522,6 @@ "fsevents": "~2.3.3" } }, - "node_modules/tsx/node_modules/@esbuild/aix-ppc64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", - "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/android-arm": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.27.7.tgz", - "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/android-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", - "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/android-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.27.7.tgz", - "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/darwin-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", - "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/darwin-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", - "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", - "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/freebsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", - "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-arm": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", - "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", - "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-ia32": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", - "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-loong64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", - "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-mips64el": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", - "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-ppc64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", - "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-riscv64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", - "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-s390x": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", - "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", - "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", - "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/netbsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", - "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", - "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/openbsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", - "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", - "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/sunos-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", - "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", - "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-ia32": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", - "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", - "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/esbuild": { - "version": "0.27.7", - "resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.27.7.tgz", - "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.27.7", - "@esbuild/android-arm": "0.27.7", - "@esbuild/android-arm64": "0.27.7", - "@esbuild/android-x64": "0.27.7", - "@esbuild/darwin-arm64": "0.27.7", - "@esbuild/darwin-x64": "0.27.7", - "@esbuild/freebsd-arm64": "0.27.7", - "@esbuild/freebsd-x64": "0.27.7", - "@esbuild/linux-arm": "0.27.7", - "@esbuild/linux-arm64": "0.27.7", - "@esbuild/linux-ia32": "0.27.7", - "@esbuild/linux-loong64": "0.27.7", - "@esbuild/linux-mips64el": "0.27.7", - "@esbuild/linux-ppc64": "0.27.7", - "@esbuild/linux-riscv64": "0.27.7", - "@esbuild/linux-s390x": "0.27.7", - "@esbuild/linux-x64": "0.27.7", - "@esbuild/netbsd-arm64": "0.27.7", - "@esbuild/netbsd-x64": "0.27.7", - "@esbuild/openbsd-arm64": "0.27.7", - "@esbuild/openbsd-x64": "0.27.7", - "@esbuild/openharmony-arm64": "0.27.7", - "@esbuild/sunos-x64": "0.27.7", - "@esbuild/win32-arm64": "0.27.7", - "@esbuild/win32-ia32": "0.27.7", - "@esbuild/win32-x64": "0.27.7" - } - }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmmirror.com/type-check/-/type-check-0.4.0.tgz", @@ -4073,16 +3565,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.59.2", - "resolved": "https://registry.npmmirror.com/typescript-eslint/-/typescript-eslint-8.59.2.tgz", - "integrity": "sha512-pJw051uomb3ZeCzGTpRb8RbEqB5Y4WWet8gl/GcTlU35BSx0PVdZ86/bqkQCyKKuraVQEK7r6kBHQXF+fBhkoQ==", + "version": "8.59.3", + "resolved": "https://registry.npmmirror.com/typescript-eslint/-/typescript-eslint-8.59.3.tgz", + "integrity": "sha512-KgusgyDgG4LI8Ih/sWaCtZ06tckLAS5CvT5A4D1Q7bYVoAAyzwiZvE4BmwDHkhRVkvhRBepKeASoFzQetha7Fg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.59.2", - "@typescript-eslint/parser": "8.59.2", - "@typescript-eslint/typescript-estree": "8.59.2", - "@typescript-eslint/utils": "8.59.2" + "@typescript-eslint/eslint-plugin": "8.59.3", + "@typescript-eslint/parser": "8.59.3", + "@typescript-eslint/typescript-estree": "8.59.3", + "@typescript-eslint/utils": "8.59.3" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4097,9 +3589,9 @@ } }, "node_modules/undici-types": { - "version": "7.19.2", - "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.19.2.tgz", - "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==", + "version": "7.24.6", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", "dev": true, "license": "MIT" }, @@ -4203,9 +3695,9 @@ } }, "node_modules/ws": { - "version": "8.20.0", - "resolved": "https://registry.npmmirror.com/ws/-/ws-8.20.0.tgz", - "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", + "version": "8.20.1", + "resolved": "https://registry.npmmirror.com/ws/-/ws-8.20.1.tgz", + "integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==", "license": "MIT", "engines": { "node": ">=10.0.0" @@ -4231,9 +3723,9 @@ "license": "ISC" }, "node_modules/yaml": { - "version": "2.8.4", - "resolved": "https://registry.npmmirror.com/yaml/-/yaml-2.8.4.tgz", - "integrity": "sha512-ml/JPOj9fOQK8RNnWojA67GbZ0ApXAUlN2UQclwv2eVgTgn7O9gg9o7paZWKMp4g0H3nTLtS9LVzhkpOFIKzog==", + "version": "2.9.0", + "resolved": "https://registry.npmmirror.com/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", "dev": true, "license": "ISC", "optional": true, diff --git a/src/session.ts b/src/session.ts index 8c078f3..6da8835 100644 --- a/src/session.ts +++ b/src/session.ts @@ -197,6 +197,7 @@ type SessionManagerOptions = { onSessionEntryUpdated?: (entry: SessionEntry) => void; onLlmStreamProgress?: (progress: LlmStreamProgress) => void; onMcpStatusChanged?: () => void; + onProcessStdout?: (pid: number, chunk: string) => void; }; export type LlmStreamProgress = { @@ -220,6 +221,7 @@ export class SessionManager { private readonly onSessionEntryUpdated?: (entry: SessionEntry) => void; private readonly onLlmStreamProgress?: (progress: LlmStreamProgress) => void; private readonly onMcpStatusChanged?: () => void; + private readonly onProcessStdout?: (pid: number, chunk: string) => void; private activeSessionId: string | null = null; private activePromptController: AbortController | null = null; private readonly sessionControllers = new Map(); @@ -235,6 +237,7 @@ export class SessionManager { this.onSessionEntryUpdated = options.onSessionEntryUpdated; this.onLlmStreamProgress = options.onLlmStreamProgress; this.onMcpStatusChanged = options.onMcpStatusChanged; + this.onProcessStdout = options.onProcessStdout; this.toolExecutor = new ToolExecutor(this.projectRoot, this.createOpenAIClient, this.mcpManager); this.mcpManager.prepare(this.getResolvedSettings().mcpServers); } @@ -1699,6 +1702,7 @@ ${skillMd} const toolExecutions = await this.toolExecutor.executeToolCalls(sessionId, toolCalls, { onProcessStart: (pid, command) => this.addSessionProcess(sessionId, pid, command), onProcessExit: (pid) => this.removeSessionProcess(sessionId, pid), + onProcessStdout: (pid, chunk) => this.onProcessStdout?.(Number(pid), chunk), shouldStop: () => this.isInterrupted(sessionId), }); if (this.isInterrupted(sessionId)) { diff --git a/src/tools/bash-handler.ts b/src/tools/bash-handler.ts index 95e7e76..071da53 100644 --- a/src/tools/bash-handler.ts +++ b/src/tools/bash-handler.ts @@ -124,9 +124,13 @@ async function executeShellCommand( child.stdout?.on("data", (chunk: string | Buffer) => { stdout = appendChunk(stdout, chunk); + const text = typeof chunk === "string" ? chunk : chunk.toString("utf8"); + context.onProcessStdout?.(pid as number, text); }); child.stderr?.on("data", (chunk: string | Buffer) => { stderr = appendChunk(stderr, chunk); + const text = typeof chunk === "string" ? chunk : chunk.toString("utf8"); + context.onProcessStdout?.(pid as number, text); }); child.on("error", (spawnError) => { diff --git a/src/tools/executor.ts b/src/tools/executor.ts index bc2d7d8..e6018d9 100644 --- a/src/tools/executor.ts +++ b/src/tools/executor.ts @@ -37,11 +37,13 @@ export type ToolExecutionContext = { createOpenAIClient?: CreateOpenAIClient; onProcessStart?: (processId: string | number, command: string) => void; onProcessExit?: (processId: string | number) => void; + onProcessStdout?: (processId: string | number, chunk: string) => void; }; export type ToolExecutionHooks = { onProcessStart?: (processId: string | number, command: string) => void; onProcessExit?: (processId: string | number) => void; + onProcessStdout?: (processId: string | number, chunk: string) => void; shouldStop?: () => boolean; }; @@ -195,6 +197,7 @@ export class ToolExecutor { createOpenAIClient: this.createOpenAIClient, onProcessStart: hooks?.onProcessStart, onProcessExit: hooks?.onProcessExit, + onProcessStdout: hooks?.onProcessStdout, }); } catch (error) { const message = error instanceof Error ? error.message : String(error); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 8c5c375..c864187 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -30,6 +30,7 @@ import { findExpandedThinkingId } from "./thinkingState"; import { WelcomeScreen } from "./WelcomeScreen"; import { AskUserQuestionPrompt } from "./AskUserQuestionPrompt"; import { McpStatusList } from "./McpStatusList"; +import { ProcessStdoutView } from "./ProcessStdoutView"; import { findPendingAskUserQuestion, formatAskUserQuestionAnswers, @@ -69,6 +70,8 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R const [resolvedSettings, setResolvedSettings] = useState(() => resolveCurrentSettings(projectRoot)); const [nowTick, setNowTick] = useState(0); const [mcpStatuses, setMcpStatuses] = useState>([]); + const [showProcessStdout, setShowProcessStdout] = useState(false); + const processStdoutRef = useRef>(new Map()); const messagesRef = useRef([]); messagesRef.current = messages; @@ -98,6 +101,19 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R // 当 MCP 状态变更时,如果当前正在查看 MCP 状态页面,则更新显示 setMcpStatuses(sessionManager.getMcpStatus()); }, + onProcessStdout: (pid, chunk) => { + const buf = processStdoutRef.current; + const current = buf.get(pid) ?? ""; + // Cap at 1 MB per process to avoid unbounded memory growth + // on noisy or long-running commands like `yes` or verbose builds. + const MAX_STDOUT_BUFFER = 1_000_000; + if (current.length >= MAX_STDOUT_BUFFER) { + return; + } + const text = typeof chunk === "string" ? chunk : String(chunk); + const available = MAX_STDOUT_BUFFER - current.length; + buf.set(pid, current + text.slice(0, available)); + }, }); }, [projectRoot]); @@ -218,6 +234,8 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R setBusy(true); setErrorLine(null); setRunningProcesses(null); + setShowProcessStdout(false); + processStdoutRef.current.clear(); try { await sessionManager.handleUserPrompt(prompt); await refreshSkills(); @@ -238,6 +256,14 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R sessionManager.interruptActiveSession(); }, [sessionManager]); + const handleToggleProcessStdout = useCallback(() => { + setShowProcessStdout(true); + }, []); + + const handleDismissProcessStdout = useCallback(() => { + setShowProcessStdout(false); + }, []); + const handleModelConfigChange = useCallback( (selection: ModelConfigSelection): string => { const current = resolveCurrentSettings(projectRoot); @@ -442,7 +468,14 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R Error: {errorLine} ) : null} - {view === "session-list" ? ( + {showProcessStdout ? ( + + ) : view === "session-list" ? ( void handleSelectSession(id)} @@ -464,9 +497,11 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R promptHistory={promptHistory} busy={busy} loadingText={loadingText} + runningProcesses={runningProcesses} onSubmit={handleSubmit} onModelConfigChange={handleModelConfigChange} onInterrupt={handleInterrupt} + onToggleProcessStdout={handleToggleProcessStdout} placeholder="Type your message..." /> )} diff --git a/src/ui/ProcessStdoutView.tsx b/src/ui/ProcessStdoutView.tsx new file mode 100644 index 0000000..a0676c6 --- /dev/null +++ b/src/ui/ProcessStdoutView.tsx @@ -0,0 +1,109 @@ +import React, { useEffect, useMemo, useRef, useState } from "react"; +import { Box, Text } from "ink"; +import type { SessionEntry } from "../session"; +import { useTerminalInput } from "./prompt"; + +type RunningProcesses = SessionEntry["processes"]; + +type ProcessStdoutViewProps = { + processStdoutRef: React.MutableRefObject>; + runningProcesses: RunningProcesses; + onDismiss: () => void; + screenWidth: number; +}; + +const REFRESH_INTERVAL_MS = 150; +const MAX_VISIBLE_LINES = 100; + +export const ProcessStdoutView = React.memo(function ProcessStdoutView({ + processStdoutRef, + runningProcesses, + onDismiss, + screenWidth, +}: ProcessStdoutViewProps): React.ReactElement { + const [stdoutText, setStdoutText] = useState(""); + const [scrollOffset, setScrollOffset] = useState(0); + const containerRef = useRef<{ lineCount: number }>({ lineCount: 0 }); + + useEffect(() => { + const updateStdout = () => { + let text = ""; + if (runningProcesses && runningProcesses.size > 0) { + for (const [pid, proc] of runningProcesses.entries()) { + const pidNum = Number(pid); + const stdout = processStdoutRef.current.get(pidNum) ?? ""; + if (text) { + text += "\n"; + } + if (runningProcesses.size > 1) { + text += `── Process ${pid} [${proc.command}] ──\n`; + } + text += stdout || "(no output yet)"; + } + } else { + text = "(no running processes)"; + } + setStdoutText(text); + }; + + updateStdout(); + const interval = setInterval(updateStdout, REFRESH_INTERVAL_MS); + return () => clearInterval(interval); + }, [processStdoutRef, runningProcesses]); + + // Update container line count for scroll awareness + const lines = useMemo(() => stdoutText.split("\n"), [stdoutText]); + containerRef.current.lineCount = lines.length; + + const visibleLines = useMemo(() => { + if (lines.length <= MAX_VISIBLE_LINES) { + return lines; + } + const start = Math.max(0, lines.length - MAX_VISIBLE_LINES - scrollOffset); + const slice = lines.slice(start, start + MAX_VISIBLE_LINES); + if (lines.length > MAX_VISIBLE_LINES) { + slice.unshift(`... (${start} lines above · ↑/↓ to scroll · ${lines.length} total lines) ...`); + } + return slice; + }, [lines, scrollOffset]); + + useTerminalInput( + (input, key) => { + if ((key.ctrl && (input === "o" || input === "O")) || key.escape) { + onDismiss(); + return; + } + if (key.upArrow) { + setScrollOffset((s) => Math.min(s + 10, Math.max(0, lines.length - MAX_VISIBLE_LINES))); + return; + } + if (key.downArrow) { + setScrollOffset((s) => Math.max(s - 10, 0)); + return; + } + if (key.pageUp) { + setScrollOffset((s) => Math.min(s + MAX_VISIBLE_LINES, Math.max(0, lines.length - MAX_VISIBLE_LINES))); + return; + } + if (key.pageDown) { + setScrollOffset((s) => Math.max(s - MAX_VISIBLE_LINES, 0)); + return; + } + }, + { isActive: true } + ); + + return ( + + + 📟 Process Output + (Ctrl+O or Esc to close · ↑↓ PageUp/PageDown to scroll) + + + {visibleLines.map((line, index) => ( + {line} + ))} + + + ); +}); diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 3965144..db3a956 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -60,9 +60,11 @@ type Props = { loadingText?: string | null; disabled?: boolean; placeholder?: string; + runningProcesses?: Map | null; onSubmit: (submission: PromptSubmission) => void; onModelConfigChange: (selection: ModelConfigSelection) => string | Promise; onInterrupt: () => void; + onToggleProcessStdout?: () => void; }; const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; @@ -109,9 +111,11 @@ export const PromptInput = React.memo(function PromptInput({ loadingText, disabled, placeholder, + runningProcesses, onSubmit, onModelConfigChange, onInterrupt, + onToggleProcessStdout, }: Props): React.ReactElement { const { exit } = useApp(); const { stdout } = useStdout(); @@ -141,13 +145,15 @@ export const PromptInput = React.memo(function PromptInput({ ); const showMenu = slashMenu.length > 0; const promptHistoryKey = React.useMemo(() => promptHistory.join("\0"), [promptHistory]); + const hasRunningProcess = runningProcesses && runningProcesses.size > 0; + const processHint = hasRunningProcess ? " · ctrl+o view output" : ""; const footerText = statusMessage ? statusMessage : busy ? loadingText && loadingText.trim() - ? loadingText - : "esc to interrupt · ctrl+c to cancel input" - : "enter send · shift+enter newline · ctrl+v image · / commands · ctrl+d exit"; + ? `${loadingText}${processHint}` + : `esc to interrupt · ctrl+c to cancel input${processHint}` + : `enter send · shift+enter newline · ctrl+v image · / commands · ctrl+d exit${processHint}`; useTerminalFocusReporting(stdout, !disabled); useTerminalExtendedKeys(stdout, !disabled); useHiddenTerminalCursor(stdout, !disabled); @@ -223,6 +229,15 @@ export const PromptInput = React.memo(function PromptInput({ return; } + if (key.ctrl && (input === "o" || input === "O")) { + if (runningProcesses && runningProcesses.size > 0 && onToggleProcessStdout) { + onToggleProcessStdout(); + } else { + setStatusMessage("No running process to inspect"); + } + return; + } + if (key.ctrl && (input === "d" || input === "D")) { if (!isEmpty(buffer)) { updateBuffer((s) => deleteForward(s)); From 1878c15a5326630cc23e64fa35855cf5aa728220 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Sat, 16 May 2026 15:41:04 +0800 Subject: [PATCH 035/129] 0.1.21 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 958eed7..51b7a95 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.20", + "version": "0.1.21", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@vegamo/deepcode-cli", - "version": "0.1.20", + "version": "0.1.21", "license": "MIT", "dependencies": { "chalk": "^5.6.2", diff --git a/package.json b/package.json index f1fd660..90c2b51 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.20", + "version": "0.1.21", "description": "Deep Code CLI - Vibe coding for the deepseek-v4 model in your terminal", "license": "MIT", "type": "module", From 38fc20130ac418aa6b8b0da143d10f38a3bd7c81 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Sat, 16 May 2026 23:06:55 +0800 Subject: [PATCH 036/129] feat: update Edit tool with broader backslash matching; add support for stripping accidental read-result tabs in Edit tool; add /continue command to resume conversations and update related functionality --- src/cli.tsx | 1 + src/session.ts | 46 ++++++++++++++++ src/tests/session.test.ts | 94 +++++++++++++++++++++++++++++++++ src/tests/slashCommands.test.ts | 9 +++- src/tests/tool-handlers.test.ts | 74 ++++++++++++++++++++++++++ src/tools/edit-handler.ts | 25 ++++++--- src/ui/App.tsx | 13 ++++- src/ui/PromptInput.tsx | 11 +++- src/ui/slashCommands.ts | 8 ++- 9 files changed, 271 insertions(+), 10 deletions(-) diff --git a/src/cli.tsx b/src/cli.tsx index 112c9dd..a0847d4 100644 --- a/src/cli.tsx +++ b/src/cli.tsx @@ -42,6 +42,7 @@ if (args.includes("--help") || args.includes("-h")) { " /new Start a fresh conversation", " /init Initialize an AGENTS.md file with instructions for LLM", " /resume Pick a previous conversation to continue", + " /continue Continue the active conversation, or resume one if empty", " /exit Quit", " ctrl+d twice Quit", ].join("\n") + "\n" diff --git a/src/session.ts b/src/session.ts index 8c078f3..095cd3a 100644 --- a/src/session.ts +++ b/src/session.ts @@ -957,6 +957,12 @@ ${skillMd} return; } + if (this.isContinuePrompt(userPrompt)) { + this.activeSessionId = sessionId; + await this.activateSession(sessionId, controller); + return; + } + this.reportNewPrompt(); if (userPrompt.text) { @@ -996,6 +1002,15 @@ ${skillMd} await this.activateSession(sessionId, controller); } + private isContinuePrompt(userPrompt: UserPromptContent): boolean { + return ( + typeof userPrompt.text === "string" && + userPrompt.text.trim() === "/continue" && + (!userPrompt.imageUrls || userPrompt.imageUrls.length === 0) && + (!userPrompt.skills || userPrompt.skills.length === 0) + ); + } + async activateSession(sessionId: string, controller?: AbortController): Promise { const startedAt = Date.now(); const { client, model, baseURL, thinkingEnabled, reasoningEffort, debugLogEnabled, notify, env } = @@ -1055,6 +1070,23 @@ ${skillMd} return; } + const pendingToolCalls = this.getTrailingPendingToolCalls(this.listSessionMessages(sessionId)); + if (pendingToolCalls.length > 0) { + const toolAppendResult = await this.appendToolMessages(sessionId, pendingToolCalls); + if (this.isInterrupted(sessionId)) { + return; + } + if (toolAppendResult.waitingForUser) { + this.updateSessionEntry(sessionId, (entry) => ({ + ...entry, + toolCalls: pendingToolCalls, + status: "waiting_for_user", + updateTime: new Date().toISOString(), + })); + return; + } + } + const compactPromptTokenThreshold = getCompactPromptTokenThreshold(model); if (session.activeTokens > compactPromptTokenThreshold) { const message = this.buildAssistantMessage( @@ -1859,6 +1891,20 @@ ${skillMd} return pairings; } + private getTrailingPendingToolCalls(messages: SessionMessage[]): unknown[] { + const activeMessages = messages.filter((message) => !message.compacted); + const latestMessage = activeMessages[activeMessages.length - 1]; + if (!latestMessage || latestMessage.role !== "assistant") { + return []; + } + + const toolCalls = this.getAssistantToolCalls(latestMessage); + if (toolCalls.length === 0) { + return []; + } + return toolCalls.filter((toolCall) => Boolean(this.getToolCallId(toolCall))); + } + private findPairableToolMessageIndex( messages: SessionMessage[], assistantIndex: number, diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 3dad6df..50d016c 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -723,6 +723,100 @@ test("replySession reports a new prompt with the machineId token", async () => { assert.equal((fetchCalls[0].init?.headers as Record).Token, "machine-id-456"); }); +test("replySession continues without appending /continue as a user message", async () => { + const workspace = createTempDir("deepcode-continue-workspace-"); + const home = createTempDir("deepcode-continue-home-"); + setHomeDir(home); + + const fetchCalls: Array<{ input: string | URL; init?: RequestInit }> = []; + globalThis.fetch = (async (input: string | URL, init?: RequestInit) => { + fetchCalls.push({ input, init }); + return { + ok: true, + text: async () => "", + } as Response; + }) as typeof fetch; + + const manager = createSessionManager(workspace, "machine-id-continue"); + const activatedSessionIds: string[] = []; + (manager as any).activateSession = async (sessionId: string) => { + activatedSessionIds.push(sessionId); + }; + + const sessionId = await manager.createSession({ text: "first prompt" }); + await flushPromises(); + const messagesBefore = manager.listSessionMessages(sessionId); + fetchCalls.length = 0; + activatedSessionIds.length = 0; + + await manager.replySession(sessionId, { text: "/continue" }); + await flushPromises(); + + const messagesAfter = manager.listSessionMessages(sessionId); + const userMessages = messagesAfter.filter((message) => message.role === "user"); + + assert.equal(activatedSessionIds.length, 1); + assert.equal(activatedSessionIds[0], sessionId); + assert.equal(messagesAfter.length, messagesBefore.length); + assert.equal( + userMessages.some((message) => message.content === "/continue"), + false + ); + assert.equal(fetchCalls.length, 0); +}); + +test("replySession /continue runs trailing pending tool calls before requesting another response", async () => { + const workspace = createTempDir("deepcode-continue-tool-workspace-"); + const home = createTempDir("deepcode-continue-tool-home-"); + setHomeDir(home); + + const responses = [ + createChatResponse("continued after tool", { + prompt_tokens: 9, + completion_tokens: 2, + total_tokens: 11, + }), + ]; + const manager = createMockedClientSessionManager(workspace, responses); + const originalActivateSession = manager.activateSession.bind(manager); + (manager as any).activateSession = async () => {}; + + const sessionId = await manager.createSession({ text: "first prompt" }); + const pendingAssistant = (manager as any).buildAssistantMessage( + sessionId, + "Need to read a file", + [ + { + id: "call-pending-read", + type: "function", + function: { name: "read", arguments: JSON.stringify({ file_path: path.join(workspace, "note.txt") }) }, + }, + ], + null + ) as SessionMessage; + fs.writeFileSync(path.join(workspace, "note.txt"), "hello from pending tool\n", "utf8"); + (manager as any).appendSessionMessage(sessionId, pendingAssistant); + (manager as any).activateSession = originalActivateSession; + + await manager.replySession(sessionId, { text: "/continue" }); + + const messages = manager.listSessionMessages(sessionId); + const toolMessage = messages.find((message) => { + const params = message.messageParams as { tool_call_id?: string } | null; + return message.role === "tool" && params?.tool_call_id === "call-pending-read"; + }); + const assistantMessages = messages.filter((message) => message.role === "assistant"); + const userMessages = messages.filter((message) => message.role === "user"); + + assert.ok(toolMessage); + assert.match(toolMessage.content ?? "", /hello from pending tool/); + assert.equal(assistantMessages[assistantMessages.length - 1]?.content, "continued after tool"); + assert.equal( + userMessages.some((message) => message.content === "/continue"), + false + ); +}); + test("replySession preserves raw session messages when a previous tool call is pending", async () => { const workspace = createTempDir("deepcode-pending-tool-workspace-"); const home = createTempDir("deepcode-pending-tool-home-"); diff --git a/src/tests/slashCommands.test.ts b/src/tests/slashCommands.test.ts index 45b6fdf..bba5244 100644 --- a/src/tests/slashCommands.test.ts +++ b/src/tests/slashCommands.test.ts @@ -19,7 +19,7 @@ test("buildSlashCommands prefixes skills before built-ins", () => { assert.equal(items[0].kind, "skill"); assert.equal(items[0].name, "skill-writer"); const builtinNames = items.filter((i) => i.kind !== "skill").map((i) => i.name); - assert.deepEqual(builtinNames, ["skills", "model", "new", "init", "resume", "mcp", "exit"]); + assert.deepEqual(builtinNames, ["skills", "model", "new", "init", "resume", "continue", "mcp", "exit"]); }); test("filterSlashCommands matches partial prefixes", () => { @@ -59,6 +59,13 @@ test("findExactSlashCommand returns built-in /init", () => { assert.equal(item?.description, "Initialize an AGENTS.md file with instructions for LLM"); }); +test("findExactSlashCommand returns built-in /continue", () => { + const items = buildSlashCommands(skills); + const item = findExactSlashCommand(items, "/continue"); + assert.ok(item); + assert.equal(item?.kind, "continue"); +}); + test("findExactSlashCommand returns built-in /skills", () => { const items = buildSlashCommands(skills); const item = findExactSlashCommand(items, "/skills"); diff --git a/src/tests/tool-handlers.test.ts b/src/tests/tool-handlers.test.ts index 43af7ca..7f371be 100644 --- a/src/tests/tool-handlers.test.ts +++ b/src/tests/tool-handlers.test.ts @@ -356,6 +356,80 @@ test("Edit accepts a unique loose-escape match when only escaping differs", asyn assert.equal(fs.readFileSync(filePath, "utf8"), "params['city_json'] = city\n"); }); +test("Edit accepts a unique loose-escape match for over-escaped unicode sequences", async () => { + const workspace = createTempWorkspace(); + const filePath = path.join(workspace, "keys.ts"); + fs.writeFileSync(filePath, 'const sequence = "\\u001B[13;2~";\n', "utf8"); + + const sessionId = "unicode-loose-escape"; + await handleReadTool({ file_path: filePath }, createContext(sessionId, workspace)); + + let llmCalls = 0; + const editResult = await handleEditTool( + { + file_path: filePath, + old_string: 'const sequence = "\\\\u001B[13;2~";', + new_string: 'const sequence = "\\\\u001B[13;130u";', + }, + createContext(sessionId, workspace, { + createOpenAIClient: () => ({ + client: { + chat: { + completions: { + create: async (request: { messages?: Array<{ content?: string }> }) => { + llmCalls += 1; + assert.match(String(request.messages?.[1]?.content ?? ""), /" + + '' + + '' + + "", + }, + }, + ], + }; + }, + }, + }, + } as any, + model: "test-model", + thinkingEnabled: false, + }), + }) + ); + + assert.equal(editResult.ok, true); + assert.equal(llmCalls, 1); + assert.equal(editResult.metadata?.matched_via, "llm_escape_correction"); + assert.equal(fs.readFileSync(filePath, "utf8"), 'const sequence = "\\u001B[13;130u";\n'); +}); + +test("Edit strips accidental read-result tabs after newlines when that creates a unique match", async () => { + const workspace = createTempWorkspace(); + const filePath = path.join(workspace, "tabs.ts"); + fs.writeFileSync(filePath, ["function demo() {", " return 1;", "}"].join("\n") + "\n", "utf8"); + + const sessionId = "line-leading-tab-correction"; + await handleReadTool({ file_path: filePath }, createContext(sessionId, workspace)); + + const editResult = await handleEditTool( + { + file_path: filePath, + old_string: "function demo() {\n\t return 1;\n\t}", + new_string: "function demo() {\n\t return 2;\n\t}", + }, + createContext(sessionId, workspace) + ); + + assert.equal(editResult.ok, true); + assert.equal(editResult.metadata?.matched_via, "line_leading_tab_correction"); + assert.equal(fs.readFileSync(filePath, "utf8"), ["function demo() {", " return 2;", "}"].join("\n") + "\n"); +}); + test("Write repairs JSON object content for .json files", async () => { const workspace = createTempWorkspace(); const filePath = path.join(workspace, "package.json"); diff --git a/src/tools/edit-handler.ts b/src/tools/edit-handler.ts index 5aaede8..29108e5 100644 --- a/src/tools/edit-handler.ts +++ b/src/tools/edit-handler.ts @@ -213,10 +213,23 @@ export async function handleEditTool( const lineIndex = buildLineIndex(raw); const scope = buildSearchScope(filePath, raw, lineIndex, snippet ?? null); let matches = findOccurrences(raw, oldString, scope); - let matchedVia: "exact" | "loose_escape" | "llm_escape_correction" = "exact"; + let matchedVia: "exact" | "line_leading_tab_correction" | "loose_escape" | "llm_escape_correction" = "exact"; let replacementOldString = oldString; let replacementNewString = newString; + if (matches.length === 0) { + const tabStrippedOldString = stripReadResultLineTabs(oldString); + if (tabStrippedOldString !== oldString) { + const tabStrippedMatches = findOccurrences(raw, tabStrippedOldString, scope); + if (tabStrippedMatches.length === 1) { + matches = tabStrippedMatches; + matchedVia = "line_leading_tab_correction"; + replacementOldString = tabStrippedOldString; + replacementNewString = stripReadResultLineTabs(newString); + } + } + } + if (matches.length === 0) { const looseEscapeMatches = findLooseEscapeMatches(raw, oldString, scope); if (looseEscapeMatches.length === 1 && looseEscapeMatches[0]?.score === 1) { @@ -545,6 +558,10 @@ function applyReplacement( return result; } +function stripReadResultLineTabs(value: string): string { + return value.replaceAll("\n\t", "\n"); +} + function buildCandidateMetadata( sessionId: string, filePath: string, @@ -691,7 +708,7 @@ function buildLooseEscapeRegex(source: string): RegExp | null { slashEnd += 1; } - if (slashEnd < source.length && isEscapeSensitiveChar(source[slashEnd])) { + if (slashEnd < source.length) { pattern += "\\\\*"; pattern += escapeRegExp(source[slashEnd]); index = slashEnd; @@ -807,10 +824,6 @@ function parseCorrectedEditStrings(content: string): CorrectedEditStrings | null return null; } -function isEscapeSensitiveChar(value: string): boolean { - return value === '"' || value === "'" || value === "`" || value === "\\"; -} - function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 8c5c375..bafb412 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -190,6 +190,12 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R setView("session-list"); return; } + if (submission.command === "continue" && isCurrentSessionEmpty(sessionManager)) { + setShowWelcome(false); + refreshSessionsList(); + setView("session-list"); + return; + } if (submission.command === "mcp") { setShowWelcome(false); setMcpStatuses(sessionManager.getMcpStatus()); @@ -211,7 +217,7 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R (selectedSkillNames.length > 0 ? `Use skills: ${selectedSkillNames.join(", ")}` : "") || (submission.imageUrls.length > 0 ? "[Image]" : ""); - if (userDisplayContent) { + if (userDisplayContent && submission.command !== "continue") { setMessages((prev) => [...prev, buildSyntheticUserMessage(userDisplayContent, submission.imageUrls.length)]); } @@ -506,6 +512,11 @@ function buildSyntheticUserMessage(content: string, imageCount: number): Session }; } +function isCurrentSessionEmpty(sessionManager: SessionManager): boolean { + const activeSessionId = sessionManager.getActiveSessionId(); + return !activeSessionId || !sessionManager.getSession(activeSessionId); +} + function buildStatusLine(entry: SessionEntry): string { const parts: string[] = []; parts.push(`status: ${entry.status}`); diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 3965144..b32d926 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -48,7 +48,7 @@ export type PromptSubmission = { text: string; imageUrls: string[]; selectedSkills?: SkillInfo[]; - command?: "new" | "resume" | "mcp" | "exit"; + command?: "new" | "resume" | "continue" | "mcp" | "exit"; }; type Props = { @@ -619,6 +619,15 @@ export const PromptInput = React.memo(function PromptInput({ setShowSkillsDropdown(false); return; } + if (item.kind === "continue") { + onSubmit({ text: "/continue", imageUrls: [], command: "continue" }); + setBuffer(EMPTY_BUFFER); + clearUndoRedoStacks(); + setImageUrls([]); + setSelectedSkills([]); + setShowSkillsDropdown(false); + return; + } if (item.kind === "mcp") { onSubmit({ text: "/mcp", imageUrls: [], command: "mcp" }); setBuffer(EMPTY_BUFFER); diff --git a/src/ui/slashCommands.ts b/src/ui/slashCommands.ts index 16a76ac..6552ba0 100644 --- a/src/ui/slashCommands.ts +++ b/src/ui/slashCommands.ts @@ -1,6 +1,6 @@ import type { SkillInfo } from "../session"; -export type SlashCommandKind = "skill" | "skills" | "model" | "new" | "init" | "resume" | "mcp" | "exit"; +export type SlashCommandKind = "skill" | "skills" | "model" | "new" | "init" | "resume" | "continue" | "mcp" | "exit"; export type SlashCommandItem = { kind: SlashCommandKind; @@ -41,6 +41,12 @@ export const BUILTIN_SLASH_COMMANDS: SlashCommandItem[] = [ label: "/resume", description: "Pick a previous conversation to continue", }, + { + kind: "continue", + name: "continue", + label: "/continue", + description: "Continue the active conversation or pick one to resume", + }, { kind: "mcp", name: "mcp", From ccaa6dd073e25bbdb61dd74192a9889d5d036c1c Mon Sep 17 00:00:00 2001 From: Yanwu Date: Sat, 16 May 2026 17:58:18 +0200 Subject: [PATCH 037/129] feat: add -p/--prompt flag to auto-submit prompt on launch Adds CLI argument -p / --prompt that takes a prompt string and auto-submits it immediately when deepcode starts. Usage: deepcode -p 'write a Python script' deepcode --prompt 'write a Python script' --- src/cli.tsx | 24 ++++++++++++++++++++---- src/ui/App.tsx | 4 +++- src/ui/PromptInput.tsx | 19 ++++++++++++++++++- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/cli.tsx b/src/cli.tsx index a0847d4..5f5ccb2 100644 --- a/src/cli.tsx +++ b/src/cli.tsx @@ -18,9 +18,11 @@ if (args.includes("--help") || args.includes("-h")) { "deepcode - Deep Code CLI", "", "Usage:", - " deepcode Launch the interactive TUI in the current directory", - " deepcode --version Print the version", - " deepcode --help Show this help", + " deepcode Launch the interactive TUI in the current directory", + " deepcode -p Launch with a pre-filled prompt", + " deepcode --prompt Same as -p", + " deepcode --version Print the version", + " deepcode --help Show this help", "", "Configuration:", " ~/.deepcode/settings.json User-level API key, model, base URL", @@ -50,6 +52,15 @@ if (args.includes("--help") || args.includes("-h")) { process.exit(0); } +function extractInitialPrompt(args: string[]): string | undefined { + const promptIndex = args.findIndex((arg) => arg === "-p" || arg === "--prompt"); + if (promptIndex !== -1 && promptIndex + 1 < args.length) { + return args[promptIndex + 1]; + } + return undefined; +} + +const initialPrompt = extractInitialPrompt(args); const projectRoot = process.cwd(); configureWindowsShell(); @@ -68,7 +79,12 @@ async function main(): Promise { function startApp(): void { let restarting = false; const inkInstance = render( - restartRef.current?.()} />, + restartRef.current?.()} + />, { exitOnCtrlC: false } ); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index bafb412..1b60618 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -45,10 +45,11 @@ type View = "chat" | "session-list" | "mcp-status"; type AppProps = { projectRoot: string; version?: string; + initialPrompt?: string; onRestart?: () => void; }; -export function App({ projectRoot, version = "", onRestart }: AppProps): React.ReactElement { +export function App({ projectRoot, version = "", initialPrompt, onRestart }: AppProps): React.ReactElement { const { exit } = useApp(); const { stdout, write } = useStdout(); const { columns } = useWindowSize(); @@ -470,6 +471,7 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R promptHistory={promptHistory} busy={busy} loadingText={loadingText} + initialPrompt={initialPrompt} onSubmit={handleSubmit} onModelConfigChange={handleModelConfigChange} onInterrupt={handleInterrupt} diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index b32d926..353a827 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -60,6 +60,7 @@ type Props = { loadingText?: string | null; disabled?: boolean; placeholder?: string; + initialPrompt?: string; onSubmit: (submission: PromptSubmission) => void; onModelConfigChange: (selection: ModelConfigSelection) => string | Promise; onInterrupt: () => void; @@ -109,13 +110,16 @@ export const PromptInput = React.memo(function PromptInput({ loadingText, disabled, placeholder, + initialPrompt, onSubmit, onModelConfigChange, onInterrupt, }: Props): React.ReactElement { const { exit } = useApp(); const { stdout } = useStdout(); - const [buffer, setBuffer] = useState(EMPTY_BUFFER); + const [buffer, setBuffer] = useState(() => + initialPrompt ? { text: initialPrompt, cursor: initialPrompt.length } : EMPTY_BUFFER + ); const [imageUrls, setImageUrls] = useState([]); const [selectedSkills, setSelectedSkills] = useState([]); const [statusMessage, setStatusMessage] = useState(null); @@ -192,6 +196,19 @@ export const PromptInput = React.memo(function PromptInput({ setDraftBeforeHistory(null); }, [promptHistoryKey]); + // Auto-submit initial prompt provided via -p/--prompt CLI flag + useEffect(() => { + if (!initialPrompt || !initialPrompt.trim()) return; + + onSubmit({ + text: initialPrompt, + imageUrls: [], + selectedSkills: undefined, + }); + setBuffer(EMPTY_BUFFER); + clearPromptUndoRedoState(undoRedoRef.current); + }, []); // Only on mount + useTerminalInput( (input, key) => { if (key.focusIn) { From e87f022dd42ab08f5929162a2bd742495e2e01a6 Mon Sep 17 00:00:00 2001 From: dengm Date: Sat, 16 May 2026 18:22:28 +0800 Subject: [PATCH 038/129] feat: add manual MCP server reconnect with secondary menu Replace automatic retry with user-initiated reconnect: - Failed servers show error details and a [Reconnect] option - Reconnect reads latest config from disk (no restart needed) - Single attempt per reconnect, no backoff/retry --- src/mcp/mcp-client.ts | 34 ++++- src/mcp/mcp-manager.ts | 266 +++++++++++++++++++++++--------------- src/session.ts | 4 + src/tests/session.test.ts | 55 ++++++++ src/ui/App.tsx | 9 +- src/ui/McpStatusList.tsx | 129 ++++++++++++------ 6 files changed, 346 insertions(+), 151 deletions(-) diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts index 9636732..3651c88 100644 --- a/src/mcp/mcp-client.ts +++ b/src/mcp/mcp-client.ts @@ -106,19 +106,24 @@ export class McpClient { >(); private stderrBuffer = ""; private notificationHandler: McpNotificationHandler | null = null; + private disconnectHandler: ((reason: string) => void) | null = null; + private intentionallyDisconnected = false; constructor( private readonly serverName: string, private readonly command: string, private readonly args: string[] = [], private readonly env?: Record, - onNotification?: McpNotificationHandler + onNotification?: McpNotificationHandler, + onDisconnect?: (reason: string) => void ) { this.notificationHandler = onNotification ?? null; + this.disconnectHandler = onDisconnect ?? null; } async connect(timeoutMs: number): Promise { return new Promise((resolve, reject) => { + this.intentionallyDisconnected = false; const childEnv = { ...process.env, ...this.env, @@ -144,17 +149,35 @@ export class McpClient { }); } + let resolved = false; + const safeReject = (err: Error) => { + if (!resolved) { + resolved = true; + reject(err); + } + }; + this.process.on("error", (err) => { - reject(this.withStderr(`Failed to start MCP server "${this.serverName}" (${this.command}): ${err.message}`)); + safeReject( + this.withStderr(`Failed to start MCP server "${this.serverName}" (${this.command}): ${err.message}`) + ); }); this.process.on("close", (code) => { - const error = this.withStderr(`MCP server "${this.serverName}" exited with code ${code}`); + const reason = `MCP server "${this.serverName}" exited with code ${code}`; + const error = this.withStderr(reason); for (const [, pending] of this.pendingRequests) { clearTimeout(pending.timer); pending.reject(error); } this.pendingRequests.clear(); + this.reader?.close(); + this.reader = null; + this.process = null; + if (!this.intentionallyDisconnected && this.disconnectHandler) { + this.disconnectHandler(reason); + } + safeReject(error); }); if (this.process.stderr) { @@ -263,6 +286,7 @@ export class McpClient { } disconnect(): void { + this.intentionallyDisconnected = true; if (this.reader) { this.reader.close(); this.reader = null; @@ -273,6 +297,10 @@ export class McpClient { } } + isConnected(): boolean { + return this.process !== null && this.process.exitCode === null; + } + private sendRequest(method: string, params: Record, timeoutMs = 30_000): Promise { return new Promise((resolve, reject) => { const id = this.nextId++; diff --git a/src/mcp/mcp-manager.ts b/src/mcp/mcp-manager.ts index 5a9f553..217e3fc 100644 --- a/src/mcp/mcp-manager.ts +++ b/src/mcp/mcp-manager.ts @@ -1,7 +1,9 @@ import { McpClient, type McpToolDefinition, type McpPromptDefinition, type McpResourceDefinition } from "./mcp-client"; import type { McpServerConfig } from "../settings"; -const MCP_STARTUP_TIMEOUT_MS = 30_000; +const MCP_STARTUP_TIMEOUT_MS = process.env.DEEPCODE_MCP_TIMEOUT + ? parseInt(process.env.DEEPCODE_MCP_TIMEOUT, 10) + : 30_000; const MCP_CALL_TOOL_TIMEOUT_MS = 60_000; type McpToolEntry = { @@ -14,7 +16,7 @@ type McpToolEntry = { export type McpServerStatus = { name: string; - status: "starting" | "ready" | "failed"; + status: "starting" | "ready" | "failed" | "reconnecting"; connected: boolean; error?: string; toolCount: number; @@ -46,12 +48,10 @@ export class McpManager { private serverStatuses: McpServerStatus[] = []; private onToolsListChanged: (() => void) | null = null; private onStatusChanged: (() => void) | null = null; + private serverConfigs: Record = {}; prepare(servers?: Record): void { if (!servers || Object.keys(servers).length === 0) return; - // Clear the disposed flag — a re-prepare means we are live again. - // (disconnect() sets disposed=true to stop a stale initialize() loop, - // but prepare+initialize must be able to start a new one.) this.disposed = false; for (const name of Object.keys(servers)) { @@ -81,116 +81,175 @@ export class McpManager { if (!servers || Object.keys(servers).length === 0) return; - const entries = Object.entries(servers); + this.serverConfigs = servers; this.prepare(servers); - for (const [name, config] of entries) { + for (const [name, config] of Object.entries(servers)) { if (this.disposed) break; - let client: McpClient | null = null; - try { - client = new McpClient(name, config.command, config.args ?? [], config.env, (method) => { + await this.connectServer(name, config); + } + } + + async reconnect(name: string, config?: McpServerConfig): Promise { + if (this.disposed) return; + const effectiveConfig = config ?? this.serverConfigs[name]; + if (!effectiveConfig) return; + if (config) { + this.serverConfigs[name] = config; + } + + this.setStatus({ + name, + status: "reconnecting", + connected: false, + error: "Reconnecting...", + toolCount: 0, + tools: [], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], + }); + + await this.connectServer(name, effectiveConfig); + } + + private async connectServer(name: string, config: McpServerConfig): Promise { + if (this.disposed) return; + + // Clean up stale entries from previous connection attempts + this.clients = this.clients.filter((c) => c.isConnected()); + this.tools = this.tools.filter((t) => t.serverName !== name); + this.prompts = this.prompts.filter((p) => p.serverName !== name); + this.resources = this.resources.filter((r) => r.serverName !== name); + + let client: McpClient | null = null; + try { + client = new McpClient( + name, + config.command, + config.args ?? [], + config.env, + (method) => { if (method === "notifications/tools/list_changed") { - this.refreshServerTools(name, client!).catch(() => { - // swallow refresh errors - }); + this.refreshServerTools(name, client!).catch(() => {}); + } + }, + (reason) => { + if (!this.disposed && this.serverConfigs[name]) { + this.onServerCrash(name, reason); } - }); - await client.connect(MCP_STARTUP_TIMEOUT_MS); - if (this.disposed) { - client.disconnect(); - break; - } - this.clients.push(client); - - // Discover tools - const serverTools = await client.listTools(MCP_STARTUP_TIMEOUT_MS); - if (this.disposed) break; - const toolNamespacedNames: string[] = []; - for (const tool of serverTools) { - const namespacedName = `mcp__${name}__${tool.name}`; - this.tools.push({ - serverName: name, - originalName: tool.name, - namespacedName, - definition: tool, - client, - }); - toolNamespacedNames.push(namespacedName); - } - - // Discover prompts - let serverPrompts: McpPromptDefinition[] = []; - try { - serverPrompts = await client.listPrompts(MCP_STARTUP_TIMEOUT_MS); - } catch { - // Server may not support prompts — safe to ignore - } - if (this.disposed) break; - const promptNamespacedNames: string[] = []; - for (const prompt of serverPrompts) { - const namespacedName = `mcp__${name}__${prompt.name}`; - this.prompts.push({ - serverName: name, - namespacedName, - definition: prompt, - client, - }); - promptNamespacedNames.push(namespacedName); } + ); + await client.connect(MCP_STARTUP_TIMEOUT_MS); + if (this.disposed) { + client.disconnect(); + return; + } + this.clients.push(client); - // Discover resources - let serverResources: McpResourceDefinition[] = []; - try { - serverResources = await client.listResources(MCP_STARTUP_TIMEOUT_MS); - } catch { - // Server may not support resources — safe to ignore - } - if (this.disposed) break; - const resourceNamespacedNames: string[] = []; - for (const resource of serverResources) { - const namespacedName = `mcp__${name}__${resource.name}`; - this.resources.push({ - serverName: name, - namespacedName, - definition: resource, - client, - }); - resourceNamespacedNames.push(namespacedName); - } + const serverTools = await client.listTools(MCP_STARTUP_TIMEOUT_MS); + if (this.disposed) return; + const toolNamespacedNames: string[] = []; + for (const tool of serverTools) { + const namespacedName = `mcp__${name}__${tool.name}`; + this.tools.push({ + serverName: name, + originalName: tool.name, + namespacedName, + definition: tool, + client, + }); + toolNamespacedNames.push(namespacedName); + } - this.setStatus({ - name, - status: "ready", - connected: true, - toolCount: serverTools.length, - tools: toolNamespacedNames, - promptCount: serverPrompts.length, - prompts: promptNamespacedNames, - resourceCount: serverResources.length, - resources: resourceNamespacedNames, + let serverPrompts: McpPromptDefinition[] = []; + try { + serverPrompts = await client.listPrompts(MCP_STARTUP_TIMEOUT_MS); + } catch { + // server may not support prompts + } + if (this.disposed) return; + const promptNamespacedNames: string[] = []; + for (const prompt of serverPrompts) { + const namespacedName = `mcp__${name}__${prompt.name}`; + this.prompts.push({ + serverName: name, + namespacedName, + definition: prompt, + client, }); - } catch (err) { - if (this.disposed) break; - client?.disconnect(); - const message = err instanceof Error ? err.message : String(err); - // 不在控制台输出错误日志,避免暴露敏感信息 - // process.stderr.write(`[deepcode] MCP server "${name}" failed to initialize: ${message}\n`); - this.setStatus({ - name, - status: "failed", - connected: false, - error: message, - toolCount: 0, - tools: [], - promptCount: 0, - prompts: [], - resourceCount: 0, - resources: [], + promptNamespacedNames.push(namespacedName); + } + + let serverResources: McpResourceDefinition[] = []; + try { + serverResources = await client.listResources(MCP_STARTUP_TIMEOUT_MS); + } catch { + // server may not support resources + } + if (this.disposed) return; + const resourceNamespacedNames: string[] = []; + for (const resource of serverResources) { + const namespacedName = `mcp__${name}__${resource.name}`; + this.resources.push({ + serverName: name, + namespacedName, + definition: resource, + client, }); + resourceNamespacedNames.push(namespacedName); } + + this.setStatus({ + name, + status: "ready", + connected: true, + toolCount: serverTools.length, + tools: toolNamespacedNames, + promptCount: serverPrompts.length, + prompts: promptNamespacedNames, + resourceCount: serverResources.length, + resources: resourceNamespacedNames, + }); + } catch (err) { + client?.disconnect(); + const message = err instanceof Error ? err.message : String(err); + this.setStatus({ + name, + status: "failed", + connected: false, + error: message, + toolCount: 0, + tools: [], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], + }); } } + private onServerCrash(name: string, reason: string): void { + if (this.disposed) return; + this.clients = this.clients.filter((c) => c.isConnected()); + this.tools = this.tools.filter((t) => t.serverName !== name); + this.prompts = this.prompts.filter((p) => p.serverName !== name); + this.resources = this.resources.filter((r) => r.serverName !== name); + this.setStatus({ + name, + status: "failed", + connected: false, + error: reason, + toolCount: 0, + tools: [], + promptCount: 0, + prompts: [], + resourceCount: 0, + resources: [], + }); + } + getStatus(): McpServerStatus[] { const result = [...this.serverStatuses]; const knownNames = new Set(result.map((s) => s.name)); @@ -345,12 +404,12 @@ export class McpManager { this.resources = []; this.serverStatuses = []; this.configuredServerNames = []; + this.serverConfigs = {}; this.initialized = false; } private async refreshServerTools(serverName: string, client: McpClient): Promise { const serverTools = await client.listTools(MCP_STARTUP_TIMEOUT_MS); - // Remove old tool entries for this server this.tools = this.tools.filter((t) => t.serverName !== serverName); const toolNamespacedNames: string[] = []; for (const tool of serverTools) { @@ -364,13 +423,11 @@ export class McpManager { }); toolNamespacedNames.push(namespacedName); } - // Update status const existing = this.serverStatuses.find((s) => s.name === serverName); if (existing) { existing.toolCount = serverTools.length; existing.tools = toolNamespacedNames; } - // Notify listener this.onToolsListChanged?.(); } @@ -390,7 +447,6 @@ export class McpManager { } else { this.serverStatuses[index] = status; } - // 触发状态变更回调 this.onStatusChanged?.(); } } diff --git a/src/session.ts b/src/session.ts index 095cd3a..9e97f86 100644 --- a/src/session.ts +++ b/src/session.ts @@ -255,6 +255,10 @@ export class SessionManager { return this.mcpManager.getStatus(); } + async reconnectMcpServer(name: string, config?: McpServerConfig): Promise { + await this.mcpManager.reconnect(name, config); + } + dispose(): void { this.mcpManager.disconnect(); } diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 50d016c..8ecb85e 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1540,6 +1540,61 @@ test("SessionManager treats OpenAI APIUserAbortError as interrupted", async () = assert.equal(session?.failReason, "interrupted"); }); +test("SessionManager marks MCP server as failed on single failed attempt (no auto-retry)", async () => { + const workspace = createTempDir("deepcode-mcp-fail-noworkspace-"); + const serverPath = path.join(workspace, "mcp-server-fail.cjs"); + fs.writeFileSync(serverPath, "process.exit(7);", "utf8"); + + const manager = createSessionManager(workspace, "machine-id-mcp-fail-no"); + await manager.initMcpServers({ broken: { command: process.execPath, args: [serverPath] } }); + + const status = manager.getMcpStatus(); + assert.equal(status.length, 1); + assert.equal(status[0]?.status, "failed"); + assert.match(status[0]?.error ?? "", /exited with code 7/); + + manager.dispose(); +}); + +test("SessionManager reconnect succeeds on previously failed server", async () => { + const workspace = createTempDir("deepcode-mcp-reconn-ok-workspace-"); + const serverPath = path.join(workspace, "mcp-server-ok.cjs"); + fs.writeFileSync( + serverPath, + ` +const readline = require("readline"); +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +function send(message) { + process.stdout.write(JSON.stringify(message) + "\\n"); +} +rl.on("line", (line) => { + const request = JSON.parse(line); + if (!("id" in request)) return; + if (request.method === "initialize") { + send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2024-11-05", capabilities: {} } }); + return; + } + if (request.method === "tools/list") { + send({ jsonrpc: "2.0", id: request.id, result: { tools: [{ name: "ping", inputSchema: { type: "object", properties: {} } }] } }); + return; + } + send({ jsonrpc: "2.0", id: request.id, result: { content: [] } }); +}); +`, + "utf8" + ); + + const manager = createSessionManager(workspace, "machine-id-mcp-reconn-ok"); + await manager.initMcpServers({ fixable: { command: process.execPath, args: [serverPath] } }); + + const status = manager.getMcpStatus(); + assert.equal(status.length, 1); + assert.equal(status[0]?.status, "ready"); + assert.equal(status[0]?.toolCount, 1); + + manager.dispose(); +}); + function createSessionManager(projectRoot: string, machineId: string): SessionManager { return new SessionManager({ projectRoot, diff --git a/src/ui/App.tsx b/src/ui/App.tsx index bafb412..1f12198 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -455,7 +455,14 @@ export function App({ projectRoot, version = "", onRestart }: AppProps): React.R onCancel={() => setView("chat")} /> ) : view === "mcp-status" ? ( - setView("chat")} /> + setView("chat")} + onReconnect={(name) => { + const latest = resolveCurrentSettings(projectRoot); + void sessionManager.reconnectMcpServer(name, latest.mcpServers?.[name]); + }} + /> ) : shouldShowQuestionPrompt && pendingQuestion && !busy ? ( void; + onReconnect: (name: string) => void; }; -export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement { +export function McpStatusList({ statuses, onCancel, onReconnect }: Props): React.ReactElement { const { columns, rows } = useWindowSize(); // 视图模式:server-list(服务器列表) 或 server-detail(服务器详情) @@ -20,10 +21,10 @@ export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement setViewMode("server-list"); }, []); - // 进入服务器详情 + // 进入服务器详情(允许 ready、failed、reconnecting 状态) const enterDetail = useCallback(() => { const server = statuses[selectedServerIndex]; - if (server && server.status === "ready") { + if (server && (server.status === "ready" || server.status === "failed" || server.status === "reconnecting")) { setViewMode("server-detail"); } }, [statuses, selectedServerIndex]); @@ -59,6 +60,7 @@ export function McpStatusList({ statuses, onCancel }: Props): React.ReactElement server={statuses[selectedServerIndex]} onBack={goBack} onCancel={onCancel} + onReconnect={onReconnect} rows={rows} columns={columns} /> @@ -173,6 +175,7 @@ function ServerListView({ const readyCount = statuses.filter((s) => s.status === "ready").length; const startingCount = statuses.filter((s) => s.status === "starting").length; + const reconnectingCount = statuses.filter((s) => s.status === "reconnecting").length; const failedCount = statuses.filter((s) => s.status === "failed").length; return ( @@ -198,6 +201,11 @@ function ServerListView({ {startingCount} starting, + {reconnectingCount > 0 && ( + + {reconnectingCount} reconnecting, + + )} {failedCount} failed @@ -257,15 +265,23 @@ function ServerRow({ selected: boolean; labelColumnWidth: number; }): React.ReactElement { - const icon = status.status === "ready" ? "✓" : status.status === "failed" ? "✗" : "●"; - const color = status.status === "ready" ? "green" : status.status === "failed" ? "red" : "yellow"; + const icon = + status.status === "ready" ? "✓" : status.status === "failed" ? "✗" : status.status === "reconnecting" ? "↻" : "●"; + const color = + status.status === "ready" + ? "green" + : status.status === "failed" + ? "red" + : status.status === "reconnecting" + ? "#ff9900" + : "yellow"; // 加载动画:循环显示 (空) → . → .. → ... → (空) → ... const [dots, setDots] = React.useState(0); React.useEffect(() => { - if (status.status !== "starting") return; + if (status.status !== "starting" && status.status !== "reconnecting") return; const interval = setInterval(() => { - setDots((d) => (d + 1) % 4); // 0 → 1 → 2 → 3 → 0 ... + setDots((d) => (d + 1) % 4); }, 500); return () => clearInterval(interval); }, [status.status]); @@ -275,7 +291,9 @@ function ServerRow({ ? `Ready (${status.toolCount} tools, ${status.promptCount} prompts, ${status.resourceCount} resources)` : status.status === "failed" ? `Failed` - : "Starting" + (dots > 0 ? ".".repeat(dots) : " "); // 动态显示 (空) / . / .. / ... + : status.status === "reconnecting" + ? `Reconnecting${dots > 0 ? ".".repeat(dots) : " "}` + : "Starting" + (dots > 0 ? ".".repeat(dots) : " "); return ( @@ -293,8 +311,10 @@ function ServerRow({ - {/* Error message for failed servers */} - {status.status === "failed" && status.error ? : null} + {/* Error message for failed or reconnecting servers */} + {(status.status === "failed" || status.status === "reconnecting") && status.error ? ( + + ) : null} ); } @@ -304,59 +324,54 @@ function ServerDetailView({ server, onBack, onCancel, + onReconnect, rows, columns, }: { server: McpServerStatus; onBack: () => void; onCancel: () => void; + onReconnect: (name: string) => void; rows: number; columns: number; }): React.ReactElement { - const [activeIndex, setActiveIndex] = useState(0); + const [activeIndex, setActiveIndex] = React.useState(0); + const hasReconnect = server.status === "failed"; + const canScroll = server.status === "ready"; - // 合并所有 items(tools, prompts, resources) + // 合并所有 items(tools, prompts, resources)+ Reconnect 选项 const allItems = useMemo(() => { const items: { type: string; name: string }[] = []; + if (hasReconnect) { + items.push({ type: "action", name: "Reconnect" }); + } server.tools.forEach((tool) => items.push({ type: "tool", name: tool })); server.prompts.forEach((prompt) => items.push({ type: "prompt", name: prompt })); server.resources.forEach((resource) => items.push({ type: "resource", name: resource })); return items; - }, [server]); + }, [server, hasReconnect]); const totalItems = allItems.length; const maxVisible = useMemo(() => { - const reservedLines = 10; // header + title + stats + footer + borders + const reservedLines = 12; // header + title + stats + error + footer + borders const availableLines = Math.max(0, Math.min(rows, 30) - reservedLines); return Math.max(1, availableLines); }, [rows]); - // 使用 ref 跟踪 visibleStart,避免循环依赖 const visibleStartRef = React.useRef(0); - // 计算可见窗口起始位置:当 activeIndex 超出可见区域时才滚动(类似终端光标行为) const visibleStart = useMemo(() => { if (totalItems === 0) return 0; - const currentStart = visibleStartRef.current; let newStart = currentStart; - - // 如果 activeIndex 在当前可见窗口之前,滚动到 activeIndex if (activeIndex < currentStart) { newStart = activeIndex; - } - // 如果 activeIndex 在当前可见窗口之后,滚动到 activeIndex - else if (activeIndex >= currentStart + maxVisible) { + } else if (activeIndex >= currentStart + maxVisible) { newStart = activeIndex - maxVisible + 1; } - - // 限制在合法范围内 newStart = Math.max(0, Math.min(newStart, Math.max(0, totalItems - maxVisible))); - - // 更新 ref visibleStartRef.current = newStart; - return newStart; }, [activeIndex, maxVisible, totalItems]); @@ -371,11 +386,16 @@ function ServerDetailView({ onBack(); return; } - // Space 或 Enter 键返回一级菜单 - if (input === " " || key.return) { + if (key.return || input === " ") { + if (activeIndex === 0 && hasReconnect) { + onReconnect(server.name); + onBack(); + return; + } onBack(); return; } + if (!canScroll && !hasReconnect) return; if (key.upArrow) { setActiveIndex((prev) => Math.max(0, prev - 1)); return; @@ -384,25 +404,33 @@ function ServerDetailView({ setActiveIndex((prev) => Math.min(totalItems - 1, prev + 1)); return; } - if (key.pageUp) { + if (key.pageUp && canScroll) { setActiveIndex((prev) => Math.max(0, prev - maxVisible)); return; } - if (key.pageDown) { + if (key.pageDown && canScroll) { setActiveIndex((prev) => Math.min(totalItems - 1, prev + maxVisible)); return; } - if (key.home) { + if (key.home && canScroll) { setActiveIndex(0); return; } - if (key.end) { + if (key.end && canScroll) { setActiveIndex(totalItems - 1); } }); - const icon = "✓"; - const color = "green"; + const statusIcon = + server.status === "ready" ? "✓" : server.status === "failed" ? "✗" : server.status === "reconnecting" ? "↻" : "●"; + const statusColor = + server.status === "ready" + ? "green" + : server.status === "failed" + ? "red" + : server.status === "reconnecting" + ? "#ff9900" + : "yellow"; return ( {/* Header row */} - {icon} + {statusIcon} {server.name} - — Details + — {server.status === "ready" ? "Details" : "Status"} {/* Server info */} - {server.toolCount} tools, {server.promptCount} prompts, {server.resourceCount} resources + {server.status === "ready" + ? `${server.toolCount} tools, ${server.promptCount} prompts, ${server.resourceCount} resources` + : `Status: ${server.status}`} + {/* Error for failed/reconnecting */} + {server.error && (server.status === "failed" || server.status === "reconnecting") ? ( + + + + ) : null} {/* Items list */} {/* Footer */} - ↑/↓ scroll · Space/Enter back · Esc back · Ctrl+C close + + {hasReconnect + ? "Enter to reconnect · Esc back · Ctrl+C close" + : canScroll + ? "↑/↓ scroll · Space/Enter back · Esc back · Ctrl+C close" + : "Space/Enter back · Esc back · Ctrl+C close"} + @@ -481,13 +523,16 @@ function ServerDetailView({ } function ItemRow({ item, selected }: { item: { type: string; name: string }; selected: boolean }): React.ReactElement { - const icon = item.type === "tool" ? "🔧" : item.type === "prompt" ? "📝" : "📦"; + const isAction = item.type === "action"; + const icon = isAction ? "↻" : item.type === "tool" ? "🔧" : item.type === "prompt" ? "📝" : "📦"; + const color = isAction && selected ? "#ff9900" : selected ? "#229ac3" : undefined; return ( + {selected ? "> " : " "} {icon} - - {item.name} + + {isAction ? `[${item.name}]` : item.name} ); From 2b509715fec54287cbc872c078e09ebb8985c2ad Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Sun, 17 May 2026 10:31:18 +0800 Subject: [PATCH 039/129] fix: the -p/--prompt option causes duplicated LLM calls when using /new. --- src/cli.tsx | 6 ++++-- src/session.ts | 19 +++++++------------ src/tests/session.test.ts | 26 ++++++++++++++++++++++++++ src/ui/App.tsx | 15 ++++++++++++++- src/ui/PromptInput.tsx | 19 +------------------ 5 files changed, 52 insertions(+), 33 deletions(-) diff --git a/src/cli.tsx b/src/cli.tsx index 5f5ccb2..435499a 100644 --- a/src/cli.tsx +++ b/src/cli.tsx @@ -60,7 +60,7 @@ function extractInitialPrompt(args: string[]): string | undefined { return undefined; } -const initialPrompt = extractInitialPrompt(args); +let initialPrompt = extractInitialPrompt(args); const projectRoot = process.cwd(); configureWindowsShell(); @@ -78,11 +78,13 @@ async function main(): Promise { function startApp(): void { let restarting = false; + const appInitialPrompt = initialPrompt; + initialPrompt = undefined; const inkInstance = render( restartRef.current?.()} />, { exitOnCtrlC: false } diff --git a/src/session.ts b/src/session.ts index 095cd3a..5d6ee26 100644 --- a/src/session.ts +++ b/src/session.ts @@ -18,6 +18,7 @@ import { logOpenAIChatCompletionDebug, normalizeDebugError } from "./common/debu const MAX_SESSION_ENTRIES = 50; const DEFAULT_NEW_PROMPT_API_URL = "https://deepcode.vegamo.cn/api/plugin/new"; +const NEW_PROMPT_REPORT_TIMEOUT_MS = 3000; const DEFAULT_COMPACT_PROMPT_TOKEN_THRESHOLD = 128 * 1024; const DEEPSEEK_V4_COMPACT_PROMPT_TOKEN_THRESHOLD = 512 * 1024; @@ -1305,6 +1306,9 @@ ${skillMd} return; } + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), NEW_PROMPT_REPORT_TIMEOUT_MS); + void fetch(DEFAULT_NEW_PROMPT_API_URL, { method: "POST", headers: { @@ -1312,19 +1316,10 @@ ${skillMd} Token: machineId, }, body: JSON.stringify({}), + signal: controller.signal, }) - .then(async (response) => { - if (response.ok) { - return; - } - - const body = await response.text().catch(() => ""); - throw new Error(`New prompt API request failed with status ${response.status}${body ? `: ${body}` : ""}`); - }) - .catch((error) => { - const message = error instanceof Error ? error.message : String(error); - console.warn(`Failed to report new prompt: ${message}`); - }); + .catch(() => {}) + .finally(() => clearTimeout(timeout)); } interruptActiveSession(): void { diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 50d016c..e5ab740 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -6,6 +6,7 @@ import * as path from "path"; import { SessionManager, type SessionMessage } from "../session"; const originalFetch = globalThis.fetch; +const originalConsoleWarn = console.warn; const originalHome = process.env.HOME; const originalUserProfile = process.env.USERPROFILE; const tempDirs: string[] = []; @@ -20,6 +21,7 @@ function setHomeDir(dir: string): void { afterEach(() => { globalThis.fetch = originalFetch; + console.warn = originalConsoleWarn; if (originalHome === undefined) { delete process.env.HOME; } else { @@ -688,6 +690,7 @@ test("createSession reports a new prompt with the machineId token", async () => assert.equal(fetchCalls.length, 1); assert.equal(String(fetchCalls[0].input), "https://deepcode.vegamo.cn/api/plugin/new"); assert.equal(fetchCalls[0].init?.method, "POST"); + assert.ok(fetchCalls[0].init?.signal instanceof AbortSignal); assert.deepEqual(JSON.parse(String(fetchCalls[0].init?.body)), {}); assert.equal((fetchCalls[0].init?.headers as Record).Token, "machine-id-123"); }); @@ -719,10 +722,33 @@ test("replySession reports a new prompt with the machineId token", async () => { assert.equal(fetchCalls.length, 1); assert.equal(String(fetchCalls[0].input), "https://deepcode.vegamo.cn/api/plugin/new"); assert.equal(fetchCalls[0].init?.method, "POST"); + assert.ok(fetchCalls[0].init?.signal instanceof AbortSignal); assert.deepEqual(JSON.parse(String(fetchCalls[0].init?.body)), {}); assert.equal((fetchCalls[0].init?.headers as Record).Token, "machine-id-456"); }); +test("reporting a new prompt does not warn when the background request fails", async () => { + const workspace = createTempDir("deepcode-report-failure-workspace-"); + const home = createTempDir("deepcode-report-failure-home-"); + setHomeDir(home); + + const warnings: unknown[][] = []; + console.warn = (...args: unknown[]) => { + warnings.push(args); + }; + globalThis.fetch = (async () => { + throw new Error("fetch failed"); + }) as typeof fetch; + + const manager = createSessionManager(workspace, "machine-id-failure"); + (manager as any).activateSession = async () => {}; + + await manager.createSession({ text: "hello world" }); + await flushPromises(); + + assert.deepEqual(warnings, []); +}); + test("replySession continues without appending /continue as a user message", async () => { const workspace = createTempDir("deepcode-continue-workspace-"); const home = createTempDir("deepcode-continue-home-"); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 1b60618..b416647 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -53,6 +53,7 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App const { exit } = useApp(); const { stdout, write } = useStdout(); const { columns } = useWindowSize(); + const initialPromptSubmittedRef = useRef(false); const [view, setView] = useState("chat"); const [busy, setBusy] = useState(false); const [skills, setSkills] = useState([]); @@ -296,6 +297,19 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App [handlePrompt] ); + useEffect(() => { + if (initialPromptSubmittedRef.current || !initialPrompt || !initialPrompt.trim()) { + return; + } + + initialPromptSubmittedRef.current = true; + handleSubmit({ + text: initialPrompt, + imageUrls: [], + selectedSkills: undefined, + }); + }, [handleSubmit, initialPrompt]); + const handleSelectSession = useCallback( async (sessionId: string) => { const currentSessionId = sessionManager.getActiveSessionId(); @@ -471,7 +485,6 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App promptHistory={promptHistory} busy={busy} loadingText={loadingText} - initialPrompt={initialPrompt} onSubmit={handleSubmit} onModelConfigChange={handleModelConfigChange} onInterrupt={handleInterrupt} diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 353a827..b32d926 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -60,7 +60,6 @@ type Props = { loadingText?: string | null; disabled?: boolean; placeholder?: string; - initialPrompt?: string; onSubmit: (submission: PromptSubmission) => void; onModelConfigChange: (selection: ModelConfigSelection) => string | Promise; onInterrupt: () => void; @@ -110,16 +109,13 @@ export const PromptInput = React.memo(function PromptInput({ loadingText, disabled, placeholder, - initialPrompt, onSubmit, onModelConfigChange, onInterrupt, }: Props): React.ReactElement { const { exit } = useApp(); const { stdout } = useStdout(); - const [buffer, setBuffer] = useState(() => - initialPrompt ? { text: initialPrompt, cursor: initialPrompt.length } : EMPTY_BUFFER - ); + const [buffer, setBuffer] = useState(EMPTY_BUFFER); const [imageUrls, setImageUrls] = useState([]); const [selectedSkills, setSelectedSkills] = useState([]); const [statusMessage, setStatusMessage] = useState(null); @@ -196,19 +192,6 @@ export const PromptInput = React.memo(function PromptInput({ setDraftBeforeHistory(null); }, [promptHistoryKey]); - // Auto-submit initial prompt provided via -p/--prompt CLI flag - useEffect(() => { - if (!initialPrompt || !initialPrompt.trim()) return; - - onSubmit({ - text: initialPrompt, - imageUrls: [], - selectedSkills: undefined, - }); - setBuffer(EMPTY_BUFFER); - clearPromptUndoRedoState(undoRedoRef.current); - }, []); // Only on mount - useTerminalInput( (input, key) => { if (key.focusIn) { From 65caf610b535b6a230ba9c58ac0ec5cc6b4ca7f0 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Sun, 17 May 2026 12:57:24 +0800 Subject: [PATCH 040/129] feat: add test for Bash tool output streaming before command completion --- package-lock.json | 814 ++++++++++++++++++++++++++------ src/tests/tool-handlers.test.ts | 43 ++ 2 files changed, 704 insertions(+), 153 deletions(-) diff --git a/package-lock.json b/package-lock.json index f9caecd..958eed7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -846,6 +846,13 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@eslint/eslintrc/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, "node_modules/@eslint/eslintrc/node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmmirror.com/ignore/-/ignore-5.3.2.tgz", @@ -856,6 +863,19 @@ "node": ">= 4" } }, + "node_modules/@eslint/eslintrc/node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/@eslint/js": { "version": "9.39.4", "resolved": "https://registry.npmmirror.com/@eslint/js/-/js-9.39.4.tgz", @@ -1040,13 +1060,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "25.8.0", - "resolved": "https://registry.npmmirror.com/@types/node/-/node-25.8.0.tgz", - "integrity": "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ==", + "version": "25.6.0", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-25.6.0.tgz", + "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": ">=7.24.0 <7.24.7" + "undici-types": "~7.19.0" } }, "node_modules/@types/react": { @@ -1066,17 +1086,17 @@ "license": "MIT" }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.3.tgz", - "integrity": "sha512-PwFvSKsXGShKGW6n5bZOhGHEcCZXM8HofLK9fNsEwZXzFRjoY+XT1Vsf1zgyXdwTr0ZYz1/2tkZ0DBTT9jZjhw==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.2.tgz", + "integrity": "sha512-j/bwmkBvHUtPNxzuWe5z6BEk3q54YRyGlBXkSsmfoih7zNrBvl5A9A98anlp/7JbyZcWIJ8KXo/3Tq/DjFLtuQ==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.59.3", - "@typescript-eslint/type-utils": "8.59.3", - "@typescript-eslint/utils": "8.59.3", - "@typescript-eslint/visitor-keys": "8.59.3", + "@typescript-eslint/scope-manager": "8.59.2", + "@typescript-eslint/type-utils": "8.59.2", + "@typescript-eslint/utils": "8.59.2", + "@typescript-eslint/visitor-keys": "8.59.2", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" @@ -1089,22 +1109,22 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.59.3", + "@typescript-eslint/parser": "^8.59.2", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "node_modules/@typescript-eslint/parser": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-8.59.3.tgz", - "integrity": "sha512-HPwA+hVkfcriajbNvTmZv4VRauibay+cWArYUYq7u7W7PmGShMxbPxLvrwDme55a6d5alG3nrYfhyJ/G28XlLg==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-8.59.2.tgz", + "integrity": "sha512-plR3pp6D+SSUn1HM7xvSkx12/DhoHInI2YF35KAcVFNZvlC0gtrWqx7Qq1oH2Ssgi0vlFRCTbP+DZc7B9+TtsQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.59.3", - "@typescript-eslint/types": "8.59.3", - "@typescript-eslint/typescript-estree": "8.59.3", - "@typescript-eslint/visitor-keys": "8.59.3", + "@typescript-eslint/scope-manager": "8.59.2", + "@typescript-eslint/types": "8.59.2", + "@typescript-eslint/typescript-estree": "8.59.2", + "@typescript-eslint/visitor-keys": "8.59.2", "debug": "^4.4.3" }, "engines": { @@ -1120,14 +1140,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/project-service/-/project-service-8.59.3.tgz", - "integrity": "sha512-ECiUWa/KYRGDFUqTNehaRgzDshnJfkTABJxVemHk4ko22gcr0ukloKjWvyQ64g8YCV/UI47kN1dbmjf/GaQYng==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/project-service/-/project-service-8.59.2.tgz", + "integrity": "sha512-+2hqvEkeyf/0FBor67duF0Ll7Ot8jyKzDQOSrxazF/danillRq2DwR9dLptsXpoZQqxE1UisSmoZewrlPas9Vw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.59.3", - "@typescript-eslint/types": "^8.59.3", + "@typescript-eslint/tsconfig-utils": "^8.59.2", + "@typescript-eslint/types": "^8.59.2", "debug": "^4.4.3" }, "engines": { @@ -1142,14 +1162,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-8.59.3.tgz", - "integrity": "sha512-t2LvZnoEfzKtnPjgeEu41xw5gxq9mQVfYy4OoZ4Vlt0sk3JwxmhCca/AR7DwOiHrjWgjAj6as4AhRLKSDfvZIA==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-8.59.2.tgz", + "integrity": "sha512-JzfyEpEtOU89CcFSwyNS3mu4MLvLSXqnmX05+aKBDM+TdR5jzcGOEBwxwGNxrEQ7p/z6kK2WyioCGBf2zZBnvg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.59.3", - "@typescript-eslint/visitor-keys": "8.59.3" + "@typescript-eslint/types": "8.59.2", + "@typescript-eslint/visitor-keys": "8.59.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1160,9 +1180,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.59.3.tgz", - "integrity": "sha512-PcIJHjmaREXLgIAIzLnSY9VucEzz8FKXsRgFa1DmdGCK/5tJpW03TKJF01Q6VZd1lLdz2sIKPWaDUZN9dp//dw==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.59.2.tgz", + "integrity": "sha512-BKK4alN7oi4C/zv4VqHQ+uRU+lTa6JGIZ7s1juw7b3RHo9OfKB+bKX3u0iVZetdsUCBBkSbdWbarJbmN0fTeSw==", "dev": true, "license": "MIT", "engines": { @@ -1177,15 +1197,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/type-utils/-/type-utils-8.59.3.tgz", - "integrity": "sha512-g71d8QD8UaiHGvrJwyIS1hCX5r63w6Jll+4VEYhEAHXTDIqX1JgxhTAbEHtKntL9kuc4jRo7/GWw5xfCepSccQ==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/type-utils/-/type-utils-8.59.2.tgz", + "integrity": "sha512-nhqaj1nmTdVVl/BP5omXNRGO38jn5iosis2vbdmupF2txCf8ylWT8lx+JlvMYYVqzGVKtjojUFoQ3JRWK+mfzQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.59.3", - "@typescript-eslint/typescript-estree": "8.59.3", - "@typescript-eslint/utils": "8.59.3", + "@typescript-eslint/types": "8.59.2", + "@typescript-eslint/typescript-estree": "8.59.2", + "@typescript-eslint/utils": "8.59.2", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, @@ -1202,9 +1222,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/types/-/types-8.59.3.tgz", - "integrity": "sha512-ePFoH0g4ludssdRFqqDxQePCxU4WQyRa9+XVwjm7yLn0FKhMeoetC+qBEEI1Eyb1pGSDveTIT09Bvw2WhlGayg==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/types/-/types-8.59.2.tgz", + "integrity": "sha512-e82GVOE8Ps3E++Egvb6Y3Dw0S10u8NkQ9KXmtRhCWJJ8kDhOJTvtMAWnFL16kB1583goCWXsr0NieKCZMs2/0Q==", "dev": true, "license": "MIT", "engines": { @@ -1216,16 +1236,16 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.59.3.tgz", - "integrity": "sha512-CbRjVRAf7Lr9Kr8RopKcbY45p2VfmmHrm0ygOCYFi7oU8q19m0Fs/6iHS7kNOmwpp+ob07ZVcAqlxUod9lYdmg==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.59.2.tgz", + "integrity": "sha512-o0XPGNwcWw+FIwStOWn+BwBuEmL6QXP0rsvAFg7ET1dey1Nr6Wb1ac8p5HEsK0ygO/6mUxlk+YWQD9xcb/nnXg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.59.3", - "@typescript-eslint/tsconfig-utils": "8.59.3", - "@typescript-eslint/types": "8.59.3", - "@typescript-eslint/visitor-keys": "8.59.3", + "@typescript-eslint/project-service": "8.59.2", + "@typescript-eslint/tsconfig-utils": "8.59.2", + "@typescript-eslint/types": "8.59.2", + "@typescript-eslint/visitor-keys": "8.59.2", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", @@ -1296,16 +1316,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/utils/-/utils-8.59.3.tgz", - "integrity": "sha512-JAvT14goBzRzzzZyqq3P9BLArIxTtQURUtFgQ/V7FO+eU+Gg6ES+5ymOPP1wRxXcxAYeivCk4uS3jCKWI1K8Zg==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/utils/-/utils-8.59.2.tgz", + "integrity": "sha512-Juw3EinkXqjaffxz6roowvV7GZT/kET5vSKKZT6upl5TXdWkLkYmNPXwDDL2Vkt2DPn0nODIS4egC/0AGxKo/Q==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.59.3", - "@typescript-eslint/types": "8.59.3", - "@typescript-eslint/typescript-estree": "8.59.3" + "@typescript-eslint/scope-manager": "8.59.2", + "@typescript-eslint/types": "8.59.2", + "@typescript-eslint/typescript-estree": "8.59.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1320,13 +1340,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.59.3.tgz", - "integrity": "sha512-f1UQF7ggd42YiwI5wGrRaPsa+P0CINBlrkLPmGfpq/u/I/oVtecoEIfFR9ag/oa1sLOsRNZ6xehf6qMZhQGBDg==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.59.2.tgz", + "integrity": "sha512-NwjLUnGy8/Zfx23fl50tRC8rYaYnM52xNRYFAXvmiil9yh1+K6aRVQMnzW6gQB/1DLgWt977lYQn7C+wtgXZiA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/types": "8.59.2", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -1430,11 +1450,13 @@ } }, "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" + "version": "1.0.10", + "resolved": "https://registry.npmmirror.com/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } }, "node_modules/auto-bind": { "version": "5.0.1", @@ -1703,7 +1725,7 @@ }, "node_modules/ejs": { "version": "5.0.2", - "resolved": "https://registry.npmmirror.com/ejs/-/ejs-5.0.2.tgz", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-5.0.2.tgz", "integrity": "sha512-IpbUaI/CAW86l3f+T8zN0iggSc0LmMZLcIW5eRVStLVNCoTXkE0YlncbbH50fp8Cl6zHIky0sW2uUbhBqGw0Jw==", "license": "Apache-2.0", "bin": { @@ -1714,9 +1736,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.356", - "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.5.356.tgz", - "integrity": "sha512-9NgFd7m5t5MCJ5rUSjJITUXAH9mEGlrlofnMf4YEr+pz6JlP7cWmTAH+JFmbPnaSW8koVTkuW7pacORWAnA5Yw==", + "version": "1.5.353", + "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.5.353.tgz", + "integrity": "sha512-kOrWphBi8TOZyiJZqsgqIle0lw+tzmnQK83pV9dZUd01Nm2POECSyFQMAuarzZdYqQW7FH9RaYOuaRo3h+bQ3w==", "dev": true, "license": "ISC" }, @@ -1802,16 +1824,12 @@ } }, "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", "license": "MIT", "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=8" } }, "node_modules/eslint": { @@ -1973,6 +1991,19 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/eslint/node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/eslint/node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmmirror.com/ignore/-/ignore-5.3.2.tgz", @@ -2195,9 +2226,9 @@ } }, "node_modules/get-east-asian-width": { - "version": "1.6.0", - "resolved": "https://registry.npmmirror.com/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", - "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "version": "1.5.0", + "resolved": "https://registry.npmmirror.com/get-east-asian-width/-/get-east-asian-width-1.5.0.tgz", + "integrity": "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==", "license": "MIT", "engines": { "node": ">=18" @@ -2206,9 +2237,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/get-tsconfig": { + "version": "4.14.0", + "resolved": "https://registry.npmmirror.com/get-tsconfig/-/get-tsconfig-4.14.0.tgz", + "integrity": "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, "node_modules/glob": { "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "resolved": "https://registry.npmmirror.com/glob/-/glob-13.0.6.tgz", "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", "dev": true, "license": "BlueOak-1.0.0", @@ -2239,7 +2283,7 @@ }, "node_modules/glob/node_modules/balanced-match": { "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz", "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", "dev": true, "license": "MIT", @@ -2249,7 +2293,7 @@ }, "node_modules/glob/node_modules/brace-expansion": { "version": "5.0.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-5.0.6.tgz", "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", "dev": true, "license": "MIT", @@ -2262,7 +2306,7 @@ }, "node_modules/glob/node_modules/minimatch": { "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-10.2.5.tgz", "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", "dev": true, "license": "BlueOak-1.0.0", @@ -2317,28 +2361,6 @@ "node": ">=6.0" } }, - "node_modules/gray-matter/node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmmirror.com/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "license": "MIT", - "dependencies": { - "sprintf-js": "~1.0.2" - } - }, - "node_modules/gray-matter/node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", - "license": "MIT", - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz", @@ -2431,9 +2453,9 @@ } }, "node_modules/ink": { - "version": "7.0.3", - "resolved": "https://registry.npmmirror.com/ink/-/ink-7.0.3.tgz", - "integrity": "sha512-5kxHkIj9+RuqCU3zyvP4qvYWNOSHP2TW/SHayHGHOmk87KwfVcZwvJGemi9ch+ci2gXUqerK/Eh2DGEDt5q45g==", + "version": "7.0.1", + "resolved": "https://registry.npmmirror.com/ink/-/ink-7.0.1.tgz", + "integrity": "sha512-o6LAC268PLawlGVYrXTyaTfke4VtJftEheuwbgkQf7yvSXyWp1nRwBbAyKEkWXFZZsW/la5wrMuNbuBvZK2C1w==", "license": "MIT", "dependencies": { "@alcalzone/ansi-tokenize": "^0.3.0", @@ -2576,13 +2598,13 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", - "dev": true, + "version": "3.14.2", + "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", "license": "MIT", "dependencies": { - "argparse": "^2.0.1" + "argparse": "^1.0.7", + "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" @@ -2949,7 +2971,7 @@ }, "node_modules/minipass": { "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "resolved": "https://registry.npmmirror.com/minipass/-/minipass-7.1.3.tgz", "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", "dev": true, "license": "BlueOak-1.0.0", @@ -2972,9 +2994,9 @@ "license": "MIT" }, "node_modules/node-releases": { - "version": "2.0.44", - "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.44.tgz", - "integrity": "sha512-5WUyunoPMsvvEhS8AxHtRzP+oA8UCkJ7YRxatWKjngndhDGLiqEVAQKWjFAiAiuL8zMRGzGSJxFnLetoa43qGQ==", + "version": "2.0.38", + "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.38.tgz", + "integrity": "sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==", "dev": true, "license": "MIT" }, @@ -2994,9 +3016,9 @@ } }, "node_modules/openai": { - "version": "6.37.0", - "resolved": "https://registry.npmmirror.com/openai/-/openai-6.37.0.tgz", - "integrity": "sha512-0H5dEGFmmLv6KSd0W1w2nyL8WsLkX6yoLeQpU+dZAOuGcany5qkYQMmj35ZrKgb6yiyYqpUzFOpR8mZQkgqeEQ==", + "version": "6.35.0", + "resolved": "https://registry.npmmirror.com/openai/-/openai-6.35.0.tgz", + "integrity": "sha512-L/skwIGnt5xQZHb0UfTu9uAUKbis3ehKypOuJKi20QvG7UStV6C8IC3myGYHcdiF4kms/bAvOJ9UqqNWqi8x/Q==", "license": "Apache-2.0", "bin": { "openai": "bin/cli" @@ -3108,7 +3130,7 @@ }, "node_modules/path-scurry": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "resolved": "https://registry.npmmirror.com/path-scurry/-/path-scurry-2.0.2.tgz", "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", "dev": true, "license": "BlueOak-1.0.0", @@ -3125,7 +3147,7 @@ }, "node_modules/path-scurry/node_modules/lru-cache": { "version": "11.3.6", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.3.6.tgz", + "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-11.3.6.tgz", "integrity": "sha512-Gf/KoL3C/MlI7Bt0PGI9I+TeTC/I6r/csU58N4BSNc4lppLBeKsOdFYkK+dX0ABDUMJNfCHTyPpzwwO21Awd3A==", "dev": true, "license": "BlueOak-1.0.0", @@ -3190,9 +3212,9 @@ } }, "node_modules/react": { - "version": "19.2.6", - "resolved": "https://registry.npmmirror.com/react/-/react-19.2.6.tgz", - "integrity": "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==", + "version": "19.2.5", + "resolved": "https://registry.npmmirror.com/react/-/react-19.2.5.tgz", + "integrity": "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==", "license": "MIT", "engines": { "node": ">=0.10.0" @@ -3223,6 +3245,16 @@ "node": ">=4" } }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, "node_modules/restore-cursor": { "version": "4.0.0", "resolved": "https://registry.npmmirror.com/restore-cursor/-/restore-cursor-4.0.0.tgz", @@ -3338,15 +3370,6 @@ "node": ">=10" } }, - "node_modules/stack-utils/node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/string-argv": { "version": "0.3.2", "resolved": "https://registry.npmmirror.com/string-argv/-/string-argv-0.3.2.tgz", @@ -3504,13 +3527,14 @@ } }, "node_modules/tsx": { - "version": "4.22.0", - "resolved": "https://registry.npmmirror.com/tsx/-/tsx-4.22.0.tgz", - "integrity": "sha512-8ccZMPD69s1AbKXx0C5ddTNZfNjwV04iIKgjZmKfKxMynEtSYcK0Lh7iQFh53fI5Yu4pb9usgAiqyPmEONaALg==", + "version": "4.21.0", + "resolved": "https://registry.npmmirror.com/tsx/-/tsx-4.21.0.tgz", + "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "dev": true, "license": "MIT", "dependencies": { - "esbuild": "~0.28.0" + "esbuild": "~0.27.0", + "get-tsconfig": "^4.7.5" }, "bin": { "tsx": "dist/cli.mjs" @@ -3522,6 +3546,490 @@ "fsevents": "~2.3.3" } }, + "node_modules/tsx/node_modules/@esbuild/aix-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", + "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.27.7.tgz", + "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", + "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.27.7.tgz", + "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/darwin-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", + "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/darwin-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", + "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", + "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/freebsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", + "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", + "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", + "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", + "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-loong64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", + "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-mips64el": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", + "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", + "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-riscv64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", + "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-s390x": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", + "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", + "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", + "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/netbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", + "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", + "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", + "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", + "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/sunos-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", + "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", + "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", + "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", + "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/esbuild": { + "version": "0.27.7", + "resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.27.7.tgz", + "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.7", + "@esbuild/android-arm": "0.27.7", + "@esbuild/android-arm64": "0.27.7", + "@esbuild/android-x64": "0.27.7", + "@esbuild/darwin-arm64": "0.27.7", + "@esbuild/darwin-x64": "0.27.7", + "@esbuild/freebsd-arm64": "0.27.7", + "@esbuild/freebsd-x64": "0.27.7", + "@esbuild/linux-arm": "0.27.7", + "@esbuild/linux-arm64": "0.27.7", + "@esbuild/linux-ia32": "0.27.7", + "@esbuild/linux-loong64": "0.27.7", + "@esbuild/linux-mips64el": "0.27.7", + "@esbuild/linux-ppc64": "0.27.7", + "@esbuild/linux-riscv64": "0.27.7", + "@esbuild/linux-s390x": "0.27.7", + "@esbuild/linux-x64": "0.27.7", + "@esbuild/netbsd-arm64": "0.27.7", + "@esbuild/netbsd-x64": "0.27.7", + "@esbuild/openbsd-arm64": "0.27.7", + "@esbuild/openbsd-x64": "0.27.7", + "@esbuild/openharmony-arm64": "0.27.7", + "@esbuild/sunos-x64": "0.27.7", + "@esbuild/win32-arm64": "0.27.7", + "@esbuild/win32-ia32": "0.27.7", + "@esbuild/win32-x64": "0.27.7" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmmirror.com/type-check/-/type-check-0.4.0.tgz", @@ -3565,16 +4073,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.59.3", - "resolved": "https://registry.npmmirror.com/typescript-eslint/-/typescript-eslint-8.59.3.tgz", - "integrity": "sha512-KgusgyDgG4LI8Ih/sWaCtZ06tckLAS5CvT5A4D1Q7bYVoAAyzwiZvE4BmwDHkhRVkvhRBepKeASoFzQetha7Fg==", + "version": "8.59.2", + "resolved": "https://registry.npmmirror.com/typescript-eslint/-/typescript-eslint-8.59.2.tgz", + "integrity": "sha512-pJw051uomb3ZeCzGTpRb8RbEqB5Y4WWet8gl/GcTlU35BSx0PVdZ86/bqkQCyKKuraVQEK7r6kBHQXF+fBhkoQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.59.3", - "@typescript-eslint/parser": "8.59.3", - "@typescript-eslint/typescript-estree": "8.59.3", - "@typescript-eslint/utils": "8.59.3" + "@typescript-eslint/eslint-plugin": "8.59.2", + "@typescript-eslint/parser": "8.59.2", + "@typescript-eslint/typescript-estree": "8.59.2", + "@typescript-eslint/utils": "8.59.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -3589,9 +4097,9 @@ } }, "node_modules/undici-types": { - "version": "7.24.6", - "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.24.6.tgz", - "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "version": "7.19.2", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.19.2.tgz", + "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==", "dev": true, "license": "MIT" }, @@ -3695,9 +4203,9 @@ } }, "node_modules/ws": { - "version": "8.20.1", - "resolved": "https://registry.npmmirror.com/ws/-/ws-8.20.1.tgz", - "integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==", + "version": "8.20.0", + "resolved": "https://registry.npmmirror.com/ws/-/ws-8.20.0.tgz", + "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", "license": "MIT", "engines": { "node": ">=10.0.0" @@ -3723,9 +4231,9 @@ "license": "ISC" }, "node_modules/yaml": { - "version": "2.9.0", - "resolved": "https://registry.npmmirror.com/yaml/-/yaml-2.9.0.tgz", - "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "version": "2.8.4", + "resolved": "https://registry.npmmirror.com/yaml/-/yaml-2.8.4.tgz", + "integrity": "sha512-ml/JPOj9fOQK8RNnWojA67GbZ0ApXAUlN2UQclwv2eVgTgn7O9gg9o7paZWKMp4g0H3nTLtS9LVzhkpOFIKzog==", "dev": true, "license": "ISC", "optional": true, diff --git a/src/tests/tool-handlers.test.ts b/src/tests/tool-handlers.test.ts index 43af7ca..611d012 100644 --- a/src/tests/tool-handlers.test.ts +++ b/src/tests/tool-handlers.test.ts @@ -3,7 +3,9 @@ import assert from "node:assert/strict"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import { setTimeout as delay } from "node:timers/promises"; import type { ToolExecutionContext } from "../tools/executor"; +import { handleBashTool } from "../tools/bash-handler"; import { handleEditTool } from "../tools/edit-handler"; import { handleReadTool } from "../tools/read-handler"; import { handleWriteTool } from "../tools/write-handler"; @@ -19,6 +21,36 @@ afterEach(() => { } }); +test("Bash streams stdout and stderr before command completion", async () => { + const workspace = createTempWorkspace(); + const chunks: string[] = []; + let completed = false; + + const resultPromise = handleBashTool( + { + command: "printf 'first\\n'; sleep 1; printf 'second\\n'; printf 'err\\n' >&2", + }, + createContext("bash-live-output", workspace, { + onProcessStdout: (_pid, chunk) => { + chunks.push(chunk); + }, + }) + ).finally(() => { + completed = true; + }); + + await waitFor(() => chunks.join("").includes("first"), 1500); + + assert.equal(completed, false); + + const result = await resultPromise; + const streamedOutput = chunks.join(""); + assert.equal(result.ok, true); + assert.match(streamedOutput, /first/); + assert.match(streamedOutput, /second/); + assert.match(streamedOutput, /err/); +}); + test("Read returns snippet metadata and Edit can scope replacements by snippet_id", async () => { const workspace = createTempWorkspace(); const filePath = path.join(workspace, "sample.txt"); @@ -573,3 +605,14 @@ function createTempWorkspace(): string { tempDirs.push(dir); return dir; } + +async function waitFor(predicate: () => boolean, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (predicate()) { + return; + } + await delay(25); + } + assert.equal(predicate(), true); +} From ac223020cdbca70c145f93608066f21b942f54e2 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 09:33:40 +0800 Subject: [PATCH 041/129] feat: add update plan tool --- docs/SKILL.md | 259 ++++++++++++++++++++++++++++++ docs/SKILL_new.md | 264 +++++++++++++++++++++++++++++++ src/prompt.ts | 24 +++ src/tests/prompt.test.ts | 13 ++ src/tests/tool-handlers.test.ts | 26 +++ src/tools/executor.ts | 2 + src/tools/update-plan-handler.ts | 23 +++ src/ui/MessageView.tsx | 31 ++++ templates/tools/update-plan.md | 38 +++++ 9 files changed, 680 insertions(+) create mode 100644 docs/SKILL.md create mode 100644 docs/SKILL_new.md create mode 100644 src/tools/update-plan-handler.ts create mode 100644 templates/tools/update-plan.md diff --git a/docs/SKILL.md b/docs/SKILL.md new file mode 100644 index 0000000..f6d7149 --- /dev/null +++ b/docs/SKILL.md @@ -0,0 +1,259 @@ +--- +name: plan-and-execute +description: Automatically plan and execute tasks from issue documents. Reads issue requirements, creates a task list at the end of the document, and systematically executes each task while updating progress. Use when working with issue documents, task planning, or when you need to break down and execute complex multi-step requirements. +--- + +# Plan and Execute + +This Skill helps you automatically plan and execute tasks based on issue documents. It reads your requirements, creates a structured task list directly in the document, and systematically works through each task while keeping the document updated with progress. + +## Quick Start + +When you need to work through an issue document: + +1. The Skill will first ask you for the issue document path +2. It reads the document to understand requirements +3. Creates a task list at the end of the document +4. Executes tasks one by one, updating status in real-time + +## Instructions + +### Step 1: Get the issue document path + +Ask the user for the path to their issue document: + +``` +What is the path to your issue document? +``` + +The document can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. + +### Step 2: Read and analyze the issue document + +Use the Read tool to load the document content and analyze: + +- What are the main requirements? +- What tasks need to be completed? +- Are there dependencies between tasks? +- What is the complexity level? + +### Step 3: Create the task list + +Create a structured task list at the END of the issue document using this format: + +```markdown +## Task List + +- [ ] Task 1 description +- [ ] Task 2 description +- [ ] Task 3 description + +### Task Status Legend +- [ ] Pending +- [>] In Progress +- [x] Completed +``` + +Use the Edit tool to append this section to the document. Break down complex requirements into specific, actionable tasks. + +### Step 4: Execute tasks systematically + +For each task in the list: + +1. **Mark as in progress**: Update the task in the document from `[ ]` to `[>]` +2. **Execute the task**: Use appropriate tools to complete the work +3. **Mark as completed**: Update the task from `[>]` to `[x]` when finished +4. **Move to next task**: Only ONE task should be in progress at a time + +Important rules: +- Always update the document BEFORE starting work on a task +- Always update the document IMMEDIATELY after completing a task +- Never work on multiple tasks simultaneously +- If you encounter errors, keep the task as `[>]` and create new tasks to resolve blockers + +### Step 5: Handle task breakdown + +If during execution you discover a task is more complex than expected: + +1. Keep the current task as `[>]` +2. Add new sub-tasks below it with indentation: + ```markdown + - [>] Main task + - [ ] Sub-task 1 + - [ ] Sub-task 2 + ``` +3. Complete sub-tasks first, then mark the main task as complete + +### Step 6: Final verification + +After all tasks are completed (`[x]`): + +1. Review the issue requirements to ensure everything is addressed +2. Run any final checks (tests, builds, linting) +3. Add a completion summary at the end of the document + +## Task State Symbols + +- `[ ]` - **Pending**: Not started yet +- `[>]` - **In Progress**: Currently working on this +- `[x]` - **Completed**: Finished successfully +- `[!]` - **Blocked**: Cannot proceed (optional, for blocked tasks) + +## Examples + +### Example 1: Simple feature request + +**Issue document (before):** +```markdown +# Feature: Add dark mode toggle + +Users should be able to switch between light and dark themes. +The toggle should be in the settings page. +``` + +**Issue document (after task list added):** +```markdown +# Feature: Add dark mode toggle + +Users should be able to switch between light and dark themes. +The toggle should be in the settings page. + +## Task List + +- [ ] Create dark mode toggle component in Settings page +- [ ] Add dark mode state management (context/store) +- [ ] Implement CSS-in-JS styles for dark theme +- [ ] Update existing components to support theme switching +- [ ] Run tests and verify functionality + +### Task Status Legend +- [ ] Pending +- [>] In Progress +- [x] Completed +``` + +**During execution:** +```markdown +## Task List + +- [x] Create dark mode toggle component in Settings page +- [>] Add dark mode state management (context/store) +- [ ] Implement CSS-in-JS styles for dark theme +- [ ] Update existing components to support theme switching +- [ ] Run tests and verify functionality +``` + +### Example 2: Bug fix with investigation + +**Issue document:** +```markdown +# Bug: Login form crashes on submit + +When users click submit, the app crashes. +Error message: "Cannot read property 'email' of undefined" +``` + +**Task list created:** +```markdown +## Task List + +- [ ] Reproduce the bug locally +- [ ] Investigate the error in login form component +- [ ] Identify root cause of undefined email property +- [ ] Implement fix +- [ ] Add validation to prevent similar issues +- [ ] Test the fix with various inputs +- [ ] Update error handling + +### Task Status Legend +- [ ] Pending +- [>] In Progress +- [x] Completed +``` + +## When to Use This Skill + +Use this Skill when: + +1. **Complex multi-step tasks** - Issue requires 3+ distinct steps +2. **Feature implementation** - Building new functionality from requirements +3. **Bug fixing** - Need to investigate, fix, and verify +4. **Refactoring** - Multiple files or components need changes +5. **User provides requirements** - Issue document contains specifications +6. **Need progress tracking** - Want visible progress in the document itself + +## When NOT to Use This Skill + +Skip this Skill when: + +1. **Single simple task** - Just one straightforward action needed +2. **Trivial changes** - Quick fixes that don't need planning +3. **Informational requests** - User just wants explanation, not execution +4. **No document provided** - User hasn't created an issue document + +## Best Practices + +1. **Be specific with tasks**: "Add login button to navbar" not "Update UI" +2. **Keep tasks atomic**: Each task should be independently completable +3. **Update immediately**: Don't batch status updates, do them in real-time +4. **One task at a time**: Never mark multiple tasks as `[>]` +5. **Handle blockers**: If stuck, create new tasks to resolve the blocker +6. **Verify completion**: Only mark `[x]` when task is fully done + +## Advanced Usage + +### Handling dependencies + +When tasks have dependencies, order them properly: + +```markdown +- [ ] Create database schema +- [ ] Implement API endpoints (depends on schema) +- [ ] Build frontend forms (depends on API) +``` + +### Using sub-tasks + +For complex tasks, break them down: + +```markdown +- [>] Implement authentication system + - [x] Set up JWT library + - [>] Create login endpoint + - [ ] Create logout endpoint + - [ ] Add token refresh logic +``` + +### Adding notes + +Add implementation notes or findings: + +```markdown +- [x] Investigate performance issue + - Note: Found N+1 query in user loader + - Solution: Added dataloader batching +``` + +## Requirements + +This Skill uses standard Deep Code tools: + +- **Read**: To read the issue document +- **Edit**: To update task status in the document +- **Bash**: To run tests, builds, or other commands +- **Write**: To create new files if needed + +No additional dependencies required. + +## Workflow Summary + +1. Ask user for issue document path +2. Read and analyze the document +3. Append structured task list to document +4. For each task: + - Update to `[>]` in document + - Execute the task + - Update to `[x]` in document +5. Add completion summary when done + +This approach keeps all planning and progress tracking in one place - the issue document itself - making it easy for users to see what's been done and what's remaining. diff --git a/docs/SKILL_new.md b/docs/SKILL_new.md new file mode 100644 index 0000000..cdcc514 --- /dev/null +++ b/docs/SKILL_new.md @@ -0,0 +1,264 @@ +--- +name: plan-and-execute +description: Automatically plan and execute tasks from issue documents. Reads issue requirements, creates a markdown task list with the UpdatePlan tool, and systematically executes each task while updating progress. Use when working with issue documents, task planning, or when you need to break down and execute complex multi-step requirements. +--- + +# Plan and Execute + +This Skill helps you automatically plan and execute tasks based on issue documents. It reads your requirements, creates a structured markdown task list with the UpdatePlan tool, and systematically works through each task while keeping progress visible. + +## Quick Start + +When you need to work through an issue document: + +1. The Skill will first ask you for the issue document path +2. It reads the document to understand requirements +3. Creates a markdown task list by calling the UpdatePlan tool +4. Executes tasks one by one, updating the tool plan in real time + +## Instructions + +### Step 1: Get the issue document path + +Ask the user for the path to their issue document: + +``` +What is the path to your issue document? +``` + +The document can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. + +### Step 2: Read and analyze the issue document + +Use the Read tool to load the document content and analyze: + +- What are the main requirements? +- What tasks need to be completed? +- Are there dependencies between tasks? +- What is the complexity level? + +### Step 3: Create the task list + +Create a structured markdown task list and pass it to the UpdatePlan tool as the `plan` string. The tool input must use this shape: + +```json +{ + "plan": "## Task List\n\n- [ ] Task 1 description\n- [ ] Task 2 description\n- [ ] Task 3 description\n\n### Task Status Legend\n- [ ] Pending\n- [>] In Progress\n- [x] Completed" +} +``` + +Use this markdown format for the `plan` content: + +```markdown +## Task List + +- [ ] Task 1 description +- [ ] Task 2 description +- [ ] Task 3 description + +### Task Status Legend +- [ ] Pending +- [>] In Progress +- [x] Completed +``` + +Do not append the task list to the issue document. Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. + +### Step 4: Execute tasks systematically + +For each task in the list: + +1. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` +2. **Execute the task**: Use appropriate tools to complete the work +3. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished +4. **Move to next task**: Only ONE task should be in progress at a time + +Important rules: +- Always call UpdatePlan BEFORE starting work on a task +- Always call UpdatePlan IMMEDIATELY after completing a task +- Always pass the complete current markdown task list, not a partial diff +- Never work on multiple tasks simultaneously +- If you encounter errors, keep the task as `[>]` and create new tasks to resolve blockers + +### Step 5: Handle task breakdown + +If during execution you discover a task is more complex than expected: + +1. Keep the current task as `[>]` +2. Call UpdatePlan with new sub-tasks below it with indentation: + ```markdown + - [>] Main task + - [ ] Sub-task 1 + - [ ] Sub-task 2 + ``` +3. Complete sub-tasks first, then mark the main task as complete with UpdatePlan + +### Step 6: Final verification + +After all tasks are completed (`[x]`): + +1. Review the issue requirements to ensure everything is addressed +2. Run any final checks (tests, builds, linting) +3. Call UpdatePlan with every task marked `[x]` +4. Provide a concise completion summary in the final response + +## Task State Symbols + +- `[ ]` - **Pending**: Not started yet +- `[>]` - **In Progress**: Currently working on this +- `[x]` - **Completed**: Finished successfully +- `[!]` - **Blocked**: Cannot proceed (optional, for blocked tasks) + +## Examples + +### Example 1: Simple feature request + +**Issue document (before):** +```markdown +# Feature: Add dark mode toggle + +Users should be able to switch between light and dark themes. +The toggle should be in the settings page. +``` + +**UpdatePlan call after analysis:** +```markdown +## Task List + +- [ ] Create dark mode toggle component in Settings page +- [ ] Add dark mode state management (context/store) +- [ ] Implement CSS-in-JS styles for dark theme +- [ ] Update existing components to support theme switching +- [ ] Run tests and verify functionality + +### Task Status Legend +- [ ] Pending +- [>] In Progress +- [x] Completed +``` + +**UpdatePlan call during execution:** +```markdown +## Task List + +- [x] Create dark mode toggle component in Settings page +- [>] Add dark mode state management (context/store) +- [ ] Implement CSS-in-JS styles for dark theme +- [ ] Update existing components to support theme switching +- [ ] Run tests and verify functionality +``` + +### Example 2: Bug fix with investigation + +**Issue document:** +```markdown +# Bug: Login form crashes on submit + +When users click submit, the app crashes. +Error message: "Cannot read property 'email' of undefined" +``` + +**UpdatePlan call after analysis:** +```markdown +## Task List + +- [ ] Reproduce the bug locally +- [ ] Investigate the error in login form component +- [ ] Identify root cause of undefined email property +- [ ] Implement fix +- [ ] Add validation to prevent similar issues +- [ ] Test the fix with various inputs +- [ ] Update error handling + +### Task Status Legend +- [ ] Pending +- [>] In Progress +- [x] Completed +``` + +## When to Use This Skill + +Use this Skill when: + +1. **Complex multi-step tasks** - Issue requires 3+ distinct steps +2. **Feature implementation** - Building new functionality from requirements +3. **Bug fixing** - Need to investigate, fix, and verify +4. **Refactoring** - Multiple files or components need changes +5. **User provides requirements** - Issue document contains specifications +6. **Need progress tracking** - Want visible progress without editing the issue document + +## When NOT to Use This Skill + +Skip this Skill when: + +1. **Single simple task** - Just one straightforward action needed +2. **Trivial changes** - Quick fixes that don't need planning +3. **Informational requests** - User just wants explanation, not execution +4. **No document provided** - User hasn't created an issue document + +## Best Practices + +1. **Be specific with tasks**: "Add login button to navbar" not "Update UI" +2. **Keep tasks atomic**: Each task should be independently completable +3. **Update immediately**: Don't batch status updates, do them in real-time +4. **One task at a time**: Never mark multiple tasks as `[>]` +5. **Handle blockers**: If stuck, create new tasks to resolve the blocker +6. **Verify completion**: Only mark `[x]` when task is fully done + +## Advanced Usage + +### Handling dependencies + +When tasks have dependencies, order them properly: + +```markdown +- [ ] Create database schema +- [ ] Implement API endpoints (depends on schema) +- [ ] Build frontend forms (depends on API) +``` + +### Using sub-tasks + +For complex tasks, break them down: + +```markdown +- [>] Implement authentication system + - [x] Set up JWT library + - [>] Create login endpoint + - [ ] Create logout endpoint + - [ ] Add token refresh logic +``` + +### Adding notes + +Add implementation notes or findings: + +```markdown +- [x] Investigate performance issue + - Note: Found N+1 query in user loader + - Solution: Added dataloader batching +``` + +## Requirements + +This Skill uses standard tools: + +- **Read**: To read the issue document +- **UpdatePlan**: To create and update the markdown task list +- **Bash**: To run tests, builds, or other commands +- **Write**: To create new files if needed + +No additional dependencies required. + +## Workflow Summary + +1. Ask user for issue document path +2. Read and analyze the document +3. Call UpdatePlan with the structured markdown task list +4. For each task: + - Update to `[>]` with UpdatePlan + - Execute the task + - Update to `[x]` with UpdatePlan +5. Call UpdatePlan with all tasks completed and summarize the result + +This approach keeps planning and progress tracking in the UpdatePlan display, leaving the issue document unchanged unless the actual task requires editing it. diff --git a/src/prompt.ts b/src/prompt.ts index 4774725..50aa2a3 100644 --- a/src/prompt.ts +++ b/src/prompt.ts @@ -509,6 +509,30 @@ export function getTools(_options: PromptToolOptions = {}, externalTools: ToolDe }, }, }, + { + type: "function", + function: { + name: "UpdatePlan", + description: + "Update the current task plan. The plan argument must be the complete markdown task list to show as the latest progress state.", + parameters: { + type: "object", + properties: { + plan: { + type: "string", + description: + "The complete markdown task list, including task status markers such as [ ], [>], [x], and optional notes.", + }, + explanation: { + type: "string", + description: "Optional short reason for changing the plan.", + }, + }, + required: ["plan"], + additionalProperties: false, + }, + }, + }, { type: "function", function: { diff --git a/src/tests/prompt.test.ts b/src/tests/prompt.test.ts index 28c6488..b7c9178 100644 --- a/src/tests/prompt.test.ts +++ b/src/tests/prompt.test.ts @@ -12,11 +12,24 @@ test("getTools always includes WebSearch", () => { assert.equal(names.includes("WebSearch"), true); }); +test("getTools includes UpdatePlan with string plan schema", () => { + const tool = getTools().find((candidate) => candidate.function.name === "UpdatePlan"); + assert.ok(tool); + assert.deepEqual(tool.function.parameters.required, ["plan"]); + assert.equal((tool.function.parameters.properties.plan as { type?: unknown }).type, "string"); +}); + test("getSystemPrompt always includes WebSearch docs", () => { const prompt = getSystemPrompt("/tmp/project"); assert.equal(prompt.includes("## WebSearch"), true); }); +test("getSystemPrompt includes UpdatePlan docs", () => { + const prompt = getSystemPrompt("/tmp/project"); + assert.equal(prompt.includes("## UpdatePlan"), true); + assert.equal(prompt.includes("The `plan` argument is a markdown string, not an array of step objects."), true); +}); + test("getSystemPrompt includes current date guidance", () => { const now = new Date(); const expected = `今天是${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日。随着对话的进行,时间在流逝。`; diff --git a/src/tests/tool-handlers.test.ts b/src/tests/tool-handlers.test.ts index 58828a2..0b21edd 100644 --- a/src/tests/tool-handlers.test.ts +++ b/src/tests/tool-handlers.test.ts @@ -8,6 +8,7 @@ import type { ToolExecutionContext } from "../tools/executor"; import { handleBashTool } from "../tools/bash-handler"; import { handleEditTool } from "../tools/edit-handler"; import { handleReadTool } from "../tools/read-handler"; +import { handleUpdatePlanTool } from "../tools/update-plan-handler"; import { handleWriteTool } from "../tools/write-handler"; const tempDirs: string[] = []; @@ -51,6 +52,31 @@ test("Bash streams stdout and stderr before command completion", async () => { assert.match(streamedOutput, /err/); }); +test("UpdatePlan accepts a markdown task list string", async () => { + const workspace = createTempWorkspace(); + const plan = ["## Task List", "", "- [>] Inspect current behavior", "- [ ] Implement UpdatePlan"].join("\n"); + + const result = await handleUpdatePlanTool({ plan }, createContext("update-plan", workspace)); + + assert.equal(result.ok, true); + assert.equal(result.name, "UpdatePlan"); + assert.equal(result.output, "Plan updated."); + assert.equal(result.metadata?.plan, plan); +}); + +test("UpdatePlan rejects non-string plan payloads", async () => { + const workspace = createTempWorkspace(); + + const result = await handleUpdatePlanTool( + { plan: [{ step: "Inspect current behavior", status: "in_progress" }] }, + createContext("update-plan-invalid", workspace) + ); + + assert.equal(result.ok, false); + assert.equal(result.name, "UpdatePlan"); + assert.match(result.error ?? "", /InputValidationError/); +}); + test("Read returns snippet metadata and Edit can scope replacements by snippet_id", async () => { const workspace = createTempWorkspace(); const filePath = path.join(workspace, "sample.txt"); diff --git a/src/tools/executor.ts b/src/tools/executor.ts index e6018d9..70ceab1 100644 --- a/src/tools/executor.ts +++ b/src/tools/executor.ts @@ -4,6 +4,7 @@ import { handleAskUserQuestionTool } from "./ask-user-question-handler"; import { handleBashTool } from "./bash-handler"; import { handleEditTool } from "./edit-handler"; import { handleReadTool } from "./read-handler"; +import { handleUpdatePlanTool } from "./update-plan-handler"; import { handleWebSearchTool } from "./web-search-handler"; import { handleWriteTool } from "./write-handler"; import type { McpManager } from "../mcp/mcp-manager"; @@ -120,6 +121,7 @@ export class ToolExecutor { this.toolHandlers.set("write", handleWriteTool); this.toolHandlers.set("edit", handleEditTool); this.toolHandlers.set("AskUserQuestion", handleAskUserQuestionTool); + this.toolHandlers.set("UpdatePlan", handleUpdatePlanTool); this.toolHandlers.set("WebSearch", handleWebSearchTool); } diff --git a/src/tools/update-plan-handler.ts b/src/tools/update-plan-handler.ts new file mode 100644 index 0000000..7c7198e --- /dev/null +++ b/src/tools/update-plan-handler.ts @@ -0,0 +1,23 @@ +import { z } from "zod"; +import type { ToolExecutionContext, ToolExecutionResult } from "./executor"; +import { executeValidatedTool } from "../common/runtime"; + +const updatePlanSchema = z.strictObject({ + plan: z.string().trim().min(1, "plan must not be empty."), + explanation: z.string().trim().optional(), +}); + +export async function handleUpdatePlanTool( + args: Record, + _context: ToolExecutionContext +): Promise { + return executeValidatedTool("UpdatePlan", updatePlanSchema, args, _context, async (input) => ({ + ok: true, + name: "UpdatePlan", + output: "Plan updated.", + metadata: { + plan: input.plan, + ...(input.explanation ? { explanation: input.explanation } : {}), + }, + })); +} diff --git a/src/ui/MessageView.tsx b/src/ui/MessageView.tsx index c8793fc..6f388d0 100644 --- a/src/ui/MessageView.tsx +++ b/src/ui/MessageView.tsx @@ -72,6 +72,7 @@ export function MessageView({ message, collapsed, width = 80 }: Props): React.Re if (message.role === "tool") { const summary = buildToolSummary(message); const diffLines = getToolDiffPreviewLines(summary); + const planLines = getUpdatePlanPreviewLines(summary); return ( {diffLines.length > 0 ? : null} + {planLines.length > 0 ? : null} ); } @@ -272,6 +274,20 @@ function getToolDiffPreviewLines(summary: ToolSummary): DiffPreviewLine[] { return parseDiffPreview(diffPreview); } +function getUpdatePlanPreviewLines(summary: ToolSummary): string[] { + if (!summary.ok || summary.name !== "UpdatePlan") { + return []; + } + const plan = summary.metadata?.plan; + if (typeof plan !== "string" || !plan.trim()) { + return []; + } + return plan + .split(/\r?\n/) + .map((line) => line.trimEnd()) + .filter((line) => line.trim().length > 0); +} + export function parseDiffPreview(diffPreview: string): DiffPreviewLine[] { return diffPreview .split("\n") @@ -311,6 +327,21 @@ function DiffPreview({ lines }: { lines: DiffPreviewLine[] }): React.ReactElemen ); } +function PlanPreview({ lines }: { lines: string[] }): React.ReactElement { + return ( + + └ Plan + + {lines.map((line, index) => ( + + {line} + + ))} + + + ); +} + function isPlainRecord(value: unknown): value is Record { return Boolean(value && typeof value === "object" && !Array.isArray(value)); } diff --git a/templates/tools/update-plan.md b/templates/tools/update-plan.md new file mode 100644 index 0000000..c3e08f0 --- /dev/null +++ b/templates/tools/update-plan.md @@ -0,0 +1,38 @@ +## UpdatePlan + +Updates the current task plan and progress display. + +Usage: +- Use this tool for non-trivial multi-step tasks when a task list helps track execution progress. +- Pass the complete current task list every time. The latest call replaces the previous visible plan. +- The `plan` argument is a markdown string, not an array of step objects. +- Keep exactly one task marked `[>]` while work is in progress. +- Update the plan before starting a task, immediately after completing a task, and whenever tasks are split, merged, reordered, blocked, or changed. +- Do not edit issue documents just to maintain task status; use `UpdatePlan` for the task list instead. + +Task markers: +- `[ ]` Pending +- `[>]` In progress +- `[x]` Completed +- `[!]` Blocked + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "plan": { + "description": "The complete markdown task list to display as the latest plan state.", + "type": "string" + }, + "explanation": { + "description": "Optional short reason for changing the plan.", + "type": "string" + } + }, + "required": [ + "plan" + ], + "additionalProperties": false +} +``` From 52dafba25903dc70258d7e59dbe86e283a0f091f Mon Sep 17 00:00:00 2001 From: dengmik-commits <270912164+dengmik-commits@users.noreply.github.com> Date: Mon, 18 May 2026 09:50:38 +0800 Subject: [PATCH 042/129] fix: re-apply dynamic modifier parsing for Shift+Enter after upstream sync Upstream v0.1.21 reverted PR #70. Re-apply: - isShiftReturn() / isReturn() dynamic CSI modifier bit parsing - Kitty progressive enhancement (ESC[>1u) alongside xterm modifyOtherKeys - Clear input when key.return is true (safety net) --- src/tests/promptInputKeys.test.ts | 6 ++--- src/ui/prompt/cursor.ts | 4 +-- src/ui/prompt/useTerminalInput.ts | 43 ++++++++++++++++++++++++++++--- 3 files changed, 44 insertions(+), 9 deletions(-) diff --git a/src/tests/promptInputKeys.test.ts b/src/tests/promptInputKeys.test.ts index 69d2075..8952a3d 100644 --- a/src/tests/promptInputKeys.test.ts +++ b/src/tests/promptInputKeys.test.ts @@ -80,7 +80,7 @@ test("parseTerminalInput keeps BS payload for meta+backspace", () => { test("parseTerminalInput recognizes shifted return sequences", () => { const { input, key } = parseTerminalInput("\u001B\r"); - assert.equal(input, "\r"); + assert.equal(input, ""); assert.equal(key.return, true); assert.equal(key.shift, true); assert.equal(key.meta, false); @@ -108,8 +108,8 @@ test("parseTerminalInput recognizes alternate shifted return sequences", () => { }); test("terminal extended key helpers request and restore modifyOtherKeys mode", () => { - assert.equal(enableTerminalExtendedKeys(), "\u001B[>4;1m"); - assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m"); + assert.equal(enableTerminalExtendedKeys(), "\u001B[>4;1m\u001B[>1u"); + assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m\u001B[ { diff --git a/src/ui/prompt/cursor.ts b/src/ui/prompt/cursor.ts index 2668470..59b24f2 100644 --- a/src/ui/prompt/cursor.ts +++ b/src/ui/prompt/cursor.ts @@ -41,11 +41,11 @@ function disableTerminalFocusReporting(): string { } export function enableTerminalExtendedKeys(): string { - return "\u001B[>4;1m"; + return "\u001B[>4;1m\u001B[>1u"; } export function disableTerminalExtendedKeys(): string { - return "\u001B[>4;0m"; + return "\u001B[>4;0m\u001B[ Date: Mon, 18 May 2026 10:22:22 +0800 Subject: [PATCH 043/129] fix: refresh mcpToolDefinitions cache after MCP reconnect After reconnectMcpServer succeeds, SessionManager's cached mcpToolDefinitions was stale, causing "Unknown MCP tool" errors when the model tried to call reconnected tools. --- src/session.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/session.ts b/src/session.ts index eddfe5c..0527ba8 100644 --- a/src/session.ts +++ b/src/session.ts @@ -261,6 +261,7 @@ export class SessionManager { async reconnectMcpServer(name: string, config?: McpServerConfig): Promise { await this.mcpManager.reconnect(name, config); + this.mcpToolDefinitions = this.mcpManager.getMcpToolDefinitions(); } dispose(): void { From 63ec2a340192f6e53b8003162320e102e521a49e Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 10:40:39 +0800 Subject: [PATCH 044/129] feat: update update-plan prompt draft --- docs/SKILL.md | 124 +++++++++++++++------------------ docs/SKILL_new.md | 77 +++++++++----------- templates/tools/update-plan.md | 7 -- 3 files changed, 90 insertions(+), 118 deletions(-) diff --git a/docs/SKILL.md b/docs/SKILL.md index f6d7149..8f45c3b 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -1,36 +1,38 @@ --- name: plan-and-execute -description: Automatically plan and execute tasks from issue documents. Reads issue requirements, creates a task list at the end of the document, and systematically executes each task while updating progress. Use when working with issue documents, task planning, or when you need to break down and execute complex multi-step requirements. +description: Automatically plan and execute requirements. Creates a markdown task list with the UpdatePlan tool, and systematically executes each task while updating progress. Use when working with task planning or when you need to break down and execute complex multi-step requirements. --- # Plan and Execute -This Skill helps you automatically plan and execute tasks based on issue documents. It reads your requirements, creates a structured task list directly in the document, and systematically works through each task while keeping the document updated with progress. +This Skill helps you automatically plan and execute requirements. It creates a structured markdown task list with the UpdatePlan tool and systematically works through each task while keeping progress visible. ## Quick Start -When you need to work through an issue document: +When you need to work through a multi-step request: -1. The Skill will first ask you for the issue document path -2. It reads the document to understand requirements -3. Creates a task list at the end of the document -4. Executes tasks one by one, updating status in real-time +1. Understand the requirements +2. Read referenced files only when they are needed for context +3. Create a markdown task list by calling the UpdatePlan tool +4. Execute tasks one by one, updating the tool plan in real time ## Instructions -### Step 1: Get the issue document path +### Step 1: Gather the requirements -Ask the user for the path to their issue document: +Identify the requirements from the available context. Do not require the requirements to be moved into a separate document. + +If a required referenced file path is missing, ask for it: ``` -What is the path to your issue document? +What is the path to the referenced file? ``` -The document can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. +Referenced files can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. If no additional file is needed, continue from the available requirements. -### Step 2: Read and analyze the issue document +### Step 2: Read and analyze the requirements -Use the Read tool to load the document content and analyze: +Analyze the requirements and read any referenced files needed for context: - What are the main requirements? - What tasks need to be completed? @@ -39,7 +41,15 @@ Use the Read tool to load the document content and analyze: ### Step 3: Create the task list -Create a structured task list at the END of the issue document using this format: +Create a structured markdown task list and pass it to the UpdatePlan tool as the `plan` string. The tool input must use this shape: + +```json +{ + "plan": "## Task List\n\n- [ ] Task 1 description\n- [ ] Task 2 description\n- [ ] Task 3 description" +} +``` + +Use this markdown format for the `plan` content: ```markdown ## Task List @@ -47,27 +57,23 @@ Create a structured task list at the END of the issue document using this format - [ ] Task 1 description - [ ] Task 2 description - [ ] Task 3 description - -### Task Status Legend -- [ ] Pending -- [>] In Progress -- [x] Completed ``` -Use the Edit tool to append this section to the document. Break down complex requirements into specific, actionable tasks. +Do not append the task list to a source file. Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. ### Step 4: Execute tasks systematically For each task in the list: -1. **Mark as in progress**: Update the task in the document from `[ ]` to `[>]` +1. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` 2. **Execute the task**: Use appropriate tools to complete the work -3. **Mark as completed**: Update the task from `[>]` to `[x]` when finished +3. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished 4. **Move to next task**: Only ONE task should be in progress at a time Important rules: -- Always update the document BEFORE starting work on a task -- Always update the document IMMEDIATELY after completing a task +- Always call UpdatePlan BEFORE starting work on a task +- Always call UpdatePlan IMMEDIATELY after completing a task +- Always pass the complete current markdown task list, not a partial diff - Never work on multiple tasks simultaneously - If you encounter errors, keep the task as `[>]` and create new tasks to resolve blockers @@ -76,34 +82,35 @@ Important rules: If during execution you discover a task is more complex than expected: 1. Keep the current task as `[>]` -2. Add new sub-tasks below it with indentation: +2. Call UpdatePlan with new sub-tasks below it with indentation: ```markdown - [>] Main task - [ ] Sub-task 1 - [ ] Sub-task 2 ``` -3. Complete sub-tasks first, then mark the main task as complete +3. Complete sub-tasks first, then mark the main task as complete with UpdatePlan ### Step 6: Final verification After all tasks are completed (`[x]`): -1. Review the issue requirements to ensure everything is addressed +1. Review the original requirements to ensure everything is addressed 2. Run any final checks (tests, builds, linting) -3. Add a completion summary at the end of the document +3. Call UpdatePlan with every task marked `[x]` +4. Provide a concise completion summary in the final response ## Task State Symbols -- `[ ]` - **Pending**: Not started yet -- `[>]` - **In Progress**: Currently working on this -- `[x]` - **Completed**: Finished successfully -- `[!]` - **Blocked**: Cannot proceed (optional, for blocked tasks) +- `[ ]` - Pending +- `[>]` - In progress +- `[x]` - Completed +- `[!]` - Blocked ## Examples ### Example 1: Simple feature request -**Issue document (before):** +**Example requirements:** ```markdown # Feature: Add dark mode toggle @@ -111,13 +118,8 @@ Users should be able to switch between light and dark themes. The toggle should be in the settings page. ``` -**Issue document (after task list added):** +**UpdatePlan call after analysis:** ```markdown -# Feature: Add dark mode toggle - -Users should be able to switch between light and dark themes. -The toggle should be in the settings page. - ## Task List - [ ] Create dark mode toggle component in Settings page @@ -125,14 +127,9 @@ The toggle should be in the settings page. - [ ] Implement CSS-in-JS styles for dark theme - [ ] Update existing components to support theme switching - [ ] Run tests and verify functionality - -### Task Status Legend -- [ ] Pending -- [>] In Progress -- [x] Completed ``` -**During execution:** +**UpdatePlan call during execution:** ```markdown ## Task List @@ -145,7 +142,7 @@ The toggle should be in the settings page. ### Example 2: Bug fix with investigation -**Issue document:** +**Example requirements:** ```markdown # Bug: Login form crashes on submit @@ -153,7 +150,7 @@ When users click submit, the app crashes. Error message: "Cannot read property 'email' of undefined" ``` -**Task list created:** +**UpdatePlan call after analysis:** ```markdown ## Task List @@ -164,23 +161,18 @@ Error message: "Cannot read property 'email' of undefined" - [ ] Add validation to prevent similar issues - [ ] Test the fix with various inputs - [ ] Update error handling - -### Task Status Legend -- [ ] Pending -- [>] In Progress -- [x] Completed ``` ## When to Use This Skill Use this Skill when: -1. **Complex multi-step tasks** - Issue requires 3+ distinct steps +1. **Complex multi-step tasks** - Request requires 3+ distinct steps 2. **Feature implementation** - Building new functionality from requirements 3. **Bug fixing** - Need to investigate, fix, and verify 4. **Refactoring** - Multiple files or components need changes -5. **User provides requirements** - Issue document contains specifications -6. **Need progress tracking** - Want visible progress in the document itself +5. **Detailed requirements** - Specifications need to be translated into concrete tasks +6. **Need progress tracking** - Want visible progress without editing source files ## When NOT to Use This Skill @@ -189,7 +181,7 @@ Skip this Skill when: 1. **Single simple task** - Just one straightforward action needed 2. **Trivial changes** - Quick fixes that don't need planning 3. **Informational requests** - User just wants explanation, not execution -4. **No document provided** - User hasn't created an issue document +4. **No execution requested** - User only wants brainstorming or a high-level explanation ## Best Practices @@ -236,10 +228,10 @@ Add implementation notes or findings: ## Requirements -This Skill uses standard Deep Code tools: +This Skill uses standard tools: -- **Read**: To read the issue document -- **Edit**: To update task status in the document +- **Read**: To inspect referenced files when needed +- **UpdatePlan**: To create and update the markdown task list - **Bash**: To run tests, builds, or other commands - **Write**: To create new files if needed @@ -247,13 +239,13 @@ No additional dependencies required. ## Workflow Summary -1. Ask user for issue document path -2. Read and analyze the document -3. Append structured task list to document +1. Analyze the requirements +2. Read referenced files when needed +3. Call UpdatePlan with the structured markdown task list 4. For each task: - - Update to `[>]` in document + - Update to `[>]` with UpdatePlan - Execute the task - - Update to `[x]` in document -5. Add completion summary when done + - Update to `[x]` with UpdatePlan +5. Call UpdatePlan with all tasks completed and summarize the result -This approach keeps all planning and progress tracking in one place - the issue document itself - making it easy for users to see what's been done and what's remaining. +This approach keeps planning and progress tracking in the UpdatePlan display, leaving source materials unchanged unless the actual task requires editing them. diff --git a/docs/SKILL_new.md b/docs/SKILL_new.md index cdcc514..6efbee9 100644 --- a/docs/SKILL_new.md +++ b/docs/SKILL_new.md @@ -1,36 +1,38 @@ --- name: plan-and-execute -description: Automatically plan and execute tasks from issue documents. Reads issue requirements, creates a markdown task list with the UpdatePlan tool, and systematically executes each task while updating progress. Use when working with issue documents, task planning, or when you need to break down and execute complex multi-step requirements. +description: Automatically plan and execute requirements. Creates a markdown task list with the UpdatePlan tool, and systematically executes each task while updating progress. Use when working with task planning or when you need to break down and execute complex multi-step requirements. --- # Plan and Execute -This Skill helps you automatically plan and execute tasks based on issue documents. It reads your requirements, creates a structured markdown task list with the UpdatePlan tool, and systematically works through each task while keeping progress visible. +This Skill helps you automatically plan and execute requirements. It creates a structured markdown task list with the UpdatePlan tool and systematically works through each task while keeping progress visible. ## Quick Start -When you need to work through an issue document: +When you need to work through a multi-step request: -1. The Skill will first ask you for the issue document path -2. It reads the document to understand requirements -3. Creates a markdown task list by calling the UpdatePlan tool -4. Executes tasks one by one, updating the tool plan in real time +1. Understand the requirements +2. Read referenced files when they are needed for context +3. Create a markdown task list by calling the UpdatePlan tool +4. Execute tasks one by one, updating the tool plan in real time ## Instructions -### Step 1: Get the issue document path +### Step 1: Gather the requirements -Ask the user for the path to their issue document: +Identify the requirements from the available context. Do not require the requirements to be moved into a separate document. + +If a required referenced file path is missing, ask for it: ``` -What is the path to your issue document? +What is the path to the referenced file? ``` -The document can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. +Referenced files can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. If no additional file is needed, continue from the available requirements. -### Step 2: Read and analyze the issue document +### Step 2: Read and analyze the requirements -Use the Read tool to load the document content and analyze: +Analyze the requirements and read any referenced files needed for context: - What are the main requirements? - What tasks need to be completed? @@ -43,7 +45,7 @@ Create a structured markdown task list and pass it to the UpdatePlan tool as the ```json { - "plan": "## Task List\n\n- [ ] Task 1 description\n- [ ] Task 2 description\n- [ ] Task 3 description\n\n### Task Status Legend\n- [ ] Pending\n- [>] In Progress\n- [x] Completed" + "plan": "## Task List\n\n- [ ] Task 1 description\n- [ ] Task 2 description\n- [ ] Task 3 description" } ``` @@ -55,14 +57,9 @@ Use this markdown format for the `plan` content: - [ ] Task 1 description - [ ] Task 2 description - [ ] Task 3 description - -### Task Status Legend -- [ ] Pending -- [>] In Progress -- [x] Completed ``` -Do not append the task list to the issue document. Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. +Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. ### Step 4: Execute tasks systematically @@ -97,23 +94,23 @@ If during execution you discover a task is more complex than expected: After all tasks are completed (`[x]`): -1. Review the issue requirements to ensure everything is addressed +1. Review the original requirements to ensure everything is addressed 2. Run any final checks (tests, builds, linting) 3. Call UpdatePlan with every task marked `[x]` 4. Provide a concise completion summary in the final response ## Task State Symbols -- `[ ]` - **Pending**: Not started yet -- `[>]` - **In Progress**: Currently working on this -- `[x]` - **Completed**: Finished successfully -- `[!]` - **Blocked**: Cannot proceed (optional, for blocked tasks) +- `[ ]` - Pending +- `[>]` - In progress +- `[x]` - Completed +- `[!]` - Blocked ## Examples ### Example 1: Simple feature request -**Issue document (before):** +**Example requirements:** ```markdown # Feature: Add dark mode toggle @@ -130,11 +127,6 @@ The toggle should be in the settings page. - [ ] Implement CSS-in-JS styles for dark theme - [ ] Update existing components to support theme switching - [ ] Run tests and verify functionality - -### Task Status Legend -- [ ] Pending -- [>] In Progress -- [x] Completed ``` **UpdatePlan call during execution:** @@ -150,7 +142,7 @@ The toggle should be in the settings page. ### Example 2: Bug fix with investigation -**Issue document:** +**Example requirements:** ```markdown # Bug: Login form crashes on submit @@ -169,23 +161,18 @@ Error message: "Cannot read property 'email' of undefined" - [ ] Add validation to prevent similar issues - [ ] Test the fix with various inputs - [ ] Update error handling - -### Task Status Legend -- [ ] Pending -- [>] In Progress -- [x] Completed ``` ## When to Use This Skill Use this Skill when: -1. **Complex multi-step tasks** - Issue requires 3+ distinct steps +1. **Complex multi-step tasks** - Request requires 3+ distinct steps 2. **Feature implementation** - Building new functionality from requirements 3. **Bug fixing** - Need to investigate, fix, and verify 4. **Refactoring** - Multiple files or components need changes -5. **User provides requirements** - Issue document contains specifications -6. **Need progress tracking** - Want visible progress without editing the issue document +5. **Detailed requirements** - Specifications need to be translated into concrete tasks +6. **Need progress tracking** - Want visible progress without editing source files ## When NOT to Use This Skill @@ -194,7 +181,7 @@ Skip this Skill when: 1. **Single simple task** - Just one straightforward action needed 2. **Trivial changes** - Quick fixes that don't need planning 3. **Informational requests** - User just wants explanation, not execution -4. **No document provided** - User hasn't created an issue document +4. **No execution requested** - User only wants brainstorming or a high-level explanation ## Best Practices @@ -243,7 +230,7 @@ Add implementation notes or findings: This Skill uses standard tools: -- **Read**: To read the issue document +- **Read**: To inspect referenced files when needed - **UpdatePlan**: To create and update the markdown task list - **Bash**: To run tests, builds, or other commands - **Write**: To create new files if needed @@ -252,8 +239,8 @@ No additional dependencies required. ## Workflow Summary -1. Ask user for issue document path -2. Read and analyze the document +1. Analyze the requirements +2. Read referenced files when needed 3. Call UpdatePlan with the structured markdown task list 4. For each task: - Update to `[>]` with UpdatePlan @@ -261,4 +248,4 @@ No additional dependencies required. - Update to `[x]` with UpdatePlan 5. Call UpdatePlan with all tasks completed and summarize the result -This approach keeps planning and progress tracking in the UpdatePlan display, leaving the issue document unchanged unless the actual task requires editing it. +This approach keeps planning and progress tracking in the UpdatePlan display, leaving source materials unchanged unless the actual task requires editing them. diff --git a/templates/tools/update-plan.md b/templates/tools/update-plan.md index c3e08f0..28d12f7 100644 --- a/templates/tools/update-plan.md +++ b/templates/tools/update-plan.md @@ -8,13 +8,6 @@ Usage: - The `plan` argument is a markdown string, not an array of step objects. - Keep exactly one task marked `[>]` while work is in progress. - Update the plan before starting a task, immediately after completing a task, and whenever tasks are split, merged, reordered, blocked, or changed. -- Do not edit issue documents just to maintain task status; use `UpdatePlan` for the task list instead. - -Task markers: -- `[ ]` Pending -- `[>]` In progress -- `[x]` Completed -- `[!]` Blocked ```json { From c638114bfc2ab23c502322955403e4c8dc1bff62 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 11:00:13 +0800 Subject: [PATCH 045/129] feat: update update-plan prompt draft --- docs/SKILL.md | 47 ++++++++++++++--------------- docs/SKILL_new.md | 54 ++++++++++++++-------------------- templates/tools/update-plan.md | 2 ++ 3 files changed, 48 insertions(+), 55 deletions(-) diff --git a/docs/SKILL.md b/docs/SKILL.md index 8f45c3b..deb8c5e 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -11,16 +11,16 @@ This Skill helps you automatically plan and execute requirements. It creates a s When you need to work through a multi-step request: -1. Understand the requirements -2. Read referenced files only when they are needed for context -3. Create a markdown task list by calling the UpdatePlan tool -4. Execute tasks one by one, updating the tool plan in real time +1. Analyze the requirements and explore enough project context +2. Create a markdown task list by calling the UpdatePlan tool +3. Execute tasks one by one, updating the tool plan in real time +4. Revise the remaining plan as new context appears ## Instructions -### Step 1: Gather the requirements +### Step 1: Analyze the requirements -Identify the requirements from the available context. Do not require the requirements to be moved into a separate document. +Identify the requirements from the available context. Explore the project enough to make the plan concrete and accurate. If a required referenced file path is missing, ask for it: @@ -30,16 +30,13 @@ What is the path to the referenced file? Referenced files can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. If no additional file is needed, continue from the available requirements. -### Step 2: Read and analyze the requirements - -Analyze the requirements and read any referenced files needed for context: - - What are the main requirements? - What tasks need to be completed? - Are there dependencies between tasks? - What is the complexity level? +- Which files, modules, commands, or tests are relevant? -### Step 3: Create the task list +### Step 2: Create the task list Create a structured markdown task list and pass it to the UpdatePlan tool as the `plan` string. The tool input must use this shape: @@ -59,25 +56,28 @@ Use this markdown format for the `plan` content: - [ ] Task 3 description ``` -Do not append the task list to a source file. Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. +Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. -### Step 4: Execute tasks systematically +### Step 3: Execute tasks systematically For each task in the list: -1. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` -2. **Execute the task**: Use appropriate tools to complete the work -3. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished -4. **Move to next task**: Only ONE task should be in progress at a time +1. **Refresh the plan**: Before starting the first task and after completing each task, re-evaluate the latest conversation and project context. Update the remaining tasks when scope, order, blockers, or follow-up work changes. +2. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` +3. **Execute the task**: Use appropriate tools to complete the work +4. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished +5. **Move to next task**: Only ONE task should be in progress at a time Important rules: +- Always keep the plan aligned with the latest context before executing the next task - Always call UpdatePlan BEFORE starting work on a task - Always call UpdatePlan IMMEDIATELY after completing a task - Always pass the complete current markdown task list, not a partial diff - Never work on multiple tasks simultaneously +- Remove tasks that are no longer relevant, and add newly discovered tasks before working on them - If you encounter errors, keep the task as `[>]` and create new tasks to resolve blockers -### Step 5: Handle task breakdown +### Step 4: Handle task breakdown If during execution you discover a task is more complex than expected: @@ -90,7 +90,7 @@ If during execution you discover a task is more complex than expected: ``` 3. Complete sub-tasks first, then mark the main task as complete with UpdatePlan -### Step 6: Final verification +### Step 5: Final verification After all tasks are completed (`[x]`): @@ -230,7 +230,7 @@ Add implementation notes or findings: This Skill uses standard tools: -- **Read**: To inspect referenced files when needed +- **Read**: To inspect relevant files and explore project context - **UpdatePlan**: To create and update the markdown task list - **Bash**: To run tests, builds, or other commands - **Write**: To create new files if needed @@ -239,13 +239,14 @@ No additional dependencies required. ## Workflow Summary -1. Analyze the requirements -2. Read referenced files when needed -3. Call UpdatePlan with the structured markdown task list +1. Analyze the requirements and relevant project context +2. Call UpdatePlan with the structured markdown task list +3. Refresh the remaining plan before the first task 4. For each task: - Update to `[>]` with UpdatePlan - Execute the task - Update to `[x]` with UpdatePlan + - Re-evaluate and revise remaining tasks before moving on 5. Call UpdatePlan with all tasks completed and summarize the result This approach keeps planning and progress tracking in the UpdatePlan display, leaving source materials unchanged unless the actual task requires editing them. diff --git a/docs/SKILL_new.md b/docs/SKILL_new.md index 6efbee9..41ed251 100644 --- a/docs/SKILL_new.md +++ b/docs/SKILL_new.md @@ -11,16 +11,16 @@ This Skill helps you automatically plan and execute requirements. It creates a s When you need to work through a multi-step request: -1. Understand the requirements -2. Read referenced files when they are needed for context -3. Create a markdown task list by calling the UpdatePlan tool -4. Execute tasks one by one, updating the tool plan in real time +1. Analyze the requirements and explore enough project context +2. Create a markdown task list by calling the UpdatePlan tool +3. Execute tasks one by one, updating the tool plan in real time +4. Revise the remaining plan as new context appears ## Instructions -### Step 1: Gather the requirements +### Step 1: Analyze the requirements -Identify the requirements from the available context. Do not require the requirements to be moved into a separate document. +Identify the requirements from the available context. Explore the project enough to make the plan concrete and accurate. If a required referenced file path is missing, ask for it: @@ -30,16 +30,13 @@ What is the path to the referenced file? Referenced files can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. If no additional file is needed, continue from the available requirements. -### Step 2: Read and analyze the requirements - -Analyze the requirements and read any referenced files needed for context: - - What are the main requirements? - What tasks need to be completed? - Are there dependencies between tasks? - What is the complexity level? +- Which files, modules, commands, or tests are relevant? -### Step 3: Create the task list +### Step 2: Create the task list Create a structured markdown task list and pass it to the UpdatePlan tool as the `plan` string. The tool input must use this shape: @@ -61,23 +58,26 @@ Use this markdown format for the `plan` content: Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. -### Step 4: Execute tasks systematically +### Step 3: Execute tasks systematically For each task in the list: -1. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` -2. **Execute the task**: Use appropriate tools to complete the work -3. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished -4. **Move to next task**: Only ONE task should be in progress at a time +1. **Refresh the plan**: Before starting the first task and after completing each task, re-evaluate the latest conversation and project context. Update the remaining tasks when scope, order, blockers, or follow-up work changes. +2. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` +3. **Execute the task**: Use appropriate tools to complete the work +4. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished +5. **Move to next task**: Only ONE task should be in progress at a time Important rules: +- Always keep the plan aligned with the latest context before executing the next task - Always call UpdatePlan BEFORE starting work on a task - Always call UpdatePlan IMMEDIATELY after completing a task - Always pass the complete current markdown task list, not a partial diff - Never work on multiple tasks simultaneously +- Remove tasks that are no longer relevant, and add newly discovered tasks before working on them - If you encounter errors, keep the task as `[>]` and create new tasks to resolve blockers -### Step 5: Handle task breakdown +### Step 4: Handle task breakdown If during execution you discover a task is more complex than expected: @@ -90,7 +90,7 @@ If during execution you discover a task is more complex than expected: ``` 3. Complete sub-tasks first, then mark the main task as complete with UpdatePlan -### Step 6: Final verification +### Step 5: Final verification After all tasks are completed (`[x]`): @@ -226,26 +226,16 @@ Add implementation notes or findings: - Solution: Added dataloader batching ``` -## Requirements - -This Skill uses standard tools: - -- **Read**: To inspect referenced files when needed -- **UpdatePlan**: To create and update the markdown task list -- **Bash**: To run tests, builds, or other commands -- **Write**: To create new files if needed - -No additional dependencies required. - ## Workflow Summary -1. Analyze the requirements -2. Read referenced files when needed -3. Call UpdatePlan with the structured markdown task list +1. Analyze the requirements and relevant project context +2. Call UpdatePlan with the structured markdown task list +3. Refresh the remaining plan before the first task 4. For each task: - Update to `[>]` with UpdatePlan - Execute the task - Update to `[x]` with UpdatePlan + - Re-evaluate and revise remaining tasks before moving on 5. Call UpdatePlan with all tasks completed and summarize the result This approach keeps planning and progress tracking in the UpdatePlan display, leaving source materials unchanged unless the actual task requires editing them. diff --git a/templates/tools/update-plan.md b/templates/tools/update-plan.md index 28d12f7..a0f2fd6 100644 --- a/templates/tools/update-plan.md +++ b/templates/tools/update-plan.md @@ -8,6 +8,8 @@ Usage: - The `plan` argument is a markdown string, not an array of step objects. - Keep exactly one task marked `[>]` while work is in progress. - Update the plan before starting a task, immediately after completing a task, and whenever tasks are split, merged, reordered, blocked, or changed. +- Before executing the first task and after completing each task, re-evaluate the latest conversation and project context, then revise the remaining plan if needed. +- Remove tasks that are no longer relevant, and add newly discovered follow-up tasks before working on them. ```json { From 33bcd484aad094b45a48d6808d017d3868b5fe78 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 11:06:06 +0800 Subject: [PATCH 046/129] feat: update update-plan prompt draft --- docs/SKILL.md | 252 ---------------------------------------------- docs/SKILL_new.md | 21 ++-- 2 files changed, 13 insertions(+), 260 deletions(-) delete mode 100644 docs/SKILL.md diff --git a/docs/SKILL.md b/docs/SKILL.md deleted file mode 100644 index deb8c5e..0000000 --- a/docs/SKILL.md +++ /dev/null @@ -1,252 +0,0 @@ ---- -name: plan-and-execute -description: Automatically plan and execute requirements. Creates a markdown task list with the UpdatePlan tool, and systematically executes each task while updating progress. Use when working with task planning or when you need to break down and execute complex multi-step requirements. ---- - -# Plan and Execute - -This Skill helps you automatically plan and execute requirements. It creates a structured markdown task list with the UpdatePlan tool and systematically works through each task while keeping progress visible. - -## Quick Start - -When you need to work through a multi-step request: - -1. Analyze the requirements and explore enough project context -2. Create a markdown task list by calling the UpdatePlan tool -3. Execute tasks one by one, updating the tool plan in real time -4. Revise the remaining plan as new context appears - -## Instructions - -### Step 1: Analyze the requirements - -Identify the requirements from the available context. Explore the project enough to make the plan concrete and accurate. - -If a required referenced file path is missing, ask for it: - -``` -What is the path to the referenced file? -``` - -Referenced files can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. If no additional file is needed, continue from the available requirements. - -- What are the main requirements? -- What tasks need to be completed? -- Are there dependencies between tasks? -- What is the complexity level? -- Which files, modules, commands, or tests are relevant? - -### Step 2: Create the task list - -Create a structured markdown task list and pass it to the UpdatePlan tool as the `plan` string. The tool input must use this shape: - -```json -{ - "plan": "## Task List\n\n- [ ] Task 1 description\n- [ ] Task 2 description\n- [ ] Task 3 description" -} -``` - -Use this markdown format for the `plan` content: - -```markdown -## Task List - -- [ ] Task 1 description -- [ ] Task 2 description -- [ ] Task 3 description -``` - -Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. - -### Step 3: Execute tasks systematically - -For each task in the list: - -1. **Refresh the plan**: Before starting the first task and after completing each task, re-evaluate the latest conversation and project context. Update the remaining tasks when scope, order, blockers, or follow-up work changes. -2. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` -3. **Execute the task**: Use appropriate tools to complete the work -4. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished -5. **Move to next task**: Only ONE task should be in progress at a time - -Important rules: -- Always keep the plan aligned with the latest context before executing the next task -- Always call UpdatePlan BEFORE starting work on a task -- Always call UpdatePlan IMMEDIATELY after completing a task -- Always pass the complete current markdown task list, not a partial diff -- Never work on multiple tasks simultaneously -- Remove tasks that are no longer relevant, and add newly discovered tasks before working on them -- If you encounter errors, keep the task as `[>]` and create new tasks to resolve blockers - -### Step 4: Handle task breakdown - -If during execution you discover a task is more complex than expected: - -1. Keep the current task as `[>]` -2. Call UpdatePlan with new sub-tasks below it with indentation: - ```markdown - - [>] Main task - - [ ] Sub-task 1 - - [ ] Sub-task 2 - ``` -3. Complete sub-tasks first, then mark the main task as complete with UpdatePlan - -### Step 5: Final verification - -After all tasks are completed (`[x]`): - -1. Review the original requirements to ensure everything is addressed -2. Run any final checks (tests, builds, linting) -3. Call UpdatePlan with every task marked `[x]` -4. Provide a concise completion summary in the final response - -## Task State Symbols - -- `[ ]` - Pending -- `[>]` - In progress -- `[x]` - Completed -- `[!]` - Blocked - -## Examples - -### Example 1: Simple feature request - -**Example requirements:** -```markdown -# Feature: Add dark mode toggle - -Users should be able to switch between light and dark themes. -The toggle should be in the settings page. -``` - -**UpdatePlan call after analysis:** -```markdown -## Task List - -- [ ] Create dark mode toggle component in Settings page -- [ ] Add dark mode state management (context/store) -- [ ] Implement CSS-in-JS styles for dark theme -- [ ] Update existing components to support theme switching -- [ ] Run tests and verify functionality -``` - -**UpdatePlan call during execution:** -```markdown -## Task List - -- [x] Create dark mode toggle component in Settings page -- [>] Add dark mode state management (context/store) -- [ ] Implement CSS-in-JS styles for dark theme -- [ ] Update existing components to support theme switching -- [ ] Run tests and verify functionality -``` - -### Example 2: Bug fix with investigation - -**Example requirements:** -```markdown -# Bug: Login form crashes on submit - -When users click submit, the app crashes. -Error message: "Cannot read property 'email' of undefined" -``` - -**UpdatePlan call after analysis:** -```markdown -## Task List - -- [ ] Reproduce the bug locally -- [ ] Investigate the error in login form component -- [ ] Identify root cause of undefined email property -- [ ] Implement fix -- [ ] Add validation to prevent similar issues -- [ ] Test the fix with various inputs -- [ ] Update error handling -``` - -## When to Use This Skill - -Use this Skill when: - -1. **Complex multi-step tasks** - Request requires 3+ distinct steps -2. **Feature implementation** - Building new functionality from requirements -3. **Bug fixing** - Need to investigate, fix, and verify -4. **Refactoring** - Multiple files or components need changes -5. **Detailed requirements** - Specifications need to be translated into concrete tasks -6. **Need progress tracking** - Want visible progress without editing source files - -## When NOT to Use This Skill - -Skip this Skill when: - -1. **Single simple task** - Just one straightforward action needed -2. **Trivial changes** - Quick fixes that don't need planning -3. **Informational requests** - User just wants explanation, not execution -4. **No execution requested** - User only wants brainstorming or a high-level explanation - -## Best Practices - -1. **Be specific with tasks**: "Add login button to navbar" not "Update UI" -2. **Keep tasks atomic**: Each task should be independently completable -3. **Update immediately**: Don't batch status updates, do them in real-time -4. **One task at a time**: Never mark multiple tasks as `[>]` -5. **Handle blockers**: If stuck, create new tasks to resolve the blocker -6. **Verify completion**: Only mark `[x]` when task is fully done - -## Advanced Usage - -### Handling dependencies - -When tasks have dependencies, order them properly: - -```markdown -- [ ] Create database schema -- [ ] Implement API endpoints (depends on schema) -- [ ] Build frontend forms (depends on API) -``` - -### Using sub-tasks - -For complex tasks, break them down: - -```markdown -- [>] Implement authentication system - - [x] Set up JWT library - - [>] Create login endpoint - - [ ] Create logout endpoint - - [ ] Add token refresh logic -``` - -### Adding notes - -Add implementation notes or findings: - -```markdown -- [x] Investigate performance issue - - Note: Found N+1 query in user loader - - Solution: Added dataloader batching -``` - -## Requirements - -This Skill uses standard tools: - -- **Read**: To inspect relevant files and explore project context -- **UpdatePlan**: To create and update the markdown task list -- **Bash**: To run tests, builds, or other commands -- **Write**: To create new files if needed - -No additional dependencies required. - -## Workflow Summary - -1. Analyze the requirements and relevant project context -2. Call UpdatePlan with the structured markdown task list -3. Refresh the remaining plan before the first task -4. For each task: - - Update to `[>]` with UpdatePlan - - Execute the task - - Update to `[x]` with UpdatePlan - - Re-evaluate and revise remaining tasks before moving on -5. Call UpdatePlan with all tasks completed and summarize the result - -This approach keeps planning and progress tracking in the UpdatePlan display, leaving source materials unchanged unless the actual task requires editing them. diff --git a/docs/SKILL_new.md b/docs/SKILL_new.md index 41ed251..9037a00 100644 --- a/docs/SKILL_new.md +++ b/docs/SKILL_new.md @@ -12,9 +12,10 @@ This Skill helps you automatically plan and execute requirements. It creates a s When you need to work through a multi-step request: 1. Analyze the requirements and explore enough project context -2. Create a markdown task list by calling the UpdatePlan tool -3. Execute tasks one by one, updating the tool plan in real time -4. Revise the remaining plan as new context appears +2. Clarify unclear or ambiguous requirements with AskUserQuestion +3. Create a markdown task list by calling the UpdatePlan tool +4. Execute tasks one by one, updating the tool plan in real time +5. Revise the remaining plan as new context appears ## Instructions @@ -22,7 +23,9 @@ When you need to work through a multi-step request: Identify the requirements from the available context. Explore the project enough to make the plan concrete and accurate. -If a required referenced file path is missing, ask for it: +If the original requirements are unclear, incomplete, or ambiguous, call the AskUserQuestion tool before creating the task list. Ask only the questions needed to avoid implementing the wrong behavior, and keep each question specific to the decision that affects the plan or acceptance criteria. + +If a required referenced file path is missing, ask for it with AskUserQuestion: ``` What is the path to the referenced file? @@ -35,6 +38,7 @@ Referenced files can be in any text format (.md, .txt, etc.) that contains task - Are there dependencies between tasks? - What is the complexity level? - Which files, modules, commands, or tests are relevant? +- What ambiguity would change the implementation or acceptance criteria? ### Step 2: Create the task list @@ -229,13 +233,14 @@ Add implementation notes or findings: ## Workflow Summary 1. Analyze the requirements and relevant project context -2. Call UpdatePlan with the structured markdown task list -3. Refresh the remaining plan before the first task -4. For each task: +2. Call AskUserQuestion if the original requirements are unclear or ambiguous +3. Call UpdatePlan with the structured markdown task list +4. Refresh the remaining plan before the first task +5. For each task: - Update to `[>]` with UpdatePlan - Execute the task - Update to `[x]` with UpdatePlan - Re-evaluate and revise remaining tasks before moving on -5. Call UpdatePlan with all tasks completed and summarize the result +6. Call UpdatePlan with all tasks completed and summarize the result This approach keeps planning and progress tracking in the UpdatePlan display, leaving source materials unchanged unless the actual task requires editing them. From 32e5796c9e188defdb69c8f3db75a539f5c9dc0c Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 11:57:39 +0800 Subject: [PATCH 047/129] feat: update update-plan prompt draft --- docs/SKILL_new.md | 48 +++++++++++++++++----------------- templates/tools/update-plan.md | 2 +- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/docs/SKILL_new.md b/docs/SKILL_new.md index 9037a00..9fc8bd2 100644 --- a/docs/SKILL_new.md +++ b/docs/SKILL_new.md @@ -116,55 +116,55 @@ After all tasks are completed (`[x]`): **Example requirements:** ```markdown -# Feature: Add dark mode toggle +# 新功能:添加深色模式切换 -Users should be able to switch between light and dark themes. -The toggle should be in the settings page. +用户应该能够在浅色和深色主题之间切换。 +切换开关应放在设置页面中。 ``` -**UpdatePlan call after analysis:** +**分析后的 UpdatePlan 调用:** ```markdown ## Task List -- [ ] Create dark mode toggle component in Settings page -- [ ] Add dark mode state management (context/store) -- [ ] Implement CSS-in-JS styles for dark theme -- [ ] Update existing components to support theme switching -- [ ] Run tests and verify functionality +- [ ] 在设置页面创建深色模式切换组件 +- [ ] 添加深色模式状态管理(context/store) +- [ ] 实现深色主题的 CSS-in-JS 样式 +- [ ] 更新现有组件以支持主题切换 +- [ ] 运行测试并验证功能 ``` **UpdatePlan call during execution:** ```markdown ## Task List -- [x] Create dark mode toggle component in Settings page -- [>] Add dark mode state management (context/store) -- [ ] Implement CSS-in-JS styles for dark theme -- [ ] Update existing components to support theme switching -- [ ] Run tests and verify functionality +- [x] 在设置页面创建深色模式切换组件 +- [>] 添加深色模式状态管理(context/store) +- [ ] 实现深色主题的 CSS-in-JS 样式 +- [ ] 更新现有组件以支持主题切换 +- [ ] 运行测试并验证功能 ``` ### Example 2: Bug fix with investigation **Example requirements:** ```markdown -# Bug: Login form crashes on submit +# Fix bug:登录表单提交时崩溃 -When users click submit, the app crashes. -Error message: "Cannot read property 'email' of undefined" +当用户点击提交时,应用崩溃。 +错误信息:"Cannot read property 'email' of undefined" ``` **UpdatePlan call after analysis:** ```markdown ## Task List -- [ ] Reproduce the bug locally -- [ ] Investigate the error in login form component -- [ ] Identify root cause of undefined email property -- [ ] Implement fix -- [ ] Add validation to prevent similar issues -- [ ] Test the fix with various inputs -- [ ] Update error handling +- [ ] 在本地复现缺陷 +- [ ] 调查登录表单组件中的错误 +- [ ] 定位 undefined email 属性的根本原因 +- [ ] 实施修复 +- [ ] 添加验证以防止类似问题 +- [ ] 使用各种输入测试修复 +- [ ] 更新错误处理 ``` ## When to Use This Skill diff --git a/templates/tools/update-plan.md b/templates/tools/update-plan.md index a0f2fd6..0c74b36 100644 --- a/templates/tools/update-plan.md +++ b/templates/tools/update-plan.md @@ -5,7 +5,7 @@ Updates the current task plan and progress display. Usage: - Use this tool for non-trivial multi-step tasks when a task list helps track execution progress. - Pass the complete current task list every time. The latest call replaces the previous visible plan. -- The `plan` argument is a markdown string, not an array of step objects. +- The `plan` argument is a markdown string, not an array of step objects. If the requirement is in Chinese, then use Chinese for the markdown as well. - Keep exactly one task marked `[>]` while work is in progress. - Update the plan before starting a task, immediately after completing a task, and whenever tasks are split, merged, reordered, blocked, or changed. - Before executing the first task and after completing each task, re-evaluate the latest conversation and project context, then revise the remaining plan if needed. From 77a779fe341aaa81a726dea319bd2b85c7fb2ab9 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 14:29:34 +0800 Subject: [PATCH 048/129] feat: change the UpdatePlan display --- src/session.ts | 2 ++ src/tests/session.test.ts | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/session.ts b/src/session.ts index 431eb40..dde29b3 100644 --- a/src/session.ts +++ b/src/session.ts @@ -2032,6 +2032,8 @@ ${skillMd} if (description) { return description; } + } else if (toolName === "UpdatePlan") { + return typeof args.explanation === "string" ? args.explanation.trim() : ""; } const firstKey = Object.keys(args)[0]; diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index e5ab740..7bc98f9 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1160,6 +1160,27 @@ test("buildOpenAIMessages preserves a real failed tool result", () => { assert.doesNotMatch(openAIMessages[1]?.content ?? "", /Previous tool call did not complete/); }); +test("UpdatePlan tool params only show explanation when provided", () => { + const manager = createSessionManager(process.cwd(), "machine-id-update-plan-params"); + const plan = "## Task List\n\n- [ ] Inspect project"; + + const withExplanation = (manager as any).buildToolMessage( + "session-1", + "call-plan-1", + JSON.stringify({ ok: true, name: "UpdatePlan", output: "Plan updated." }), + { name: "UpdatePlan", arguments: JSON.stringify({ plan, explanation: "Start planning" }) } + ) as SessionMessage; + const withoutExplanation = (manager as any).buildToolMessage( + "session-1", + "call-plan-2", + JSON.stringify({ ok: true, name: "UpdatePlan", output: "Plan updated." }), + { name: "UpdatePlan", arguments: JSON.stringify({ plan }) } + ) as SessionMessage; + + assert.equal(withExplanation.meta?.paramsMd, "Start planning"); + assert.equal(withoutExplanation.meta?.paramsMd, ""); +}); + test("buildOpenAIMessages repairs mixed missing duplicate and orphan tool messages", () => { const manager = createSessionManager(process.cwd(), "machine-id-mixed-tool-badcase"); const assistantMessage = (manager as any).buildAssistantMessage( From e691b3efcf32e24d4521a29e17b0a512960d2a79 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 15:39:26 +0800 Subject: [PATCH 049/129] feat: add default skill templates and update session management to include skill prompts --- package.json | 1 + src/prompt.ts | 198 ++++----------------- src/session.ts | 28 ++- src/tests/prompt.test.ts | 36 +++- src/tests/session.test.ts | 35 ++++ templates/skills/agent-drift-guard.md | 152 ++++++++++++++++ templates/skills/plan-and-execute.md | 246 ++++++++++++++++++++++++++ 7 files changed, 528 insertions(+), 168 deletions(-) create mode 100644 templates/skills/agent-drift-guard.md create mode 100644 templates/skills/plan-and-execute.md diff --git a/package.json b/package.json index 90c2b51..e61d81d 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "dist/cli.js", "templates/tools/**", "templates/prompts/**", + "templates/skills/**", "README.md", "LICENSE" ], diff --git a/src/prompt.ts b/src/prompt.ts index 50aa2a3..717991b 100644 --- a/src/prompt.ts +++ b/src/prompt.ts @@ -8,161 +8,6 @@ import type { SessionMessage } from "./session"; import { findGitBashPath, resolveShellPath } from "./common/shell-utils"; import { supportsMultimodal } from "./common/model-capabilities"; -export const AGENT_DRIFT_GUARD_SKILL = ` ---- -name: agent-drift-guard -description: Detect and correct execution drift while working on user requests. Use when you are actively implementing, debugging, reviewing, or investigating and there is a risk of wandering beyond the user's goal, adding unrequested work, touching live systems, over-exploring, or ignoring repeated user boundary corrections. Especially useful during multi-step coding tasks, production-adjacent requests, ambiguous scopes, and anytime you should self-check whether it is still solving the requested problem. ---- - -# Agent Drift Guard - -Keep execution tightly aligned with the user's actual request. - -## Quick Start - -Run this mental check before substantial work and again whenever the plan expands: - -1. State the user's requested outcome in one sentence. -2. List explicit non-goals or boundaries the user has set. -3. Ask whether the next action directly advances the requested outcome. -4. If not, either cut it or pause to confirm. - -## Drift Signals - -Treat these as warning signs that execution may be drifting: - -- Exploring broadly before opening the most relevant file, command, or artifact. -- Solving adjacent operational issues when the user asked only for code changes. -- Adding extra safeguards, scripts, docs, refactors, or cleanup that the user did not ask for. -- Reframing the task around what seems "better" instead of what was requested. -- Continuing with a broader plan after the user narrows the scope. -- Repeating searches or tool calls without increasing certainty. -- Mixing diagnosis, remediation, and feature work when the user asked for only one of them. -- Touching production-like state, external systems, or live data without explicit permission. - -## Severity Levels - -### Level 1: Mild Drift - -Examples: -- One or two extra exploratory commands. -- Considering a broader solution but not acting on it yet. -- Briefly over-explaining instead of moving the task forward. - -Response: -- Auto-correct silently. -- Narrow to the smallest next action. -- Do not interrupt the user. - -### Level 2: Material Drift - -Examples: -- Planning additional deliverables not requested. -- Writing helper scripts, migrations, docs, or tests outside the asked scope. -- Expanding from code changes into operational fixes. -- Continuing after the user has already corrected the scope once. - -Response: -- Stop and realign internally first. -- If the broader action is avoidable, drop it and continue on scope. -- If the broader action has non-obvious tradeoffs, ask a brief confirmation question. - -### Level 3: Boundary or Risk Violation - -Examples: -- Modifying live systems, production data, external services, or user-owned state without being asked. -- Taking destructive or hard-to-reverse actions outside the requested scope. -- Ignoring repeated user instructions about what not to do. - -Response: -- Pause before acting. -- Surface the exact boundary and ask for confirmation. -- Offer the smallest on-scope option first. - -## Self-Check Loop - -Use this loop during execution: - -### Before the first meaningful action - -Write down mentally: -- Requested outcome -- Allowed scope -- Forbidden scope -- Smallest useful next step - -### After each non-trivial step - -Ask: -- Did this step directly help deliver the requested outcome? -- Did I learn something that changes scope, or only implementation? -- Am I about to do more than the user asked? - -### After a user correction - -Treat the correction as a hard boundary update. - -Then: -- Remove the old broader plan. -- Do not defend the discarded work. -- Continue from the narrowed scope. -- If needed, acknowledge briefly and move on. - -## Decision Rules - -Use these rules in order: - -1. Prefer the most direct artifact first. - - Open the relevant file before scanning the whole repo. - - Inspect the specific failing path before designing a general framework. - -2. Prefer the smallest complete fix. - - Solve the asked problem before improving related systems. - - Avoid bonus work unless it is required for correctness. - -3. Prefer internal correction over user interruption. - - If you can shrink back to scope confidently, do it. - - Ask only when the next step changes deliverables, risk, or ownership. - -4. Treat repeated user constraints as priority signals. - - A repeated instruction means your execution style is currently misaligned. - - Tighten scope immediately. - -5. Separate categories of work. - - Code change, investigation, production remediation, cleanup, and documentation are distinct tasks unless the user explicitly combines them. - -## Good Intervention Style - -When you must pause, keep it short and specific: - -- State the potential drift in one sentence. -- Name the tradeoff or boundary. -- Offer the smallest on-scope option first. - -Example: - -"Quick alignment check: I can keep this to the code fix only, or also add an ops cleanup step. I'll stick to the code fix unless you want both." - -## Anti-Patterns - -Do not: - -- Create cleanup scripts, docs, or side tools just because they seem useful. -- Broaden the task after discovering a neighboring problem. -- Continue with a plan the user has already rejected. -- Justify drift with "best practice" when the user asked for a narrower deliverable. -- Hide extra work inside a larger patch. - -## Final Check Before Responding - -Before sending the final answer, verify: - -- The delivered work matches the requested outcome. -- No extra deliverables were added without confirmation. -- Any assumptions are stated briefly. -- Suggested next steps are optional, not bundled into the completed work. -`; - const COMPACT_PROMPT_BASE = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions. This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context. @@ -254,6 +99,8 @@ type PromptToolOptions = { webSearchEnabled?: boolean; }; +const DEFAULT_SKILL_TEMPLATES = ["agent-drift-guard.md", "plan-and-execute.md"]; + function readToolDocs(extensionRoot: string, options: PromptToolOptions = {}): string { const toolsDir = path.join(extensionRoot, "templates", "tools"); if (!fs.existsSync(toolsDir)) { @@ -281,6 +128,35 @@ function readToolDocs(extensionRoot: string, options: PromptToolOptions = {}): s return docs.join("\n\n"); } +function readDefaultSkillDocs(extensionRoot: string): Array<{ name: string; content: string }> { + const skillsDir = path.join(extensionRoot, "templates", "skills"); + return DEFAULT_SKILL_TEMPLATES.map((entry) => { + const fullPath = path.join(skillsDir, entry); + try { + return { + name: path.basename(entry, ".md"), + content: fs.readFileSync(fullPath, "utf8").trim(), + }; + } catch { + return null; + } + }).filter((skill): skill is { name: string; content: string } => Boolean(skill?.content)); +} + +export function getDefaultSkillPrompt(): string { + const skillDocs = readDefaultSkillDocs(getExtensionRoot()); + if (skillDocs.length === 0) { + return ""; + } + + const blocks = skillDocs.map( + (skill) => `<${skill.name}-skill> +${skill.content} +` + ); + return `Use the skill documents below to assist the user:\n${blocks.join("\n\n")}`; +} + function getCurrentDateAndModelPrompt(model?: string): string { const date = new Date(); let prompt = `今天是${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日。随着对话的进行,时间在流逝。`; @@ -288,10 +164,10 @@ function getCurrentDateAndModelPrompt(model?: string): string { return prompt; } -export function getSystemPrompt(projectRoot: string, options: PromptToolOptions = {}): string { +export function getSystemPrompt(_projectRoot: string, options: PromptToolOptions = {}): string { const toolDocs = readToolDocs(getExtensionRoot(), options); const basePrompt = toolDocs ? `${SYSTEM_PROMPT_BASE}\n\n# Available Tools\n\n${toolDocs}` : SYSTEM_PROMPT_BASE; - return `${basePrompt}\n\n${getCurrentDateAndModelPrompt(options.model)}\n\n${getRuntimeContext(projectRoot)}`; + return basePrompt; } export function getCompactPrompt(sessionMessages: SessionMessage[]): string { @@ -310,7 +186,7 @@ export function getCompactPrompt(sessionMessages: SessionMessage[]): string { return `${COMPACT_PROMPT_BASE}\n\nconversation below:\n\n\`\`\`jsonl\n${jsonl}\n\`\`\``; } -function getRuntimeContext(projectRoot: string): string { +export function getRuntimeContext(projectRoot: string, model?: string): string { const uname = getUnameInfo(); const shellPath = getShellPathInfo(); const shellModeOpts = process.platform === "win32" ? { "shell mode": "git-bash" } : {}; @@ -328,7 +204,11 @@ function getRuntimeContext(projectRoot: string): string { jq: checkToolInstalled("jq"), }, }; - return `# Local Workspace Environment\n\n\`\`\`json + return `${getCurrentDateAndModelPrompt(model)} + +# Local Workspace Environment + +\`\`\`json ${JSON.stringify(env, null, 2)} \`\`\``; } diff --git a/src/session.ts b/src/session.ts index dde29b3..1c9d3b6 100644 --- a/src/session.ts +++ b/src/session.ts @@ -9,7 +9,14 @@ import type { ChatCompletionMessageParam, ChatCompletionContentPart } from "open import { launchNotifyScript } from "./common/notify"; import { buildThinkingRequestOptions } from "./common/openai-thinking"; import { DEEPSEEK_V4_MODELS, supportsMultimodal } from "./common/model-capabilities"; -import { getCompactPrompt, getSystemPrompt, getTools, AGENT_DRIFT_GUARD_SKILL, type ToolDefinition } from "./prompt"; +import { + getCompactPrompt, + getDefaultSkillPrompt, + getRuntimeContext, + getSystemPrompt, + getTools, + type ToolDefinition, +} from "./prompt"; import { ToolExecutor, type CreateOpenAIClient } from "./tools/executor"; import { McpManager } from "./mcp/mcp-manager"; import type { McpServerConfig } from "./settings"; @@ -907,20 +914,29 @@ The candidate skills are as follows:\n\n`; this.saveSessionsIndex(index); this.removeSessionMessages(droppedEntries.map((item) => item.id)); - const systemPrompt = getSystemPrompt(this.projectRoot, this.getPromptToolOptions()); + const promptToolOptions = this.getPromptToolOptions(); + const systemPrompt = getSystemPrompt(this.projectRoot, promptToolOptions); const systemMessage = this.buildSystemMessage(sessionId, systemPrompt); this.appendSessionMessage(sessionId, systemMessage); + const defaultSkillPrompt = getDefaultSkillPrompt(); + if (defaultSkillPrompt) { + const defaultSkillMessage = this.buildSystemMessage(sessionId, defaultSkillPrompt); + this.appendSessionMessage(sessionId, defaultSkillMessage); + } + + const runtimeContextMessage = this.buildSystemMessage( + sessionId, + getRuntimeContext(this.projectRoot, promptToolOptions.model) + ); + this.appendSessionMessage(sessionId, runtimeContextMessage); + const agentInstructions = this.loadAgentInstructions(); if (agentInstructions) { const instructionsMessage = this.buildSystemMessage(sessionId, agentInstructions); this.appendSessionMessage(sessionId, instructionsMessage); } - const defaultSkillPrompt = `Use the skill document below to assist the user:\n${AGENT_DRIFT_GUARD_SKILL}`; - const defaultSkillMessage = this.buildSystemMessage(sessionId, defaultSkillPrompt); - this.appendSessionMessage(sessionId, defaultSkillMessage); - const userMessage = this.buildUserMessage(sessionId, userPrompt); this.appendSessionMessage(sessionId, userMessage); diff --git a/src/tests/prompt.test.ts b/src/tests/prompt.test.ts index b7c9178..cc86712 100644 --- a/src/tests/prompt.test.ts +++ b/src/tests/prompt.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import * as fs from "fs"; import * as path from "path"; import { fileURLToPath } from "url"; -import { getSystemPrompt, getTools } from "../prompt"; +import { getDefaultSkillPrompt, getRuntimeContext, getSystemPrompt, getTools } from "../prompt"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); @@ -30,11 +30,39 @@ test("getSystemPrompt includes UpdatePlan docs", () => { assert.equal(prompt.includes("The `plan` argument is a markdown string, not an array of step objects."), true); }); -test("getSystemPrompt includes current date guidance", () => { +test("getSystemPrompt does not include runtime context", () => { + const prompt = getSystemPrompt("/tmp/project"); + assert.equal(prompt.includes("# Local Workspace Environment"), false); + assert.equal(prompt.includes('"root path": "/tmp/project"'), false); +}); + +test("getDefaultSkillPrompt loads default skill templates in order", () => { + const prompt = getDefaultSkillPrompt(); + const agentDriftIndex = prompt.indexOf(""); + const planIndex = prompt.indexOf(""); + + assert.notEqual(agentDriftIndex, -1); + assert.notEqual(planIndex, -1); + assert.equal(agentDriftIndex < planIndex, true); + assert.equal(prompt.includes("Use the skill documents below to assist the user:"), true); + assert.equal(prompt.includes('path="templates/skills/'), false); +}); + +test("getSystemPrompt does not include current date guidance", () => { const now = new Date(); const expected = `今天是${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日。随着对话的进行,时间在流逝。`; const prompt = getSystemPrompt("/tmp/project"); - assert.equal(prompt.includes(expected), true); + assert.equal(prompt.includes(expected), false); +}); + +test("getRuntimeContext includes current date and model guidance", () => { + const now = new Date(); + const expectedDate = `今天是${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日。随着对话的进行,时间在流逝。`; + const prompt = getRuntimeContext("/tmp/project", "deepseek-v4-pro"); + assert.equal(prompt.includes(expectedDate), true); + assert.equal(prompt.includes("当前LLM模型为deepseek-v4-pro,对话中可通过/model命令切换模型。"), true); + assert.equal(prompt.includes("# Local Workspace Environment"), true); + assert.equal(prompt.includes('"root path": "/tmp/project"'), true); }); test("getSystemPrompt renders Read docs for non-multimodal models", () => { @@ -47,6 +75,8 @@ test("runtime prompt assets live under templates", () => { assert.equal(fs.existsSync(path.join(repoRoot, "templates", "tools", "web-search.md")), true); assert.equal(fs.existsSync(path.join(repoRoot, "templates", "tools", "read.md.ejs")), true); assert.equal(fs.existsSync(path.join(repoRoot, "templates", "prompts", "init_command.md.ejs")), true); + assert.equal(fs.existsSync(path.join(repoRoot, "templates", "skills", "agent-drift-guard.md")), true); + assert.equal(fs.existsSync(path.join(repoRoot, "templates", "skills", "plan-and-execute.md")), true); assert.equal(fs.existsSync(path.join(repoRoot, "templates", "tools", "read.md")), false); assert.equal(fs.existsSync(path.join(repoRoot, "docs", "tools")), false); assert.equal(fs.existsSync(path.join(repoRoot, "docs", "prompts")), false); diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 7bc98f9..10e3b2c 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -609,6 +609,37 @@ test("createSession stores /init and sends the active .deepcode project AGENTS p assert.ok(!systemContents.includes("root project instructions")); }); +test("createSession appends default system prompts in prefix-cache-friendly order", async () => { + const workspace = createTempDir("deepcode-system-order-workspace-"); + const home = createTempDir("deepcode-system-order-home-"); + setHomeDir(home); + globalThis.fetch = (async () => ({ ok: true, text: async () => "" }) as Response) as typeof fetch; + + fs.writeFileSync(path.join(workspace, "AGENTS.md"), "root project instructions", "utf8"); + + const manager = createSessionManager(workspace, "machine-id-system-order"); + (manager as any).activateSession = async () => {}; + + const sessionId = await manager.createSession({ text: "hello" }); + const systemContents = manager + .listSessionMessages(sessionId) + .filter((message) => message.role === "system") + .map((message) => message.content ?? ""); + + assert.equal(systemContents.length >= 4, true); + assert.match(systemContents[0] ?? "", /# Available Tools/); + assert.doesNotMatch(systemContents[0] ?? "", /# Local Workspace Environment/); + assert.doesNotMatch(systemContents[0] ?? "", /当前LLM模型为test-model/); + assert.match(systemContents[1] ?? "", //); + assert.match(systemContents[1] ?? "", //); + assert.doesNotMatch(systemContents[1] ?? "", /path="templates\/skills\//); + assert.doesNotMatch(systemContents[1] ?? "", /当前LLM模型为test-model/); + assert.match(systemContents[2] ?? "", /# Local Workspace Environment/); + assert.match(systemContents[2] ?? "", /当前LLM模型为test-model/); + assert.match(systemContents[2] ?? "", new RegExp(escapeRegExp(`"root path": "${workspace}"`))); + assert.equal(systemContents[3], "root project instructions"); +}); + test("replySession stores /init and sends the active root project AGENTS path to the LLM", async () => { const workspace = createTempDir("deepcode-init-root-workspace-"); const home = createTempDir("deepcode-init-root-home-"); @@ -1686,6 +1717,10 @@ function createTempDir(prefix: string): string { return dir; } +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + async function flushPromises(): Promise { await new Promise((resolve) => setImmediate(resolve)); } diff --git a/templates/skills/agent-drift-guard.md b/templates/skills/agent-drift-guard.md new file mode 100644 index 0000000..c6711b1 --- /dev/null +++ b/templates/skills/agent-drift-guard.md @@ -0,0 +1,152 @@ +--- +name: agent-drift-guard +description: Detect and correct execution drift while working on user requests. Use when you are actively implementing, debugging, reviewing, or investigating and there is a risk of wandering beyond the user's goal, adding unrequested work, touching live systems, over-exploring, or ignoring repeated user boundary corrections. Especially useful during multi-step coding tasks, production-adjacent requests, ambiguous scopes, and anytime you should self-check whether it is still solving the requested problem. +--- + +# Agent Drift Guard + +Keep execution tightly aligned with the user's actual request. + +## Quick Start + +Run this mental check before substantial work and again whenever the plan expands: + +1. State the user's requested outcome in one sentence. +2. List explicit non-goals or boundaries the user has set. +3. Ask whether the next action directly advances the requested outcome. +4. If not, either cut it or pause to confirm. + +## Drift Signals + +Treat these as warning signs that execution may be drifting: + +- Exploring broadly before opening the most relevant file, command, or artifact. +- Solving adjacent operational issues when the user asked only for code changes. +- Adding extra safeguards, scripts, docs, refactors, or cleanup that the user did not ask for. +- Reframing the task around what seems "better" instead of what was requested. +- Continuing with a broader plan after the user narrows the scope. +- Repeating searches or tool calls without increasing certainty. +- Mixing diagnosis, remediation, and feature work when the user asked for only one of them. +- Touching production-like state, external systems, or live data without explicit permission. + +## Severity Levels + +### Level 1: Mild Drift + +Examples: +- One or two extra exploratory commands. +- Considering a broader solution but not acting on it yet. +- Briefly over-explaining instead of moving the task forward. + +Response: +- Auto-correct silently. +- Narrow to the smallest next action. +- Do not interrupt the user. + +### Level 2: Material Drift + +Examples: +- Planning additional deliverables not requested. +- Writing helper scripts, migrations, docs, or tests outside the asked scope. +- Expanding from code changes into operational fixes. +- Continuing after the user has already corrected the scope once. + +Response: +- Stop and realign internally first. +- If the broader action is avoidable, drop it and continue on scope. +- If the broader action has non-obvious tradeoffs, ask a brief confirmation question. + +### Level 3: Boundary or Risk Violation + +Examples: +- Modifying live systems, production data, external services, or user-owned state without being asked. +- Taking destructive or hard-to-reverse actions outside the requested scope. +- Ignoring repeated user instructions about what not to do. + +Response: +- Pause before acting. +- Surface the exact boundary and ask for confirmation. +- Offer the smallest on-scope option first. + +## Self-Check Loop + +Use this loop during execution: + +### Before the first meaningful action + +Write down mentally: +- Requested outcome +- Allowed scope +- Forbidden scope +- Smallest useful next step + +### After each non-trivial step + +Ask: +- Did this step directly help deliver the requested outcome? +- Did I learn something that changes scope, or only implementation? +- Am I about to do more than the user asked? + +### After a user correction + +Treat the correction as a hard boundary update. + +Then: +- Remove the old broader plan. +- Do not defend the discarded work. +- Continue from the narrowed scope. +- If needed, acknowledge briefly and move on. + +## Decision Rules + +Use these rules in order: + +1. Prefer the most direct artifact first. + - Open the relevant file before scanning the whole repo. + - Inspect the specific failing path before designing a general framework. + +2. Prefer the smallest complete fix. + - Solve the asked problem before improving related systems. + - Avoid bonus work unless it is required for correctness. + +3. Prefer internal correction over user interruption. + - If you can shrink back to scope confidently, do it. + - Ask only when the next step changes deliverables, risk, or ownership. + +4. Treat repeated user constraints as priority signals. + - A repeated instruction means your execution style is currently misaligned. + - Tighten scope immediately. + +5. Separate categories of work. + - Code change, investigation, production remediation, cleanup, and documentation are distinct tasks unless the user explicitly combines them. + +## Good Intervention Style + +When you must pause, keep it short and specific: + +- State the potential drift in one sentence. +- Name the tradeoff or boundary. +- Offer the smallest on-scope option first. + +Example: + +"Quick alignment check: I can keep this to the code fix only, or also add an ops cleanup step. I'll stick to the code fix unless you want both." + +## Anti-Patterns + +Do not: + +- Create cleanup scripts, docs, or side tools just because they seem useful. +- Broaden the task after discovering a neighboring problem. +- Continue with a plan the user has already rejected. +- Justify drift with "best practice" when the user asked for a narrower deliverable. +- Hide extra work inside a larger patch. + +## Final Check Before Responding + +Before sending the final answer, verify: + +- The delivered work matches the requested outcome. +- No extra deliverables were added without confirmation. +- Any assumptions are stated briefly. +- Suggested next steps are optional, not bundled into the completed work. diff --git a/templates/skills/plan-and-execute.md b/templates/skills/plan-and-execute.md new file mode 100644 index 0000000..9fc8bd2 --- /dev/null +++ b/templates/skills/plan-and-execute.md @@ -0,0 +1,246 @@ +--- +name: plan-and-execute +description: Automatically plan and execute requirements. Creates a markdown task list with the UpdatePlan tool, and systematically executes each task while updating progress. Use when working with task planning or when you need to break down and execute complex multi-step requirements. +--- + +# Plan and Execute + +This Skill helps you automatically plan and execute requirements. It creates a structured markdown task list with the UpdatePlan tool and systematically works through each task while keeping progress visible. + +## Quick Start + +When you need to work through a multi-step request: + +1. Analyze the requirements and explore enough project context +2. Clarify unclear or ambiguous requirements with AskUserQuestion +3. Create a markdown task list by calling the UpdatePlan tool +4. Execute tasks one by one, updating the tool plan in real time +5. Revise the remaining plan as new context appears + +## Instructions + +### Step 1: Analyze the requirements + +Identify the requirements from the available context. Explore the project enough to make the plan concrete and accurate. + +If the original requirements are unclear, incomplete, or ambiguous, call the AskUserQuestion tool before creating the task list. Ask only the questions needed to avoid implementing the wrong behavior, and keep each question specific to the decision that affects the plan or acceptance criteria. + +If a required referenced file path is missing, ask for it with AskUserQuestion: + +``` +What is the path to the referenced file? +``` + +Referenced files can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. If no additional file is needed, continue from the available requirements. + +- What are the main requirements? +- What tasks need to be completed? +- Are there dependencies between tasks? +- What is the complexity level? +- Which files, modules, commands, or tests are relevant? +- What ambiguity would change the implementation or acceptance criteria? + +### Step 2: Create the task list + +Create a structured markdown task list and pass it to the UpdatePlan tool as the `plan` string. The tool input must use this shape: + +```json +{ + "plan": "## Task List\n\n- [ ] Task 1 description\n- [ ] Task 2 description\n- [ ] Task 3 description" +} +``` + +Use this markdown format for the `plan` content: + +```markdown +## Task List + +- [ ] Task 1 description +- [ ] Task 2 description +- [ ] Task 3 description +``` + +Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. + +### Step 3: Execute tasks systematically + +For each task in the list: + +1. **Refresh the plan**: Before starting the first task and after completing each task, re-evaluate the latest conversation and project context. Update the remaining tasks when scope, order, blockers, or follow-up work changes. +2. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` +3. **Execute the task**: Use appropriate tools to complete the work +4. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished +5. **Move to next task**: Only ONE task should be in progress at a time + +Important rules: +- Always keep the plan aligned with the latest context before executing the next task +- Always call UpdatePlan BEFORE starting work on a task +- Always call UpdatePlan IMMEDIATELY after completing a task +- Always pass the complete current markdown task list, not a partial diff +- Never work on multiple tasks simultaneously +- Remove tasks that are no longer relevant, and add newly discovered tasks before working on them +- If you encounter errors, keep the task as `[>]` and create new tasks to resolve blockers + +### Step 4: Handle task breakdown + +If during execution you discover a task is more complex than expected: + +1. Keep the current task as `[>]` +2. Call UpdatePlan with new sub-tasks below it with indentation: + ```markdown + - [>] Main task + - [ ] Sub-task 1 + - [ ] Sub-task 2 + ``` +3. Complete sub-tasks first, then mark the main task as complete with UpdatePlan + +### Step 5: Final verification + +After all tasks are completed (`[x]`): + +1. Review the original requirements to ensure everything is addressed +2. Run any final checks (tests, builds, linting) +3. Call UpdatePlan with every task marked `[x]` +4. Provide a concise completion summary in the final response + +## Task State Symbols + +- `[ ]` - Pending +- `[>]` - In progress +- `[x]` - Completed +- `[!]` - Blocked + +## Examples + +### Example 1: Simple feature request + +**Example requirements:** +```markdown +# 新功能:添加深色模式切换 + +用户应该能够在浅色和深色主题之间切换。 +切换开关应放在设置页面中。 +``` + +**分析后的 UpdatePlan 调用:** +```markdown +## Task List + +- [ ] 在设置页面创建深色模式切换组件 +- [ ] 添加深色模式状态管理(context/store) +- [ ] 实现深色主题的 CSS-in-JS 样式 +- [ ] 更新现有组件以支持主题切换 +- [ ] 运行测试并验证功能 +``` + +**UpdatePlan call during execution:** +```markdown +## Task List + +- [x] 在设置页面创建深色模式切换组件 +- [>] 添加深色模式状态管理(context/store) +- [ ] 实现深色主题的 CSS-in-JS 样式 +- [ ] 更新现有组件以支持主题切换 +- [ ] 运行测试并验证功能 +``` + +### Example 2: Bug fix with investigation + +**Example requirements:** +```markdown +# Fix bug:登录表单提交时崩溃 + +当用户点击提交时,应用崩溃。 +错误信息:"Cannot read property 'email' of undefined" +``` + +**UpdatePlan call after analysis:** +```markdown +## Task List + +- [ ] 在本地复现缺陷 +- [ ] 调查登录表单组件中的错误 +- [ ] 定位 undefined email 属性的根本原因 +- [ ] 实施修复 +- [ ] 添加验证以防止类似问题 +- [ ] 使用各种输入测试修复 +- [ ] 更新错误处理 +``` + +## When to Use This Skill + +Use this Skill when: + +1. **Complex multi-step tasks** - Request requires 3+ distinct steps +2. **Feature implementation** - Building new functionality from requirements +3. **Bug fixing** - Need to investigate, fix, and verify +4. **Refactoring** - Multiple files or components need changes +5. **Detailed requirements** - Specifications need to be translated into concrete tasks +6. **Need progress tracking** - Want visible progress without editing source files + +## When NOT to Use This Skill + +Skip this Skill when: + +1. **Single simple task** - Just one straightforward action needed +2. **Trivial changes** - Quick fixes that don't need planning +3. **Informational requests** - User just wants explanation, not execution +4. **No execution requested** - User only wants brainstorming or a high-level explanation + +## Best Practices + +1. **Be specific with tasks**: "Add login button to navbar" not "Update UI" +2. **Keep tasks atomic**: Each task should be independently completable +3. **Update immediately**: Don't batch status updates, do them in real-time +4. **One task at a time**: Never mark multiple tasks as `[>]` +5. **Handle blockers**: If stuck, create new tasks to resolve the blocker +6. **Verify completion**: Only mark `[x]` when task is fully done + +## Advanced Usage + +### Handling dependencies + +When tasks have dependencies, order them properly: + +```markdown +- [ ] Create database schema +- [ ] Implement API endpoints (depends on schema) +- [ ] Build frontend forms (depends on API) +``` + +### Using sub-tasks + +For complex tasks, break them down: + +```markdown +- [>] Implement authentication system + - [x] Set up JWT library + - [>] Create login endpoint + - [ ] Create logout endpoint + - [ ] Add token refresh logic +``` + +### Adding notes + +Add implementation notes or findings: + +```markdown +- [x] Investigate performance issue + - Note: Found N+1 query in user loader + - Solution: Added dataloader batching +``` + +## Workflow Summary + +1. Analyze the requirements and relevant project context +2. Call AskUserQuestion if the original requirements are unclear or ambiguous +3. Call UpdatePlan with the structured markdown task list +4. Refresh the remaining plan before the first task +5. For each task: + - Update to `[>]` with UpdatePlan + - Execute the task + - Update to `[x]` with UpdatePlan + - Re-evaluate and revise remaining tasks before moving on +6. Call UpdatePlan with all tasks completed and summarize the result + +This approach keeps planning and progress tracking in the UpdatePlan display, leaving source materials unchanged unless the actual task requires editing them. From 486e649adbe93f4dd7db62a0b433bc54351d254a Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 16:29:20 +0800 Subject: [PATCH 050/129] feat: update createSession test to validate environment JSON structure and root path --- src/tests/session.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 10e3b2c..a178726 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -636,7 +636,10 @@ test("createSession appends default system prompts in prefix-cache-friendly orde assert.doesNotMatch(systemContents[1] ?? "", /当前LLM模型为test-model/); assert.match(systemContents[2] ?? "", /# Local Workspace Environment/); assert.match(systemContents[2] ?? "", /当前LLM模型为test-model/); - assert.match(systemContents[2] ?? "", new RegExp(escapeRegExp(`"root path": "${workspace}"`))); + const environmentJsonMatch = (systemContents[2] ?? "").match(/```json\n([\s\S]+?)\n```/); + assert.ok(environmentJsonMatch); + const environmentInfo = JSON.parse(environmentJsonMatch[1] ?? "{}") as { "root path"?: string }; + assert.equal(environmentInfo["root path"], workspace); assert.equal(systemContents[3], "root project instructions"); }); From 08ba8d34b298f045f0fd908317e543dcfa6644e6 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 18:05:10 +0800 Subject: [PATCH 051/129] feat: add file mention functionality with scanning and filtering capabilities --- src/tests/fileMentions.test.ts | 157 +++++++++++++ src/ui/App.tsx | 1 + src/ui/PromptInput.tsx | 110 ++++++++- src/ui/fileMentions.ts | 410 +++++++++++++++++++++++++++++++++ src/ui/index.ts | 9 + 5 files changed, 682 insertions(+), 5 deletions(-) create mode 100644 src/tests/fileMentions.test.ts create mode 100644 src/ui/fileMentions.ts diff --git a/src/tests/fileMentions.test.ts b/src/tests/fileMentions.test.ts new file mode 100644 index 0000000..57f078e --- /dev/null +++ b/src/tests/fileMentions.test.ts @@ -0,0 +1,157 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { + filterFileMentionItems, + formatFileMentionPath, + getCurrentFileMentionToken, + replaceCurrentFileMentionToken, + scanFileMentionItems, + type FileMentionItem, +} from "../ui/fileMentions"; + +test("getCurrentFileMentionToken detects bare @file tokens under the cursor", () => { + assert.deepEqual(getCurrentFileMentionToken({ text: "review @src/app.ts please", cursor: 10 }), { + query: "src/app.ts", + start: 7, + end: 18, + quoted: false, + }); + assert.deepEqual(getCurrentFileMentionToken({ text: "@", cursor: 1 }), { + query: "", + start: 0, + end: 1, + quoted: false, + }); + assert.equal(getCurrentFileMentionToken({ text: "foo@bar", cursor: 7 }), null); +}); + +test("getCurrentFileMentionToken supports quoted paths with spaces", () => { + assert.deepEqual(getCurrentFileMentionToken({ text: 'open @"docs/my file.md"', cursor: 22 }), { + query: "docs/my file.md", + start: 5, + end: 23, + quoted: true, + }); + assert.deepEqual(getCurrentFileMentionToken({ text: 'open @"docs/my', cursor: 14 }), { + query: "docs/my", + start: 5, + end: 14, + quoted: true, + }); + assert.equal(getCurrentFileMentionToken({ text: 'open @"docs/my file.md" now', cursor: 24 }), null); +}); + +test("formatFileMentionPath quotes only paths that need it", () => { + assert.equal(formatFileMentionPath("src/App.tsx"), "@src/App.tsx"); + assert.equal(formatFileMentionPath("docs/my file.md"), '@"docs/my file.md"'); + assert.equal(formatFileMentionPath('docs/a"b.md'), '@"docs/a\\"b.md"'); +}); + +test("replaceCurrentFileMentionToken inserts a trailing-space mention", () => { + const state = { text: "read @sr then", cursor: 8 }; + const token = getCurrentFileMentionToken(state); + assert.ok(token); + assert.deepEqual(replaceCurrentFileMentionToken(state, token, "src/index.ts"), { + text: "read @src/index.ts then", + cursor: 19, + }); + + const quotedState = { text: 'read @"doc', cursor: 10 }; + const quotedToken = getCurrentFileMentionToken(quotedState); + assert.ok(quotedToken); + assert.deepEqual(replaceCurrentFileMentionToken(quotedState, quotedToken, "docs/my file.md"), { + text: 'read @"docs/my file.md" ', + cursor: 24, + }); +}); + +test("filterFileMentionItems prioritizes prefix and basename matches", () => { + const items: FileMentionItem[] = [ + { path: "src/PromptInput.tsx", type: "file" }, + { path: "docs/prompt guide.md", type: "file" }, + { path: "templates/prompts/init.md", type: "file" }, + ]; + + assert.deepEqual( + filterFileMentionItems(items, "prompt").map((item) => item.path), + ["docs/prompt guide.md", "src/PromptInput.tsx", "templates/prompts/init.md"] + ); +}); + +test("scanFileMentionItems returns relative slash-separated files and directories", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.mkdirSync(path.join(root, "src")); + fs.writeFileSync(path.join(root, "src", "index.ts"), ""); + fs.mkdirSync(path.join(root, "node_modules")); + fs.writeFileSync(path.join(root, "node_modules", "ignored.js"), ""); + + assert.deepEqual( + scanFileMentionItems(root).map((item) => item.path), + ["node_modules/", "node_modules/ignored.js", "src/", "src/index.ts"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("scanFileMentionItems respects project gitignore patterns inside git repositories", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.mkdirSync(path.join(root, ".git")); + fs.mkdirSync(path.join(root, ".mypy_cache"), { recursive: true }); + fs.writeFileSync(path.join(root, ".mypy_cache", "ignored.json"), ""); + fs.mkdirSync(path.join(root, "tmp")); + fs.writeFileSync(path.join(root, "tmp", "ignored.txt"), ""); + fs.mkdirSync(path.join(root, "docs")); + fs.writeFileSync(path.join(root, "docs", "guide.md"), ""); + fs.writeFileSync(path.join(root, ".gitignore"), ".mypy_cache/\ntmp/\n"); + + assert.deepEqual( + scanFileMentionItems(root).map((item) => item.path), + ["docs/", "docs/guide.md", ".gitignore"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("scanFileMentionItems ignores gitignore files outside git repositories", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.mkdirSync(path.join(root, "tmp")); + fs.writeFileSync(path.join(root, "tmp", "visible.txt"), ""); + fs.writeFileSync(path.join(root, ".gitignore"), "tmp/\n"); + + assert.deepEqual( + scanFileMentionItems(root).map((item) => item.path), + ["tmp/", "tmp/visible.txt", ".gitignore"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("scanFileMentionItems applies parent and nested ignore files", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.mkdirSync(path.join(root, ".git")); + fs.writeFileSync(path.join(root, ".gitignore"), "ignored-from-parent/\n"); + fs.mkdirSync(path.join(root, "sub", "ignored-from-parent"), { recursive: true }); + fs.writeFileSync(path.join(root, "sub", "ignored-from-parent", "hidden.txt"), ""); + fs.mkdirSync(path.join(root, "sub", "nested", "ignored-from-nested"), { recursive: true }); + fs.writeFileSync(path.join(root, "sub", "nested", ".gitignore"), "ignored-from-nested/\n"); + fs.writeFileSync(path.join(root, "sub", "nested", "ignored-from-nested", "hidden.txt"), ""); + fs.writeFileSync(path.join(root, "sub", "nested", "visible.txt"), ""); + + assert.deepEqual( + scanFileMentionItems(path.join(root, "sub")).map((item) => item.path), + ["nested/", "nested/.gitignore", "nested/visible.txt"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index e56111f..8d8dca1 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -512,6 +512,7 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App /> ) : isExiting ? null : ( (null); const [modelDropdownIndex, setModelDropdownIndex] = useState(0); const [pendingModel, setPendingModel] = useState(null); + const [fileMentionIndex, setFileMentionIndex] = useState(0); + const [dismissedFileMentionKey, setDismissedFileMentionKey] = useState(null); const [historyCursor, setHistoryCursor] = useState(-1); const [draftBeforeHistory, setDraftBeforeHistory] = useState(null); const [hasTerminalFocus, setHasTerminalFocus] = useState(true); const lastCtrlDAt = React.useRef(0); const undoRedoRef = React.useRef(createPromptUndoRedoState()); + const fileMentionItems = React.useMemo(() => scanFileMentionItems(projectRoot), [projectRoot]); + const fileMentionToken = getCurrentFileMentionToken(buffer); + const fileMentionKey = fileMentionToken ? `${fileMentionToken.start}:${fileMentionToken.query}` : null; + const fileMentionMatches = React.useMemo( + () => (fileMentionToken ? filterFileMentionItems(fileMentionItems, fileMentionToken.query) : []), + [fileMentionItems, fileMentionToken] + ); + const showFileMentionMenu = + !showSkillsDropdown && + !modelDropdownStep && + fileMentionToken !== null && + fileMentionKey !== dismissedFileMentionKey; const slashItems = React.useMemo(() => buildSlashCommands(skills), [skills]); const slashToken = getCurrentSlashToken(buffer); const slashMenu = React.useMemo( () => - showSkillsDropdown || modelDropdownStep ? [] : slashToken ? filterSlashCommands(slashItems, slashToken) : [], - [showSkillsDropdown, modelDropdownStep, slashToken, slashItems] + showSkillsDropdown || modelDropdownStep || showFileMentionMenu + ? [] + : slashToken + ? filterSlashCommands(slashItems, slashToken) + : [], + [showSkillsDropdown, modelDropdownStep, showFileMentionMenu, slashToken, slashItems] ); const showMenu = slashMenu.length > 0; const promptHistoryKey = React.useMemo(() => promptHistory.join("\0"), [promptHistory]); @@ -153,7 +180,7 @@ export const PromptInput = React.memo(function PromptInput({ ? loadingText && loadingText.trim() ? `${loadingText}${processHint}` : `esc to interrupt · ctrl+c to cancel input${processHint}` - : `enter send · shift+enter newline · ctrl+v image · / commands · ctrl+d exit${processHint}`; + : `enter send · shift+enter newline · @ files · ctrl+v image · / commands · ctrl+d exit${processHint}`; useTerminalFocusReporting(stdout, !disabled); useTerminalExtendedKeys(stdout, !disabled); useHiddenTerminalCursor(stdout, !disabled); @@ -168,6 +195,22 @@ export const PromptInput = React.memo(function PromptInput({ } }, [slashMenu, showMenu, menuIndex]); + useEffect(() => { + if (!fileMentionKey) { + setDismissedFileMentionKey(null); + } + }, [fileMentionKey]); + + useEffect(() => { + if (!showFileMentionMenu) { + setFileMentionIndex(0); + return; + } + if (fileMentionIndex >= fileMentionMatches.length) { + setFileMentionIndex(Math.max(0, fileMentionMatches.length - 1)); + } + }, [fileMentionMatches.length, fileMentionIndex, showFileMentionMenu]); + useEffect(() => { if (skillsDropdownIndex >= skills.length) { setSkillsDropdownIndex(Math.max(0, skills.length - 1)); @@ -222,6 +265,10 @@ export const PromptInput = React.memo(function PromptInput({ setShowSkillsDropdown(false); return; } + if (showFileMentionMenu && fileMentionKey) { + setDismissedFileMentionKey(fileMentionKey); + return; + } if (busy) { onInterrupt(); setStatusMessage("Interrupting…"); @@ -353,6 +400,35 @@ export const PromptInput = React.memo(function PromptInput({ const returnAction = getPromptReturnKeyAction(key); const isPlainReturn = returnAction === "submit"; + if (showFileMentionMenu) { + if (key.upArrow) { + if (fileMentionMatches.length > 0) { + setFileMentionIndex((idx) => (idx - 1 + fileMentionMatches.length) % fileMentionMatches.length); + } + return; + } + if (key.downArrow) { + if (fileMentionMatches.length > 0) { + setFileMentionIndex((idx) => (idx + 1) % fileMentionMatches.length); + } + return; + } + if (key.tab || returnAction === "submit") { + const selected = fileMentionMatches[fileMentionIndex]; + if (selected && fileMentionToken) { + insertFileMentionSelection(selected); + return; + } + if (key.tab) { + setDismissedFileMentionKey(fileMentionKey); + return; + } + if (fileMentionKey) { + setDismissedFileMentionKey(fileMentionKey); + } + } + } + if (showMenu) { if (key.upArrow) { setMenuIndex((idx) => (idx - 1 + slashMenu.length) % slashMenu.length); @@ -585,6 +661,14 @@ export const PromptInput = React.memo(function PromptInput({ setHistoryCursor(nextCursor); } + function insertFileMentionSelection(item: FileMentionItem): void { + if (!fileMentionToken) { + return; + } + updateBuffer((state) => replaceCurrentFileMentionToken(state, fileMentionToken, item.path)); + setDismissedFileMentionKey(null); + } + function handleSlashSelection(item: SlashCommandItem): void { if (busy && item.kind !== "exit") { setStatusMessage("wait for the current response or press esc to interrupt"); @@ -760,8 +844,8 @@ export const PromptInput = React.memo(function PromptInput({ })); const showFooterText = useMemo( - () => showMenu || showSkillsDropdown || modelDropdownStep !== null, - [showMenu, showSkillsDropdown, modelDropdownStep] + () => showMenu || showSkillsDropdown || modelDropdownStep !== null || showFileMentionMenu, + [showMenu, showSkillsDropdown, modelDropdownStep, showFileMentionMenu] ); return ( @@ -830,6 +914,22 @@ export const PromptInput = React.memo(function PromptInput({ maxVisible={6} /> ) : null} + {showFileMentionMenu ? ( + ({ + key: item.path, + label: item.path, + description: item.type === "directory" ? "directory" : "file", + }))} + activeIndex={fileMentionIndex} + activeColor="#229ac3" + maxVisible={8} + /> + ) : null} {!showFooterText && ( diff --git a/src/ui/fileMentions.ts b/src/ui/fileMentions.ts new file mode 100644 index 0000000..cbacbe6 --- /dev/null +++ b/src/ui/fileMentions.ts @@ -0,0 +1,410 @@ +import * as fs from "fs"; +import * as path from "path"; +import ignore from "ignore"; +import type { PromptBufferState } from "./promptBuffer"; + +export type FileMentionItem = { + path: string; + type: "file" | "directory"; +}; + +export type FileMentionToken = { + query: string; + start: number; + end: number; + quoted: boolean; +}; + +const DEFAULT_MAX_ITEMS = 2000; +const DEFAULT_MAX_DEPTH = 8; + +type IgnoreMatcher = { + base: string; + matcher: ignore.Ignore; +}; + +export function scanFileMentionItems(root: string, maxItems = DEFAULT_MAX_ITEMS): FileMentionItem[] { + const items: FileMentionItem[] = []; + const seen = new Set(); + const gitRoot = findGitRoot(root); + const visitedDirectories = new Set(); + + function addItem(item: FileMentionItem): void { + if (items.length >= maxItems || seen.has(item.path)) { + return; + } + seen.add(item.path); + items.push(item); + } + + function visit(directory: string, depth: number, matchers: IgnoreMatcher[]): void { + if (items.length >= maxItems || depth > DEFAULT_MAX_DEPTH) { + return; + } + + const currentMatchers = [...matchers, ...loadDirectoryIgnoreMatchers(directory, gitRoot)]; + + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(directory, { withFileTypes: true }); + } catch { + return; + } + + entries.sort((a, b) => { + if (a.isDirectory() !== b.isDirectory()) { + return a.isDirectory() ? -1 : 1; + } + return a.name.localeCompare(b.name); + }); + + for (const entry of entries) { + if (items.length >= maxItems) { + return; + } + if (entry.name === "." || entry.name === ".." || entry.name === ".git") { + continue; + } + + const absolute = path.join(directory, entry.name); + const relative = toMentionPath(path.relative(root, absolute)); + if (!relative) { + continue; + } + + const entryType = getMentionEntryType(entry, absolute); + if (!entryType) { + continue; + } + + if (matchesAnyIgnore(absolute, entryType === "directory", currentMatchers)) { + continue; + } + + if (entryType === "directory") { + const realPath = safeRealpath(absolute); + if (realPath) { + if (visitedDirectories.has(realPath)) { + continue; + } + visitedDirectories.add(realPath); + } + addItem({ path: `${relative}/`, type: "directory" }); + visit(absolute, depth + 1, currentMatchers); + continue; + } + + if (entryType === "file") { + addItem({ path: relative, type: "file" }); + } + } + } + + const rootRealPath = safeRealpath(root); + if (rootRealPath) { + visitedDirectories.add(rootRealPath); + } + visit(root, 0, loadAncestorIgnoreMatchers(root, gitRoot)); + return items; +} + +function getMentionEntryType(entry: fs.Dirent, absolute: string): FileMentionItem["type"] | null { + if (entry.isDirectory()) { + return "directory"; + } + if (entry.isFile()) { + return "file"; + } + if (!entry.isSymbolicLink()) { + return null; + } + try { + const stat = fs.statSync(absolute); + if (stat.isDirectory()) { + return "directory"; + } + if (stat.isFile()) { + return "file"; + } + } catch { + return null; + } + return null; +} + +function safeRealpath(absolute: string): string | null { + try { + return fs.realpathSync(absolute); + } catch { + return null; + } +} + +function loadDirectoryIgnoreMatchers(directory: string, gitRoot: string | null): IgnoreMatcher[] { + const matchers: IgnoreMatcher[] = []; + if (gitRoot && isPathInsideOrEqual(directory, gitRoot)) { + const gitignoreMatcher = loadIgnoreFileMatcher(directory, path.join(directory, ".gitignore")); + if (gitignoreMatcher) { + matchers.push(gitignoreMatcher); + } + if (path.resolve(directory) === path.resolve(gitRoot)) { + const gitExcludeMatcher = loadIgnoreFileMatcher(directory, path.join(directory, ".git", "info", "exclude")); + if (gitExcludeMatcher) { + matchers.push(gitExcludeMatcher); + } + } + } + + const ignoreMatcher = loadIgnoreFileMatcher(directory, path.join(directory, ".ignore")); + if (ignoreMatcher) { + matchers.push(ignoreMatcher); + } + return matchers; +} + +function loadAncestorIgnoreMatchers(root: string, gitRoot: string | null): IgnoreMatcher[] { + const resolvedRoot = path.resolve(root); + const ancestors: string[] = []; + let current = path.dirname(resolvedRoot); + while (gitRoot && isPathInsideOrEqual(current, gitRoot)) { + ancestors.push(current); + if (path.resolve(current) === path.resolve(gitRoot)) { + break; + } + current = path.dirname(current); + } + return ancestors.reverse().flatMap((directory) => loadDirectoryIgnoreMatchers(directory, gitRoot)); +} + +function loadIgnoreFileMatcher(base: string, ignoreFilePath: string): IgnoreMatcher | null { + try { + if (!fs.existsSync(ignoreFilePath)) { + return null; + } + const content = fs.readFileSync(ignoreFilePath, "utf8"); + if (!content.trim()) { + return null; + } + return { base, matcher: ignore().add(content) }; + } catch { + return null; + } +} + +function matchesAnyIgnore(absolute: string, isDir: boolean, matchers: IgnoreMatcher[]): boolean { + let ignored = false; + for (const { base, matcher } of matchers) { + const relative = toMentionPath(path.relative(base, absolute)); + if (!relative || relative.startsWith("../")) { + continue; + } + const result = matcher.test(isDir ? `${relative}/` : relative); + if (result.ignored) { + ignored = true; + } + if (result.unignored) { + ignored = false; + } + } + return ignored; +} + +function findGitRoot(start: string): string | null { + let current = path.resolve(start); + while (true) { + if (fs.existsSync(path.join(current, ".git"))) { + return current; + } + const parent = path.dirname(current); + if (parent === current) { + return null; + } + current = parent; + } +} + +function isPathInsideOrEqual(candidate: string, parent: string): boolean { + const relative = path.relative(parent, candidate); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); +} + +export function filterFileMentionItems(items: FileMentionItem[], query: string, maxResults = 12): FileMentionItem[] { + const normalizedQuery = normalizeForSearch(query); + const scored = items + .map((item, index) => ({ item, index, score: scoreFileMention(item.path, normalizedQuery) })) + .filter((entry) => entry.score !== Number.POSITIVE_INFINITY) + .sort((a, b) => a.score - b.score || a.item.path.length - b.item.path.length || a.index - b.index); + + return scored.slice(0, maxResults).map((entry) => entry.item); +} + +export function getCurrentFileMentionToken(state: PromptBufferState): FileMentionToken | null { + const text = state.text; + const cursor = clampCursorToBoundary(text, state.cursor); + const quoted = getCurrentQuotedFileMentionToken(text, cursor); + if (quoted) { + return quoted; + } + return getCurrentBareFileMentionToken(text, cursor); +} + +export function replaceCurrentFileMentionToken( + state: PromptBufferState, + token: FileMentionToken, + selectedPath: string +): PromptBufferState { + const inserted = `${formatFileMentionPath(selectedPath)} `; + const end = token.end < state.text.length && isWhitespace(state.text[token.end] ?? "") ? token.end + 1 : token.end; + const text = `${state.text.slice(0, token.start)}${inserted}${state.text.slice(end)}`; + return { text, cursor: token.start + inserted.length }; +} + +export function formatFileMentionPath(filePath: string): string { + if (!/[\s"]/.test(filePath)) { + return `@${filePath}`; + } + return `@"${filePath.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +function getCurrentBareFileMentionToken(text: string, cursor: number): FileMentionToken | null { + const beforeCursor = text.slice(0, cursor); + const afterCursor = text.slice(cursor); + const start = findTokenStart(beforeCursor); + const end = cursor + findTokenEnd(afterCursor); + const token = text.slice(start, end); + + if (!token.startsWith("@") || token.startsWith('@"')) { + return null; + } + if (start > 0 && !isWhitespace(text[start - 1] ?? "")) { + return null; + } + return { query: token.slice(1), start, end, quoted: false }; +} + +function getCurrentQuotedFileMentionToken(text: string, cursor: number): FileMentionToken | null { + for (let index = cursor; index >= 0; index--) { + if (text[index] !== "@" || text[index + 1] !== '"') { + continue; + } + if (index > 0 && !isWhitespace(text[index - 1] ?? "")) { + continue; + } + + const closeQuote = findClosingQuote(text, index + 2); + if (closeQuote !== -1 && cursor > closeQuote) { + continue; + } + + const end = closeQuote === -1 ? cursor : closeQuote + 1; + return { + query: unescapeQuotedMentionQuery( + text.slice(index + 2, Math.min(cursor, closeQuote === -1 ? cursor : closeQuote)) + ), + start: index, + end, + quoted: true, + }; + } + return null; +} + +function findTokenStart(beforeCursor: string): number { + const whitespaceIndex = findLastWhitespaceIndex(beforeCursor); + return whitespaceIndex === -1 ? 0 : whitespaceIndex + 1; +} + +function findTokenEnd(afterCursor: string): number { + const whitespaceIndex = afterCursor.search(/\s/); + return whitespaceIndex === -1 ? afterCursor.length : whitespaceIndex; +} + +function findLastWhitespaceIndex(value: string): number { + for (let index = value.length - 1; index >= 0; index--) { + if (isWhitespace(value[index] ?? "")) { + return index; + } + } + return -1; +} + +function findClosingQuote(text: string, start: number): number { + let escaped = false; + for (let index = start; index < text.length; index++) { + const char = text[index]; + if (escaped) { + escaped = false; + continue; + } + if (char === "\\") { + escaped = true; + continue; + } + if (char === '"') { + return index; + } + } + return -1; +} + +function unescapeQuotedMentionQuery(query: string): string { + return query.replace(/\\(["\\])/g, "$1"); +} + +function clampCursorToBoundary(text: string, cursor: number): number { + return Math.max(0, Math.min(cursor, text.length)); +} + +function scoreFileMention(itemPath: string, normalizedQuery: string): number { + if (!normalizedQuery) { + return itemPath.endsWith("/") ? 5 : 10; + } + + const normalizedPath = normalizeForSearch(itemPath); + const normalizedBase = normalizeForSearch(path.posix.basename(itemPath.replace(/\/$/, ""))); + if (normalizedPath === normalizedQuery) { + return 0; + } + if (normalizedPath.startsWith(normalizedQuery)) { + return 1; + } + if (normalizedBase.startsWith(normalizedQuery)) { + return isQueryBoundary(normalizedBase[normalizedQuery.length] ?? "") ? 2 : 3; + } + const pathIndex = normalizedPath.indexOf(normalizedQuery); + if (pathIndex !== -1) { + return 20 + pathIndex; + } + const fuzzyScore = fuzzyMatchScore(normalizedPath, normalizedQuery); + return fuzzyScore === null ? Number.POSITIVE_INFINITY : 100 + fuzzyScore; +} + +function fuzzyMatchScore(value: string, query: string): number | null { + let valueIndex = 0; + let score = 0; + for (const char of query) { + const nextIndex = value.indexOf(char, valueIndex); + if (nextIndex === -1) { + return null; + } + score += nextIndex - valueIndex; + valueIndex = nextIndex + 1; + } + return score; +} + +function normalizeForSearch(value: string): string { + return value.trim().toLocaleLowerCase(); +} + +function isQueryBoundary(value: string): boolean { + return value === "" || /[\s._/-]/.test(value); +} + +function toMentionPath(value: string): string { + return value.split(path.sep).join("/"); +} + +function isWhitespace(value: string): boolean { + return /\s/.test(value); +} diff --git a/src/ui/index.ts b/src/ui/index.ts index 5b4ff8f..5bcde40 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -79,5 +79,14 @@ export { type SlashCommandKind, type SlashCommandItem, } from "./slashCommands"; +export { + filterFileMentionItems, + formatFileMentionPath, + getCurrentFileMentionToken, + replaceCurrentFileMentionToken, + scanFileMentionItems, + type FileMentionItem, + type FileMentionToken, +} from "./fileMentions"; export { findExpandedThinkingId } from "./thinkingState"; export { buildExitSummaryText } from "./exitSummary"; From 47d3c21abe3c3582d24e7c1109bdf19e0818c90d Mon Sep 17 00:00:00 2001 From: hcyang Date: Mon, 18 May 2026 18:13:34 +0800 Subject: [PATCH 052/129] =?UTF-8?q?feat(ui):=20=E6=B7=BB=E5=8A=A0=20/raw?= =?UTF-8?q?=20=E6=A8=A1=E5=BC=8F=E6=94=AF=E6=8C=81=E5=8F=8A=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E7=BB=84=E4=BB=B6=E5=92=8C=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 RawMode 功能,包括 Normal、Lite 和 Raw scrollback 模式 - App 组件中集成 RawMode 上下文及切换逻辑,支持在 Raw 模式下直接向 stdout 渲染消息 - 增加 RawModeExitPrompt 组件,支持按 ESC 退出原始模式 - 新增 RawModelDropdown 组件,提供原始模式选择下拉菜单 - 在 PromptInput 中集成原始模式选择交互及状态管理 - 调整消息视图实现,拆分 MessageView 到 compoments 目录,支持根据 RawMode 呈现不同内容 - 新建 AppContainer 组件,包装 App 并提供版本上下文和 RawModeProvider - 修改 SlashCommand 体系,支持内置 /raw 命令及对应测试覆盖 - 更新 cli 入口,使用 AppContainer 替换直接渲染 App,传递版本信息 - 移除旧 MessageView 文件,重构消息渲染逻辑 - 优化 SlashCommandMenu 显示,支持命令参数提示显示 - 更新相关测试,支持原始模式功能验证 --- src/cli.tsx | 4 +- src/tests/messageView.test.ts | 51 +-- src/tests/slashCommands.test.ts | 9 +- src/ui/App.tsx | 69 +++- src/ui/AppContainer.tsx | 21 ++ src/ui/MessageView.tsx | 355 ------------------ src/ui/PromptInput.tsx | 27 +- src/ui/SlashCommandMenu.tsx | 5 +- src/ui/WelcomeScreen.tsx | 11 +- src/ui/compoments/MessageView/index.tsx | 183 +++++++++ .../{ => compoments/MessageView}/markdown.ts | 0 src/ui/compoments/MessageView/types.ts | 19 + src/ui/compoments/MessageView/utils.ts | 255 +++++++++++++ src/ui/compoments/RawModeExitPrompt/index.tsx | 15 + src/ui/compoments/RawModelDropdown/index.tsx | 55 +++ src/ui/compoments/index.ts | 3 + src/ui/contexts/AppContext.tsx | 15 + src/ui/contexts/RawModeContext.tsx | 40 ++ src/ui/contexts/index.ts | 3 + src/ui/index.ts | 5 +- src/ui/slashCommands.ts | 22 +- 21 files changed, 750 insertions(+), 417 deletions(-) create mode 100644 src/ui/AppContainer.tsx delete mode 100644 src/ui/MessageView.tsx create mode 100644 src/ui/compoments/MessageView/index.tsx rename src/ui/{ => compoments/MessageView}/markdown.ts (100%) create mode 100644 src/ui/compoments/MessageView/types.ts create mode 100644 src/ui/compoments/MessageView/utils.ts create mode 100644 src/ui/compoments/RawModeExitPrompt/index.tsx create mode 100644 src/ui/compoments/RawModelDropdown/index.tsx create mode 100644 src/ui/compoments/index.ts create mode 100644 src/ui/contexts/AppContext.tsx create mode 100644 src/ui/contexts/RawModeContext.tsx create mode 100644 src/ui/contexts/index.ts diff --git a/src/cli.tsx b/src/cli.tsx index 435499a..e8e8659 100644 --- a/src/cli.tsx +++ b/src/cli.tsx @@ -1,8 +1,8 @@ import React from "react"; import { render } from "ink"; -import { App } from "./ui"; import { setShellIfWindows } from "./common/shell-utils"; import { checkForNpmUpdate, promptForPendingUpdate, type PackageInfo } from "./updateCheck"; +import AppContainer from "./ui/AppContainer"; const args = process.argv.slice(2); const packageInfo = readPackageInfo(); @@ -81,7 +81,7 @@ async function main(): Promise { const appInitialPrompt = initialPrompt; initialPrompt = undefined; const inkInstance = render( - { const lines = parseDiffPreview( @@ -25,45 +26,29 @@ test("parseDiffPreview keeps nonstandard context lines", () => { test("MessageView summarizes thinking content across lines", () => { assert.equal( - getThinkingParams({ - content: "Plan:\n\nInspect the code and update tests", - }), + buildThinkingSummary("Plan:\n\nInspect the code and update tests", null, RawMode.Lite), "Plan: Inspect the code and update tests" ); }); -test("MessageView removes a trailing colon from thinking summaries", () => { - assert.equal(getThinkingParams({ content: "Planning:" }), "Planning"); +test("MessageView removes a trailing colon from thinking summary", () => { + assert.equal(buildThinkingSummary("Planning:", null, RawMode.Lite), "Planning"); }); -test("MessageView falls back to a reasoning placeholder for hidden reasoning content", () => { +test("MessageView falls back to a reasoning placeholder for hidden reasoning content in Lite mode", () => { assert.equal( - getThinkingParams({ - content: "", - messageParams: { reasoning_content: "hidden chain of thought" }, - }), + buildThinkingSummary("", { reasoning_content: "hidden chain of thought" }, RawMode.Lite), "(reasoning...)" ); }); -function getThinkingParams(overrides: Partial): string { - const view = MessageView({ message: buildAssistantMessage(overrides) }) as any; - return view.props.children.props.params; -} - -function buildAssistantMessage(overrides: Partial): SessionMessage { - return { - id: "message-1", - sessionId: "session-1", - role: "assistant", - content: "", - contentParams: null, - messageParams: null, - compacted: false, - visible: true, - createTime: "2026-01-01T00:00:00.000Z", - updateTime: "2026-01-01T00:00:00.000Z", - meta: { asThinking: true }, - ...overrides, - }; -} +test("MessageView shows full reasoning content in Normal/Raw mode", () => { + assert.equal( + buildThinkingSummary("", { reasoning_content: "hidden chain of thought" }, RawMode.None), + "hidden chain of thought" + ); + assert.equal( + buildThinkingSummary("", { reasoning_content: "hidden chain of thought" }, RawMode.Raw), + "hidden chain of thought" + ); +}); diff --git a/src/tests/slashCommands.test.ts b/src/tests/slashCommands.test.ts index bba5244..34b48d0 100644 --- a/src/tests/slashCommands.test.ts +++ b/src/tests/slashCommands.test.ts @@ -19,7 +19,7 @@ test("buildSlashCommands prefixes skills before built-ins", () => { assert.equal(items[0].kind, "skill"); assert.equal(items[0].name, "skill-writer"); const builtinNames = items.filter((i) => i.kind !== "skill").map((i) => i.name); - assert.deepEqual(builtinNames, ["skills", "model", "new", "init", "resume", "continue", "mcp", "exit"]); + assert.deepEqual(builtinNames, ["skills", "model", "new", "init", "resume", "continue", "mcp", "raw", "exit"]); }); test("filterSlashCommands matches partial prefixes", () => { @@ -80,6 +80,13 @@ test("findExactSlashCommand returns built-in /model", () => { assert.equal(item?.kind, "model"); }); +test("findExactSlashCommand returns built-in /raw", () => { + const items = buildSlashCommands(skills); + const item = findExactSlashCommand(items, "/raw"); + assert.ok(item); + assert.equal(item?.kind, "raw"); +}); + test("findExactSlashCommand returns the matching skill", () => { const items = buildSlashCommands(skills); const item = findExactSlashCommand(items, "/code-review"); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index e56111f..1c9bac4 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -6,10 +6,10 @@ import * as os from "os"; import * as path from "path"; import OpenAI from "openai"; import { - SessionManager, type LlmStreamProgress, type MessageMeta, type SessionEntry, + SessionManager, type SessionMessage, type SessionStatus, type SkillInfo, @@ -17,13 +17,13 @@ import { } from "../session"; import { applyModelConfigSelection, - resolveSettingsSources, type DeepcodingSettings, type ModelConfigSelection, type ResolvedDeepcodingSettings, + resolveSettingsSources, } from "../settings"; import { PromptInput, type PromptSubmission } from "./PromptInput"; -import { MessageView } from "./MessageView"; +import { MessageView, RawModeExitPrompt } from "./compoments"; import { SessionList } from "./SessionList"; import { buildLoadingText } from "./loadingText"; import { findExpandedThinkingId } from "./thinkingState"; @@ -32,11 +32,13 @@ import { AskUserQuestionPrompt } from "./AskUserQuestionPrompt"; import { McpStatusList } from "./McpStatusList"; import { ProcessStdoutView } from "./ProcessStdoutView"; import { + type AskUserQuestionAnswers, findPendingAskUserQuestion, formatAskUserQuestionAnswers, - type AskUserQuestionAnswers, } from "./askUserQuestion"; import { buildExitSummaryText } from "./exitSummary"; +import { RawMode, useRawModeContext } from "./contexts"; +import { renderMessageToStdout } from "./compoments/MessageView/utils"; const DEFAULT_MODEL = "deepseek-v4-pro"; const DEFAULT_BASE_URL = "https://api.deepseek.com"; @@ -45,12 +47,11 @@ type View = "chat" | "session-list" | "mcp-status"; type AppProps = { projectRoot: string; - version?: string; initialPrompt?: string; onRestart?: () => void; }; -export function App({ projectRoot, version = "", initialPrompt, onRestart }: AppProps): React.ReactElement { +export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React.ReactElement { const { exit } = useApp(); const { stdout, write } = useStdout(); const { columns } = useWindowSize(); @@ -75,6 +76,10 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App const [showProcessStdout, setShowProcessStdout] = useState(false); const processStdoutRef = useRef>(new Map()); + const { mode, setMode } = useRawModeContext(); + const rawModeRef = useRef(mode); + rawModeRef.current = mode; + const messagesRef = useRef([]); messagesRef.current = messages; @@ -86,6 +91,10 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App renderMarkdown: (text) => text, onAssistantMessage: (message: SessionMessage) => { setMessages((prev) => [...prev, message]); + if (rawModeRef.current === RawMode.Raw) { + process.stdout.write("\n"); + process.stdout.write(renderMessageToStdout(message, rawModeRef.current) + "\n\n"); + } }, onSessionEntryUpdated: (entry) => { setStatusLine(buildStatusLine(entry)); @@ -362,6 +371,39 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App [sessionManager, refreshSkills] ); + const handleRawModeChange = useCallback( + (nextMode: string) => { + const activeSessionId = sessionManager.getActiveSessionId(); + if (!activeSessionId) { + return; + } + + setMode(nextMode as RawMode); + + // Clear screen to remove stale formatted text. + process.stdout.write("\u001B[2J\u001B[3J\u001B[H"); + + setTimeout(() => { + if (nextMode === RawMode.Raw) { + // Write all messages directly to stdout for raw scrollback mode. + const allMessages = loadVisibleMessages(sessionManager, activeSessionId); + for (const msg of allMessages) { + process.stdout.write("\n"); + process.stdout.write(renderMessageToStdout(msg, nextMode) + "\n\n"); + } + if (allMessages.length > 0) { + process.stdout.write("\n\n"); + process.stdout.write(chalk.dim("Press ESC to exit raw mode")); + } + } else { + // Switch to chat view to render messages. + handleSelectSession(activeSessionId); + } + }, 200); + }, + [handleSelectSession, sessionManager, setMode] + ); + const [stableColumns, setStableColumns] = useState(columns); useEffect(() => { const timer = setTimeout(() => setStableColumns(columns), 100); @@ -413,7 +455,7 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App // eslint-disable-next-line react-hooks/exhaustive-deps -- nowTick forces periodic recalculation for spinner animation [busy, streamProgress, runningProcesses, nowTick] ); - const welcomeSettings = resolvedSettings; + const welcomeItem: SessionMessage = useMemo( () => ({ id: `__welcome__${welcomeNonce}`, @@ -430,11 +472,14 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App [welcomeNonce] ); const staticItems = useMemo(() => { + if (mode === RawMode.Raw) { + return []; + } if (showWelcome && view === "chat") { return [welcomeItem, ...messages]; } return messages; - }, [showWelcome, view, messages, welcomeItem]); + }, [mode, showWelcome, view, messages, welcomeItem]); const handleQuestionAnswers = useCallback( (answers: AskUserQuestionAnswers) => { @@ -453,6 +498,10 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App setDismissedQuestionIds((prev) => new Set(prev).add(pendingQuestion.messageId)); }, [pendingQuestion]); + if (mode === RawMode.Raw) { + return handleRawModeChange(RawMode.None)} />; + } + return ( @@ -462,9 +511,8 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App ); @@ -521,6 +569,7 @@ export function App({ projectRoot, version = "", initialPrompt, onRestart }: App runningProcesses={runningProcesses} onSubmit={handleSubmit} onModelConfigChange={handleModelConfigChange} + onRawModeChange={handleRawModeChange} onInterrupt={handleInterrupt} onToggleProcessStdout={handleToggleProcessStdout} placeholder="Type your message..." diff --git a/src/ui/AppContainer.tsx b/src/ui/AppContainer.tsx new file mode 100644 index 0000000..e437b44 --- /dev/null +++ b/src/ui/AppContainer.tsx @@ -0,0 +1,21 @@ +import React from "react"; +import { AppContext } from "./contexts"; +import { App } from "./App"; +import { RawModeProvider } from "./contexts/RawModeContext"; + +const AppContainer: React.FC<{ + projectRoot: string; + version: string; + initialPrompt: string | undefined; + onRestart: () => void; +}> = ({ version, projectRoot, initialPrompt, onRestart }) => { + return ( + + + + + + ); +}; + +export default AppContainer; diff --git a/src/ui/MessageView.tsx b/src/ui/MessageView.tsx deleted file mode 100644 index c8793fc..0000000 --- a/src/ui/MessageView.tsx +++ /dev/null @@ -1,355 +0,0 @@ -import React from "react"; -import { Box, Text } from "ink"; -import { renderMarkdown } from "./markdown"; -import type { SessionMessage } from "../session"; - -type Props = { - message: SessionMessage; - collapsed?: boolean; - width?: number; -}; - -export function MessageView({ message, collapsed, width = 80 }: Props): React.ReactElement | null { - if (!message.visible) { - return null; - } - - if (message.role === "user") { - const text = message.content || "(no content)"; - return ( - - - {`>`} - - - {text} - {Array.isArray(message.contentParams) && message.contentParams.length > 0 ? ( - {` 📎 ${message.contentParams.length} image attachment(s)`} - ) : null} - - - ); - } - - if (message.role === "assistant") { - const isThinking = Boolean(message.meta?.asThinking); - const content = (message.content || "").trim(); - - if (isThinking) { - const summary = buildThinkingSummary(content, message.messageParams); - if (collapsed !== false) { - return ( - - - - ); - } - return ( - - - - {content ? {renderMarkdown(content)} : null} - - - ); - } - - const containerWidth = Math.max(1, width - 2); - const contentWidth = Math.max(1, width - 4); - - return ( - - - - - - {content ? {renderMarkdown(content)} : null} - - - ); - } - - if (message.role === "tool") { - const summary = buildToolSummary(message); - const diffLines = getToolDiffPreviewLines(summary); - return ( - - - {diffLines.length > 0 ? : null} - - ); - } - - if (message.role === "system") { - // Render model change messages in the same style as user commands. - if (message.meta?.isModelChange) { - return ( - - - {`>`} - - - {message.content} - - - ); - } - - if (message.meta?.skill) { - return ( - - ⚡ Loaded skill: {message.meta.skill.name} - - ); - } - if (message.meta?.isSummary) { - return ( - - - (conversation summary inserted) - - - ); - } - return null; - } - - return null; -} - -function StatusLine({ - bulletColor, - name, - params, -}: { - bulletColor: "gray" | "green" | "red"; - name: string; - params: string; -}): React.ReactElement { - return ( - - {[ - - ✧ - , - " ", - - {name} - , - params ? {` ${params}`} : null, - ]} - - ); -} - -function formatToolStatusParams(summary: ToolSummary): string { - const params = firstNonEmptyLine(summary.params); - return summary.name.toLowerCase() === "bash" ? params : truncate(params, 120); -} - -type ToolSummary = { - name: string; - params: string; - ok: boolean; - metadata: Record | null; -}; - -type DiffPreviewLine = { - marker: string; - content: string; - kind: "added" | "removed" | "context"; -}; - -function buildToolSummary(message: SessionMessage): ToolSummary { - const payload = parseToolPayload(message.content); - const metaFunctionName = - message.meta?.function && typeof (message.meta.function as { name?: unknown }).name === "string" - ? (message.meta.function as { name: string }).name - : null; - const name = payload.name || metaFunctionName || "tool"; - const params = - name === "AskUserQuestion" - ? extractAskUserQuestionParams(message) || getMetaParams(message) - : getMetaParams(message); - - return { - name, - params, - ok: payload.ok !== false, - metadata: payload.metadata, - }; -} - -function getMetaParams(message: SessionMessage): string { - return typeof message.meta?.paramsMd === "string" ? message.meta.paramsMd.trim() : ""; -} - -function extractAskUserQuestionParams(message: SessionMessage): string { - const fromFunction = extractQuestionsFromToolFunction(message.meta?.function); - if (fromFunction) { - return fromFunction; - } - - const params = getMetaParams(message); - if (!params) { - return ""; - } - - try { - const parsed = JSON.parse(params); - return extractQuestionsFromValue(parsed); - } catch { - return ""; - } -} - -function extractQuestionsFromToolFunction(toolFunction: unknown): string { - if (!toolFunction || typeof toolFunction !== "object") { - return ""; - } - const args = (toolFunction as { arguments?: unknown }).arguments; - if (typeof args !== "string" || !args.trim()) { - return ""; - } - try { - const parsed = JSON.parse(args); - return extractQuestionsFromValue((parsed as { questions?: unknown })?.questions); - } catch { - return ""; - } -} - -function extractQuestionsFromValue(value: unknown): string { - if (!Array.isArray(value)) { - return ""; - } - return value - .map((item) => { - if (!item || typeof item !== "object" || Array.isArray(item)) { - return ""; - } - return typeof (item as { question?: unknown }).question === "string" - ? (item as { question: string }).question.trim() - : ""; - }) - .filter(Boolean) - .join(" / "); -} - -function parseToolPayload(content: string | null): { - name: string | null; - ok: boolean; - metadata: Record | null; -} { - if (!content) { - return { name: null, ok: true, metadata: null }; - } - - try { - const parsed = JSON.parse(content) as { name?: unknown; ok?: unknown; metadata?: unknown }; - return { - name: typeof parsed.name === "string" && parsed.name.trim() ? parsed.name.trim() : null, - ok: parsed.ok !== false, - metadata: isPlainRecord(parsed.metadata) ? parsed.metadata : null, - }; - } catch { - return { name: null, ok: true, metadata: null }; - } -} - -function getToolDiffPreviewLines(summary: ToolSummary): DiffPreviewLine[] { - if (!summary.ok || !["edit", "write"].includes(summary.name.toLowerCase())) { - return []; - } - const diffPreview = summary.metadata?.diff_preview; - if (typeof diffPreview !== "string" || !diffPreview.trim()) { - return []; - } - return parseDiffPreview(diffPreview); -} - -export function parseDiffPreview(diffPreview: string): DiffPreviewLine[] { - return diffPreview - .split("\n") - .filter((line) => line && !line.startsWith("--- ") && !line.startsWith("+++ ") && !line.startsWith("@@ ")) - .map((line) => { - if (line.startsWith("+")) { - return { marker: "+", content: line.slice(1), kind: "added" }; - } - if (line.startsWith("-")) { - return { marker: "-", content: line.slice(1), kind: "removed" }; - } - return { - marker: " ", - content: line.startsWith(" ") ? line.slice(1) : line, - kind: "context", - }; - }); -} - -function DiffPreview({ lines }: { lines: DiffPreviewLine[] }): React.ReactElement { - return ( - - └ Changes - - {lines.map((line, index) => ( - - - {line.marker} - - - {line.content} - - - ))} - - - ); -} - -function isPlainRecord(value: unknown): value is Record { - return Boolean(value && typeof value === "object" && !Array.isArray(value)); -} - -function formatStatusName(value: string): string { - return value ? `${value.charAt(0).toUpperCase()}${value.slice(1)}` : "Tool"; -} - -function truncate(value: string, max: number): string { - if (value.length <= max) { - return value; - } - return `${value.slice(0, max)}…`; -} - -function firstNonEmptyLine(value: string): string { - for (const line of value.split(/\r?\n/)) { - const trimmed = line.trim().replace(/\s+/g, " "); - if (trimmed) { - return trimmed; - } - } - return ""; -} - -function buildThinkingSummary(content: string, messageParams: unknown | null): string { - if (content) { - const normalized = content.replace(/\r?\n/g, " ").replace(/\s+/g, " "); - let result = truncate(normalized, 100); - if (result.endsWith(":") || result.endsWith(":")) { - result = result.slice(0, -1); - } - return result; - } - - const params = messageParams as { reasoning_content?: unknown } | null | undefined; - if (typeof params?.reasoning_content === "string" && params.reasoning_content.trim()) { - return "(reasoning...)"; - } - - return ""; -} diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index affa9ad..c1cf335 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -43,6 +43,7 @@ import { useHiddenTerminalCursor, useTerminalExtendedKeys, useTerminalFocusRepor import SlashCommandMenu from "./SlashCommandMenu"; import type { ModelConfigSelection, ReasoningEffort } from "../settings"; import DropdownMenu from "./DropdownMenu"; +import { RawModelDropdown } from "./compoments"; export type PromptSubmission = { text: string; @@ -63,6 +64,7 @@ type Props = { runningProcesses?: Map | null; onSubmit: (submission: PromptSubmission) => void; onModelConfigChange: (selection: ModelConfigSelection) => string | Promise; + onRawModeChange?: (mode: string) => void; onInterrupt: () => void; onToggleProcessStdout?: () => void; }; @@ -116,6 +118,7 @@ export const PromptInput = React.memo(function PromptInput({ onModelConfigChange, onInterrupt, onToggleProcessStdout, + onRawModeChange, }: Props): React.ReactElement { const { exit } = useApp(); const { stdout } = useStdout(); @@ -126,6 +129,7 @@ export const PromptInput = React.memo(function PromptInput({ const [pendingExit, setPendingExit] = useState(false); const [menuIndex, setMenuIndex] = useState(0); const [showSkillsDropdown, setShowSkillsDropdown] = useState(false); + const [openRawModelDropdown, setOpenRawModelDropdown] = useState(false); const [skillsDropdownIndex, setSkillsDropdownIndex] = useState(0); const [modelDropdownStep, setModelDropdownStep] = useState(null); const [modelDropdownIndex, setModelDropdownIndex] = useState(0); @@ -271,6 +275,10 @@ export const PromptInput = React.memo(function PromptInput({ setPendingExit(false); } + if (openRawModelDropdown) { + return; + } + if (historyCursor !== -1 && !key.upArrow && !key.downArrow) { exitHistoryBrowsing(); } @@ -607,6 +615,11 @@ export const PromptInput = React.memo(function PromptInput({ openModelDropdown(); return; } + if (item.kind === "raw") { + clearSlashToken(); + setOpenRawModelDropdown(true); + return; + } if (item.kind === "new") { onSubmit({ text: "", imageUrls: [], command: "new" }); setBuffer(EMPTY_BUFFER); @@ -760,10 +773,13 @@ export const PromptInput = React.memo(function PromptInput({ })); const showFooterText = useMemo( - () => showMenu || showSkillsDropdown || modelDropdownStep !== null, - [showMenu, showSkillsDropdown, modelDropdownStep] + () => showMenu || showSkillsDropdown || openRawModelDropdown || modelDropdownStep !== null, + [showMenu, showSkillsDropdown, openRawModelDropdown, modelDropdownStep] ); + const matchedCommand = slashToken ? findExactSlashCommand(slashItems, slashToken) : null; + const inlineHint = matchedCommand?.args ? ` ${matchedCommand.args.join("|")}` : ""; + return ( {imageUrls.length > 0 ? ( @@ -791,7 +807,14 @@ export const PromptInput = React.memo(function PromptInput({ > {renderBufferWithCursor(buffer, !disabled && hasTerminalFocus, placeholder)} + {inlineHint ? {inlineHint} : null} + onRawModeChange?.(mode)} + screenWidth={screenWidth} + /> {showSkillsDropdown ? ( s.label.length)); + const longestLabel = Math.max(...items.map((s) => s.label.length + (s.args ? s.args?.join("|")?.length + 4 : 0))); const contentWidth = longestLabel + 2; // +2 for prefix "> " or " " const maxAllowed = Math.max(10, (width - 2) >> 1); // 容器50%宽度(减去gap),至少保留10列 return Math.min(contentWidth, maxAllowed); @@ -49,11 +49,12 @@ const SlashCommandMenu = React.memo(function SlashCommandMenu({ const actualIndex = visibleStart + idx; return ( - + {actualIndex === activeIndex ? "> " : " "} {formatSlashCommandLabel(item)} + {item.args ? {item.args.join("|")} : null} diff --git a/src/ui/WelcomeScreen.tsx b/src/ui/WelcomeScreen.tsx index 3d82eed..7e740d1 100644 --- a/src/ui/WelcomeScreen.tsx +++ b/src/ui/WelcomeScreen.tsx @@ -7,12 +7,12 @@ import type { ResolvedDeepcodingSettings } from "../settings"; import { buildSlashCommands, BUILTIN_SLASH_COMMANDS, formatSlashCommandDescription } from "./slashCommands"; import { ThemedGradient } from "./ThemedGradient"; import { AsciiLogo } from "../AsciiArt"; +import { useAppContext } from "./contexts"; type WelcomeScreenProps = { projectRoot: string; settings: ResolvedDeepcodingSettings; skills: SkillInfo[]; - version: string; width: number; }; @@ -28,13 +28,8 @@ const SHORTCUT_TIPS = [ { label: "Ctrl+D twice", description: "Quit Deep Code CLI" }, ]; -export function WelcomeScreen({ - projectRoot, - settings, - skills, - version, - width, -}: WelcomeScreenProps): React.ReactElement { +export function WelcomeScreen({ projectRoot, settings, skills, width }: WelcomeScreenProps): React.ReactElement { + const { version } = useAppContext(); const tips = useMemo(() => buildWelcomeTips(skills), [skills]); const [tipIndex] = useState(() => randomTipIndex(tips.length)); const compact = width < TITLE_PANEL_WIDTH + 42; diff --git a/src/ui/compoments/MessageView/index.tsx b/src/ui/compoments/MessageView/index.tsx new file mode 100644 index 0000000..9aa82fd --- /dev/null +++ b/src/ui/compoments/MessageView/index.tsx @@ -0,0 +1,183 @@ +import React from "react"; +import { Box, Text } from "ink"; +import { renderMarkdown } from "./markdown"; +import { + buildThinkingSummary, + buildToolSummary, + formatStatusName, + formatToolStatusParams, + getToolDiffPreviewLines, +} from "./utils"; +import type { DiffPreviewLine, MessageViewProps } from "./types"; +import { RawMode, useRawModeContext } from "../../contexts"; + +export function MessageView({ message, collapsed, width = 80 }: MessageViewProps): React.ReactElement | null { + const { mode } = useRawModeContext(); + if (!message.visible) { + return null; + } + + if (message.role === "user") { + const text = message.content || "(no content)"; + return ( + + + {`>`} + + + {text} + {Array.isArray(message.contentParams) && message.contentParams.length > 0 ? ( + {` 📎 ${message.contentParams.length} image attachment(s)`} + ) : null} + + + ); + } + + if (message.role === "assistant") { + const isThinking = Boolean(message.meta?.asThinking); + const content = (message.content || "").trim(); + + if (isThinking) { + const summary = buildThinkingSummary(content, message.messageParams, mode); + if (collapsed !== false) { + return ( + + + + ); + } + return ( + + + + {content ? {renderMarkdown(content)} : null} + + + ); + } + + const containerWidth = Math.max(1, width - 2); + const contentWidth = Math.max(1, width - 4); + + return ( + + + + + + {content ? {renderMarkdown(content)} : null} + + + ); + } + + if (message.role === "tool") { + const summary = buildToolSummary(message); + const diffLines = getToolDiffPreviewLines(summary); + return ( + + + {diffLines.length > 0 ? : null} + + ); + } + + if (message.role === "system") { + // Render model change messages in the same style as user commands. + if (message.meta?.isModelChange) { + return ( + + + {`>`} + + + {message.content} + + + ); + } + + if (message.meta?.skill) { + return ( + + ⚡ Loaded skill: {message.meta.skill.name} + + ); + } + if (message.meta?.isSummary) { + return ( + + + (conversation summary inserted) + + + ); + } + return null; + } + + return null; +} + +function StatusLine({ + bulletColor, + name, + params, + width, +}: { + bulletColor: "gray" | "green" | "red"; + name: string; + params: string; + width: number; +}): React.ReactElement { + const { mode } = useRawModeContext(); + const containerWidth = Math.max(1, width - 2); + const contentWidth = Math.max(1, width - 4); + return ( + + + + ✧ + + + + + + {name} + + {params ? ( + + {` ${params}`} + + ) : null} + + + + ); +} + +function DiffPreview({ lines }: { lines: DiffPreviewLine[] }): React.ReactElement { + return ( + + └ Changes + + {lines.map((line, index) => ( + + + {line.marker} + + + {line.content} + + + ))} + + + ); +} diff --git a/src/ui/markdown.ts b/src/ui/compoments/MessageView/markdown.ts similarity index 100% rename from src/ui/markdown.ts rename to src/ui/compoments/MessageView/markdown.ts diff --git a/src/ui/compoments/MessageView/types.ts b/src/ui/compoments/MessageView/types.ts new file mode 100644 index 0000000..743eb2d --- /dev/null +++ b/src/ui/compoments/MessageView/types.ts @@ -0,0 +1,19 @@ +import type { SessionMessage } from "../../../session"; + +export type MessageViewProps = { + message: SessionMessage; + collapsed?: boolean; + width?: number; +}; +export type ToolSummary = { + name: string; + params: string; + ok: boolean; + metadata: Record | null; +}; + +export type DiffPreviewLine = { + marker: string; + content: string; + kind: "added" | "removed" | "context"; +}; diff --git a/src/ui/compoments/MessageView/utils.ts b/src/ui/compoments/MessageView/utils.ts new file mode 100644 index 0000000..50a7b94 --- /dev/null +++ b/src/ui/compoments/MessageView/utils.ts @@ -0,0 +1,255 @@ +import type { DiffPreviewLine, ToolSummary } from "./types"; +import type { SessionMessage } from "../../../session"; +import { RawMode } from "../../contexts"; +import chalk from "chalk"; + +/** Type guard that checks whether a value is a plain object (not null, not an array). */ +export function isPlainRecord(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} + +/** Capitalizes the first character of a tool status name, falling back to "Tool". */ +export function formatStatusName(value: string): string { + return value ? `${value.charAt(0).toUpperCase()}${value.slice(1)}` : "Tool"; +} + +/** Truncates a string to the given maximum length, appending an ellipsis when truncated. */ +export function truncate(value: string, max: number): string { + if (value.length <= max) { + return value; + } + return `${value.slice(0, max)}…`; +} + +/** Returns the first non-empty line from a multi-line string, normalizing whitespace. */ +export function firstNonEmptyLine(value: string): string { + for (const line of value.split(/\r?\n/)) { + const trimmed = line.trim().replace(/\s+/g, " "); + if (trimmed) { + return trimmed; + } + } + return ""; +} + +/** + * Builds a one-line summary of thinking / reasoning content. + * Falls back to "(reasoning...)" when only reasoning_content params are present. + */ +export function buildThinkingSummary(content: string, messageParams: unknown | null, mode?: RawMode): string { + if (content) { + const normalized = content.replace(/\r?\n/g, " ").replace(/\s+/g, " "); + let result = truncate(normalized, 100); + if (result.endsWith(":") || result.endsWith(":")) { + result = result.slice(0, -1); + } + return result; + } + + const params = messageParams as { reasoning_content?: unknown } | null | undefined; + if (typeof params?.reasoning_content === "string" && params.reasoning_content.trim()) { + return mode !== RawMode.Lite ? params?.reasoning_content || "" : "(reasoning...)"; + } + + return ""; +} + +/** Formats a tool's parameters for status display, preserving full bash commands but truncating others. */ +export function formatToolStatusParams(summary: ToolSummary): string { + const params = firstNonEmptyLine(summary.params); + return summary.name.toLowerCase() === "bash" ? params : truncate(params, 120); +} + +/** Builds a structured summary (name, params, ok, metadata) from a tool session message. */ +export function buildToolSummary(message: SessionMessage): ToolSummary { + const payload = parseToolPayload(message.content); + const metaFunctionName = + message.meta?.function && typeof (message.meta.function as { name?: unknown }).name === "string" + ? (message.meta.function as { name: string }).name + : null; + const name = payload.name || metaFunctionName || "tool"; + const params = + name === "AskUserQuestion" + ? extractAskUserQuestionParams(message) || getMetaParams(message) + : getMetaParams(message); + + return { + name, + params, + ok: payload.ok !== false, + metadata: payload.metadata, + }; +} + +/** Extracts the paramsMd field from a session message's metadata, trimmed. */ +export function getMetaParams(message: SessionMessage): string { + return typeof message.meta?.paramsMd === "string" ? message.meta.paramsMd.trim() : ""; +} + +/** + * Extracts human-readable question text from an AskUserQuestion tool message. + * Tries the tool function arguments first, then falls back to parsing metadata params. + */ +export function extractAskUserQuestionParams(message: SessionMessage): string { + const fromFunction = extractQuestionsFromToolFunction(message.meta?.function); + if (fromFunction) { + return fromFunction; + } + + const params = getMetaParams(message); + if (!params) { + return ""; + } + + try { + const parsed = JSON.parse(params); + return extractQuestionsFromValue(parsed); + } catch { + return ""; + } +} + +/** + * Extracts question strings from a tool function object by parsing its JSON arguments. + */ +export function extractQuestionsFromToolFunction(toolFunction: unknown): string { + if (!toolFunction || typeof toolFunction !== "object") { + return ""; + } + const args = (toolFunction as { arguments?: unknown }).arguments; + if (typeof args !== "string" || !args.trim()) { + return ""; + } + try { + const parsed = JSON.parse(args); + return extractQuestionsFromValue((parsed as { questions?: unknown })?.questions); + } catch { + return ""; + } +} + +/** Extracts and joins question strings from an array of question objects. */ +export function extractQuestionsFromValue(value: unknown): string { + if (!Array.isArray(value)) { + return ""; + } + return value + .map((item) => { + if (!item || typeof item !== "object" || Array.isArray(item)) { + return ""; + } + return typeof (item as { question?: unknown }).question === "string" + ? (item as { question: string }).question.trim() + : ""; + }) + .filter(Boolean) + .join(" / "); +} + +/** Parses a tool's JSON payload, extracting name, ok flag, and metadata. */ +export function parseToolPayload(content: string | null): { + name: string | null; + ok: boolean; + metadata: Record | null; +} { + if (!content) { + return { name: null, ok: true, metadata: null }; + } + + try { + const parsed = JSON.parse(content) as { name?: unknown; ok?: unknown; metadata?: unknown }; + return { + name: typeof parsed.name === "string" && parsed.name.trim() ? parsed.name.trim() : null, + ok: parsed.ok !== false, + metadata: isPlainRecord(parsed.metadata) ? parsed.metadata : null, + }; + } catch { + return { name: null, ok: true, metadata: null }; + } +} + +/** + * Returns structured diff preview lines for successful edit or write tool calls. + * Returns an empty array if the tool is not edit/write or has no diff_preview metadata. + */ +export function getToolDiffPreviewLines(summary: ToolSummary): DiffPreviewLine[] { + if (!summary.ok || !["edit", "write"].includes(summary.name.toLowerCase())) { + return []; + } + const diffPreview = summary.metadata?.diff_preview; + if (typeof diffPreview !== "string" || !diffPreview.trim()) { + return []; + } + return parseDiffPreview(diffPreview); +} + +/** Parses a unified-diff-style preview string into an array of structured diff lines. */ +export function parseDiffPreview(diffPreview: string): DiffPreviewLine[] { + return diffPreview + .split("\n") + .filter((line) => line && !line.startsWith("--- ") && !line.startsWith("+++ ") && !line.startsWith("@@ ")) + .map((line) => { + if (line.startsWith("+")) { + return { marker: "+", content: line.slice(1), kind: "added" }; + } + if (line.startsWith("-")) { + return { marker: "-", content: line.slice(1), kind: "removed" }; + } + return { + marker: " ", + content: line.startsWith(" ") ? line.slice(1) : line, + kind: "context", + }; + }); +} + +export function renderMessageToStdout(message: SessionMessage, mode: RawMode): string { + if (!message.visible) { + return ""; + } + + if (message.role === "user") { + const text = message.content || "(no content)"; + return chalk(`> ${text}`); + } + + if (message.role === "assistant") { + const isThinking = Boolean(message.meta?.asThinking); + const content = (message.content || "").trim(); + + if (isThinking) { + const summary = buildThinkingSummary(content, message.messageParams, mode); + return `${chalk("✧")} ${chalk("Thinking")}${summary ? ` ${chalk(summary)}` : ""}`; + } + + return `${chalk("✦")} ${content}`; + } + + if (message.role === "tool") { + const payload = parseToolPayload(message.content); + const metaFunctionName = + message.meta?.function && typeof (message.meta.function as { name?: unknown }).name === "string" + ? (message.meta.function as { name: string }).name + : null; + const name = payload.name || metaFunctionName || "tool"; + const metaParams = typeof message.meta?.paramsMd === "string" ? message.meta.paramsMd.trim() : ""; + const params = name.toLowerCase() === "bash" ? metaParams : truncate(metaParams, 120); + return `${chalk("✧")} ${chalk(formatStatusName(name))}${params ? ` ${chalk(params)}` : ""}`; + } + + if (message.role === "system") { + if (message.meta?.isModelChange) { + return chalk(`> ${message.content}`); + } + if (message.meta?.skill && typeof message.meta.skill === "object") { + const skillName = (message.meta.skill as { name?: unknown }).name; + return chalk(`⚡ Loaded skill: ${typeof skillName === "string" ? skillName : ""}`); + } + if (message.meta?.isSummary) { + return chalk.dim.italic("(conversation summary inserted)"); + } + return ""; + } + + return ""; +} diff --git a/src/ui/compoments/RawModeExitPrompt/index.tsx b/src/ui/compoments/RawModeExitPrompt/index.tsx new file mode 100644 index 0000000..9b1d218 --- /dev/null +++ b/src/ui/compoments/RawModeExitPrompt/index.tsx @@ -0,0 +1,15 @@ +import type React from "react"; +import { useInput } from "ink"; + +export function RawModeExitPrompt({ onExit }: { onExit: () => void }): React.ReactElement | null { + useInput( + (_input, key) => { + if (key.escape) { + onExit(); + } + }, + { isActive: true } + ); + + return null; +} diff --git a/src/ui/compoments/RawModelDropdown/index.tsx b/src/ui/compoments/RawModelDropdown/index.tsx new file mode 100644 index 0000000..3397013 --- /dev/null +++ b/src/ui/compoments/RawModelDropdown/index.tsx @@ -0,0 +1,55 @@ +import React, { useState } from "react"; +import { useInput } from "ink"; +import DropdownMenu from "../../DropdownMenu"; +import type { RawMode } from "../../contexts"; +import { RAW_COMMAND_MODELS, useRawModeContext } from "../../contexts"; + +const RawModelDropdown: React.FC<{ + open: boolean; + screenWidth: number; + onClose?: (value: boolean) => void; + onSelect?: (model: string) => void; +}> = ({ open = false, screenWidth, onSelect, onClose }) => { + const { mode, setMode } = useRawModeContext(); + const [index, setIndex] = useState(0); + useInput( + (input, key) => { + if (key.upArrow) { + setIndex((i) => Math.max(0, i - 1)); + return; + } + if (key.downArrow) { + setIndex((i) => Math.min(RAW_COMMAND_MODELS.length - 1, i + 1)); + return; + } + if ((input === " " && !key.ctrl && !key.meta) || (key.return && !key.shift && !key.meta)) { + setMode(RAW_COMMAND_MODELS[index].key as RawMode); + onClose?.(false); + onSelect?.(RAW_COMMAND_MODELS[index].key); + return; + } + if (key.escape) { + onClose?.(false); + return; + } + }, + { isActive: open } + ); + if (!open) { + return null; + } + return ( + ({ ...model, selected: model.key === mode }))} + helpText="Space/Enter select mode · Esc to close" + // onSelect={onSelect} + activeColor="#229ac3" + maxVisible={6} + activeIndex={index} + width={screenWidth} + /> + ); +}; + +export default RawModelDropdown; diff --git a/src/ui/compoments/index.ts b/src/ui/compoments/index.ts new file mode 100644 index 0000000..942d3ed --- /dev/null +++ b/src/ui/compoments/index.ts @@ -0,0 +1,3 @@ +export { default as RawModelDropdown } from "./RawModelDropdown"; +export { MessageView } from "./MessageView"; +export { RawModeExitPrompt } from "./RawModeExitPrompt"; diff --git a/src/ui/contexts/AppContext.tsx b/src/ui/contexts/AppContext.tsx new file mode 100644 index 0000000..34d4589 --- /dev/null +++ b/src/ui/contexts/AppContext.tsx @@ -0,0 +1,15 @@ +import { createContext, useContext } from "react"; + +export interface AppState { + version: string; +} + +export const AppContext = createContext(null); + +export const useAppContext = () => { + const context = useContext(AppContext); + if (!context) { + throw new Error("useAppContext must be used within an AppProvider"); + } + return context; +}; diff --git a/src/ui/contexts/RawModeContext.tsx b/src/ui/contexts/RawModeContext.tsx new file mode 100644 index 0000000..a7b6090 --- /dev/null +++ b/src/ui/contexts/RawModeContext.tsx @@ -0,0 +1,40 @@ +import React, { createContext, useContext, useState } from "react"; +import type { DropdownMenuItem } from "../DropdownMenu"; + +export enum RawMode { + None = "Normal mode", + Lite = "Lite mode", + Raw = "Raw scrollback mode", +} +export const RAW_COMMAND_MODELS: DropdownMenuItem[] = [ + { + label: "Lite mode", + key: RawMode.Lite, + }, + { + label: "Raw scrollback mode", + key: RawMode.Raw, + }, + { + label: "Normal mode", + key: RawMode.None, + }, +] as const; + +const RawModeContext = createContext<{ mode: RawMode; setMode: React.Dispatch> }>({ + mode: RawMode.Lite, + setMode: () => {}, +}); + +export function useRawModeContext() { + const context = useContext(RawModeContext); + if (!context) { + throw new Error("useRawModeContext must be used within a RawModeProvider"); + } + return context; +} + +export const RawModeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { + const [mode, setMode] = useState(RawMode.Lite); + return {children}; +}; diff --git a/src/ui/contexts/index.ts b/src/ui/contexts/index.ts new file mode 100644 index 0000000..37e40cd --- /dev/null +++ b/src/ui/contexts/index.ts @@ -0,0 +1,3 @@ +export { AppContext, useAppContext } from "./AppContext"; +export type { AppState } from "./AppContext"; +export { RawMode, RAW_COMMAND_MODELS, useRawModeContext, RawModeProvider } from "./RawModeContext"; diff --git a/src/ui/index.ts b/src/ui/index.ts index 5b4ff8f..dd99330 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -9,7 +9,8 @@ export { createOpenAIClient, } from "./App"; export { AskUserQuestionPrompt } from "./AskUserQuestionPrompt"; -export { MessageView, parseDiffPreview } from "./MessageView"; +export { MessageView } from "./compoments"; +export { parseDiffPreview } from "./compoments/MessageView/utils"; export { PromptInput, IMAGE_ATTACHMENT_CLEAR_HINT, @@ -47,7 +48,7 @@ export { } from "./askUserQuestion"; export { readClipboardImage, type ClipboardImage } from "./clipboard"; export { buildLoadingText, type LoadingTextInput } from "./loadingText"; -export { renderMarkdown } from "./markdown"; +export { renderMarkdown } from "./compoments/MessageView/markdown"; export { EMPTY_BUFFER, insertText, diff --git a/src/ui/slashCommands.ts b/src/ui/slashCommands.ts index 6552ba0..aab06bd 100644 --- a/src/ui/slashCommands.ts +++ b/src/ui/slashCommands.ts @@ -1,6 +1,16 @@ import type { SkillInfo } from "../session"; -export type SlashCommandKind = "skill" | "skills" | "model" | "new" | "init" | "resume" | "continue" | "mcp" | "exit"; +export type SlashCommandKind = + | "skill" + | "skills" + | "model" + | "new" + | "init" + | "resume" + | "continue" + | "mcp" + | "raw" + | "exit"; export type SlashCommandItem = { kind: SlashCommandKind; @@ -8,6 +18,7 @@ export type SlashCommandItem = { label: string; description: string; skill?: SkillInfo; + args?: string[]; }; export const BUILTIN_SLASH_COMMANDS: SlashCommandItem[] = [ @@ -53,6 +64,13 @@ export const BUILTIN_SLASH_COMMANDS: SlashCommandItem[] = [ label: "/mcp", description: "Show MCP server status and available tools", }, + { + kind: "raw", + name: "raw", + label: "/raw", + args: ["lite", "normal", "raw-scrollback"], + description: "Toggle display mode for viewing or collapsing reasoning content", + }, { kind: "exit", name: "exit", @@ -88,7 +106,7 @@ export function findExactSlashCommand(items: SlashCommandItem[], token: string): return null; } const query = token.slice(1); - const matches = items.filter((item) => item.name === query); + const matches = items.filter((item) => item.name.includes(query)); return matches.find((item) => item.kind !== "skill") ?? matches[0] ?? null; } From f69ef03394cccf42f019fa22b0bf19bb4a42a09e Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 18:45:17 +0800 Subject: [PATCH 053/129] feat: enhance file mention handling in PromptInput with dynamic updates --- src/tests/fileMentions.test.ts | 115 +++++++++++++++++++++++++++++++++ src/ui/PromptInput.tsx | 42 +++++++++++- 2 files changed, 156 insertions(+), 1 deletion(-) diff --git a/src/tests/fileMentions.test.ts b/src/tests/fileMentions.test.ts index 57f078e..b382eee 100644 --- a/src/tests/fileMentions.test.ts +++ b/src/tests/fileMentions.test.ts @@ -155,3 +155,118 @@ test("scanFileMentionItems applies parent and nested ignore files", () => { fs.rmSync(root, { recursive: true, force: true }); } }); + +test("scanFileMentionItems applies git info exclude at the repository root", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.mkdirSync(path.join(root, ".git", "info"), { recursive: true }); + fs.writeFileSync(path.join(root, ".git", "info", "exclude"), "secret.txt\n"); + fs.writeFileSync(path.join(root, "secret.txt"), ""); + fs.writeFileSync(path.join(root, "visible.txt"), ""); + + assert.deepEqual( + scanFileMentionItems(root).map((item) => item.path), + ["visible.txt"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("scanFileMentionItems applies .ignore files outside git repositories", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.writeFileSync(path.join(root, ".ignore"), "ignored.txt\n"); + fs.writeFileSync(path.join(root, "ignored.txt"), ""); + fs.writeFileSync(path.join(root, "visible.txt"), ""); + + assert.deepEqual( + scanFileMentionItems(root).map((item) => item.path), + [".ignore", "visible.txt"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("scanFileMentionItems honors gitignore negation patterns", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.mkdirSync(path.join(root, ".git")); + fs.writeFileSync(path.join(root, ".gitignore"), "*.log\n!important.log\n"); + fs.writeFileSync(path.join(root, "debug.log"), ""); + fs.writeFileSync(path.join(root, "important.log"), ""); + + assert.deepEqual( + scanFileMentionItems(root).map((item) => item.path), + [".gitignore", "important.log"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("scanFileMentionItems includes hidden entries except the .git directory", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.mkdirSync(path.join(root, ".git")); + fs.writeFileSync(path.join(root, ".env"), ""); + fs.mkdirSync(path.join(root, ".config")); + fs.writeFileSync(path.join(root, ".config", "settings.json"), ""); + + assert.deepEqual( + scanFileMentionItems(root).map((item) => item.path), + [".config/", ".config/settings.json", ".env"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("scanFileMentionItems sees files created after an earlier scan", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + assert.deepEqual(scanFileMentionItems(root), []); + + fs.writeFileSync(path.join(root, "index.html"), ""); + + assert.deepEqual(scanFileMentionItems(root), [{ path: "index.html", type: "file" }]); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("scanFileMentionItems follows symlinked files", (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.writeFileSync(path.join(root, "source.txt"), ""); + try { + fs.symlinkSync(path.join(root, "source.txt"), path.join(root, "alias.txt")); + } catch { + t.skip("symlink creation is not available in this environment"); + return; + } + + assert.deepEqual( + scanFileMentionItems(root).map((item) => item.path), + ["alias.txt", "source.txt"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("filterFileMentionItems returns newly scanned files for @ mention queries", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-file-mentions-")); + try { + fs.writeFileSync(path.join(root, "index.html"), ""); + const items = scanFileMentionItems(root); + + assert.deepEqual( + filterFileMentionItems(items, "index").map((item) => item.path), + ["index.html"] + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index c9e4c47..0387ceb 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -139,6 +139,7 @@ export const PromptInput = React.memo(function PromptInput({ const [modelDropdownStep, setModelDropdownStep] = useState(null); const [modelDropdownIndex, setModelDropdownIndex] = useState(0); const [pendingModel, setPendingModel] = useState(null); + const [fileMentionItems, setFileMentionItems] = useState(() => scanFileMentionItems(projectRoot)); const [fileMentionIndex, setFileMentionIndex] = useState(0); const [dismissedFileMentionKey, setDismissedFileMentionKey] = useState(null); const [historyCursor, setHistoryCursor] = useState(-1); @@ -146,9 +147,11 @@ export const PromptInput = React.memo(function PromptInput({ const [hasTerminalFocus, setHasTerminalFocus] = useState(true); const lastCtrlDAt = React.useRef(0); const undoRedoRef = React.useRef(createPromptUndoRedoState()); + const wasBusyRef = React.useRef(busy); + const hadFileMentionTokenRef = React.useRef(false); - const fileMentionItems = React.useMemo(() => scanFileMentionItems(projectRoot), [projectRoot]); const fileMentionToken = getCurrentFileMentionToken(buffer); + const hasFileMentionToken = fileMentionToken !== null; const fileMentionKey = fileMentionToken ? `${fileMentionToken.start}:${fileMentionToken.query}` : null; const fileMentionMatches = React.useMemo( () => (fileMentionToken ? filterFileMentionItems(fileMentionItems, fileMentionToken.query) : []), @@ -185,6 +188,28 @@ export const PromptInput = React.memo(function PromptInput({ useTerminalExtendedKeys(stdout, !disabled); useHiddenTerminalCursor(stdout, !disabled); + const refreshFileMentionItems = React.useCallback(() => { + setFileMentionItems(scanFileMentionItems(projectRoot)); + }, [projectRoot]); + + useEffect(() => { + refreshFileMentionItems(); + }, [refreshFileMentionItems]); + + useEffect(() => { + if (wasBusyRef.current && !busy) { + refreshFileMentionItems(); + } + wasBusyRef.current = busy; + }, [busy, refreshFileMentionItems]); + + useEffect(() => { + if (hasFileMentionToken && !hadFileMentionTokenRef.current) { + refreshFileMentionItems(); + } + hadFileMentionTokenRef.current = hasFileMentionToken; + }, [hasFileMentionToken, refreshFileMentionItems]); + useEffect(() => { if (!showMenu) { setMenuIndex(0); @@ -928,6 +953,21 @@ export const PromptInput = React.memo(function PromptInput({ activeIndex={fileMentionIndex} activeColor="#229ac3" maxVisible={8} + renderItem={(item, isActive) => ( + + {isActive ? "> " : " "} + + + {item.label} + + + {item.description ? ( + + {item.description} + + ) : null} + + )} /> ) : null} From 67e2066b73f7e2d1b172e1e053d44009bcb7be0a Mon Sep 17 00:00:00 2001 From: hcyang Date: Mon, 18 May 2026 20:20:26 +0800 Subject: [PATCH 054/129] =?UTF-8?q?feat(MessageView):=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E7=8A=B6=E6=80=81=E8=A1=8C=E7=9A=84=20Plan?= =?UTF-8?q?=20Message=20=E9=A2=84=E8=A7=88=E6=98=BE=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 提取状态行文本为 statusLine 变量 - 创建 ToolSummary 对象汇总工具信息 - 获取并渲染更新计划的预览行 - 当有计划内容时,追加显示计划标题和内容 - 保持无计划时返回单行状态信息 --- src/ui/compoments/MessageView/utils.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/ui/compoments/MessageView/utils.ts b/src/ui/compoments/MessageView/utils.ts index a6ca4f6..45eb79c 100644 --- a/src/ui/compoments/MessageView/utils.ts +++ b/src/ui/compoments/MessageView/utils.ts @@ -234,7 +234,21 @@ export function renderMessageToStdout(message: SessionMessage, mode: RawMode): s const name = payload.name || metaFunctionName || "tool"; const metaParams = typeof message.meta?.paramsMd === "string" ? message.meta.paramsMd.trim() : ""; const params = name.toLowerCase() === "bash" ? metaParams : truncate(metaParams, 120); - return `${chalk("✧")} ${chalk(formatStatusName(name))}${params ? ` ${chalk(params)}` : ""}`; + const statusLine = `${chalk("✧")} ${chalk(formatStatusName(name))}${params ? ` ${chalk(params)}` : ""}`; + + const summary: ToolSummary = { + name, + params, + ok: payload.ok !== false, + metadata: payload.metadata, + }; + const planLines = getUpdatePlanPreviewLines(summary); + if (planLines.length > 0) { + const planText = planLines.map((line) => ` ${line}`).join("\n"); + return `${statusLine}\n${chalk.dim(" └ Plan")}\n${planText}`; + } + + return statusLine; } if (message.role === "system") { From d87dcfccf86496ad3e9b69a5f194b7779c82f6c1 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 20:51:03 +0800 Subject: [PATCH 055/129] feat: update AGENTS.md --- .deepcode/AGENTS.md | 53 ++++++++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/.deepcode/AGENTS.md b/.deepcode/AGENTS.md index 9cdf64e..7f9cf35 100644 --- a/.deepcode/AGENTS.md +++ b/.deepcode/AGENTS.md @@ -4,40 +4,47 @@ ``` src/ -├── cli.tsx # Entry point — parses args, renders Ink App +├── cli.tsx # Entry point — parses args (-p, -v), renders Ink App ├── session.ts # SessionManager — LLM loop, compaction, tool orchestration ├── settings.ts # Settings resolution from ~/.deepcode/settings.json -├── prompt.ts # System prompt builder, tool definitions, agent-drift-guard skill +├── prompt.ts # System prompt builder, tool definitions, built-in skills ├── common/ │ ├── model-capabilities.ts # Model detection and thinking-mode defaults +│ ├── openai-thinking.ts # OpenAI thinking request options builder │ ├── file-utils.ts # File read/write with encoding and diff preview │ ├── shell-utils.ts # Shell path resolution (Git Bash, zsh, bash) │ ├── state.ts # In-memory file state and snippet tracking -│ └── runtime.ts # Tool validation runtime helpers +│ ├── runtime.ts # Tool validation runtime helpers +│ ├── notify.ts # Desktop notification after LLM turn completion +│ ├── debug-logger.ts # Debug logging for OpenAI API calls +│ └── error-logger.ts # API error logging ├── ui/ │ ├── App.tsx # Root Ink component — state, routing, session orchestration -│ ├── PromptInput.tsx # Multi-line input with slash commands, image paste, skills +│ ├── PromptInput.tsx # Multi-line input with file mentions (@), slash commands, image paste, skills │ ├── MessageView.tsx # Renders assistant/tool messages with markdown -│ ├── DropdownMenu.tsx # Reusable dropdown for skill/model selection -│ ├── SessionList.tsx # Session picker for /resume -│ ├── promptUndoRedo.ts # Ctrl+- undo / Ctrl+Shift+- redo for prompt input +│ ├── McpStatusList.tsx # MCP server connection status and available tools +│ ├── ProcessStdoutView.tsx # Ctrl+O fullscreen overlay for live process stdout +│ ├── UpdatePrompt.tsx # UpdatePlan task list progress display +│ ├── fileMentions.ts # @-mention file scanning, filtering, and insertion │ └── ... ├── mcp/ │ ├── mcp-client.ts # MCP client — JSON-RPC communication with MCP servers -│ └── mcp-manager.ts # MCP manager — lifecycle, tool registration, execution +│ └── mcp-manager.ts # MCP manager — lifecycle, tool registration, execution, status ├── tools/ -│ ├── executor.ts # ToolExecutor — dispatches tool calls to handlers -│ ├── bash-handler.ts # Executes shell commands -│ ├── read-handler.ts # Reads files and images +│ ├── executor.ts # ToolExecutor — dispatches tool calls to handlers (7 built-in) +│ ├── bash-handler.ts # Executes shell commands with live stdout streaming +│ ├── read-handler.ts # Reads files, images, PDFs, and notebooks │ ├── write-handler.ts # Creates/overwrites files -│ ├── edit-handler.ts # Scoped string replacements in files -│ ├── web-search-handler.ts # Web search tool -│ └── ask-user-question-handler.ts # Interactive user prompts -├── tests/ # Test suite — one *.test.ts per module +│ ├── edit-handler.ts # Scoped string replacements with snippet tracking +│ ├── update-plan-handler.ts # Updates the task plan progress display +│ ├── web-search-handler.ts # Web search via natural language queries +│ └── ask-user-question-handler.ts # Interactive user prompts with options +├── tests/ # One *.test.ts per source module, plus run-tests.mjs templates/ ├── tools/ # Tool descriptions fed to the LLM +├── skills/ # Built-in skill definitions (agent-drift-guard, plan-and-execute) ├── prompts/ # EJS templates (e.g., init_command.md.ejs) -docs/ # User-facing documentation +docs/ # User-facing documentation (configuration, MCP, skills) dist/ # Bundled CLI output (gitignored) ``` @@ -80,7 +87,7 @@ Run the CLI locally for manual testing: `node dist/cli.js` (after `npm run bundl - **Coverage**: Target meaningful unit tests for core logic (session management, tool handlers, settings resolution, prompt buffer). Test files are in `src/tests/` matching the source module name. - **Test naming**: `describe`/`test` blocks with descriptive names. Example: `test("SessionManager preserves structured system content when building OpenAI messages", ...)` - **Relaxed lint rules**: Test files allow `any` and unused vars. -- Run all tests with `npm test` before submitting a PR. +- Run all tests with `npm test` before submitting a PR. A cross-platform test runner is available at `src/tests/run-tests.mjs`. ## Commit & Pull Request Guidelines @@ -102,12 +109,18 @@ Run the CLI locally for manual testing: `node dist/cli.js` (after `npm run bundl ## Architecture Overview -The CLI renders a terminal UI using [Ink](https://github.com/vadimdemedes/ink) (React for terminals). `SessionManager` drives the LLM interaction loop: it builds system prompts, sends user messages with optional skills/images, streams responses, executes tool calls via `ToolExecutor`, and compacts context when token thresholds are exceeded (512K for DeepSeek V4 models, 128K for others). +The CLI (`@vegamo/deepcode-cli`) renders a terminal UI using [Ink](https://github.com/vadimdemedes/ink) (React for terminals). `SessionManager` drives the LLM interaction loop: it builds system prompts, sends user messages with optional skills/images, streams responses, executes tool calls via `ToolExecutor`, and compacts context when token thresholds are exceeded (512K for DeepSeek V4 models, 128K for others). -Six tools are available to the LLM: `bash`, `read`, `write`, `edit`, `AskUserQuestion`, and `WebSearch`. Tool definitions are registered in `src/tools/executor.ts` and described to the LLM via `src/prompt.ts` and `templates/tools/`. +Seven built-in tools are available to the LLM: `bash`, `read`, `write`, `edit`, `AskUserQuestion`, `UpdatePlan`, and `WebSearch`. Tool definitions are registered in `src/tools/executor.ts` and described to the LLM via `src/prompt.ts` and `templates/tools/`. The `UpdatePlan` tool enables the LLM to display and update a structured task list in the terminal. + +**Slash commands**: `/model`, `/new`, `/init`, `/resume`, `/continue`, `/mcp`, `/exit`, plus dynamic `/skill-name` for each loaded skill. + +**Key UI features**: `@` file mentions in the prompt input (scans project files), `Ctrl+O` to view live process stdout in fullscreen, `Ctrl+V` to paste images, MCP server status display. + +**CLI flags**: `-p ` / `--prompt` to auto-submit a prompt on launch, `-v` / `--version`, `-h` / `--help`. ## Agent-Specific Instructions - **AGENTS.md loading**: The CLI loads agent instructions from `./AGENTS.md`, `./.deepcode/AGENTS.md`, or `~/.deepcode/AGENTS.md` (first found wins). Write project-specific guidance for the LLM in any of these. - **Skills**: Place skill definitions in `~/.agents/skills//SKILL.md` (user-level) or `./.agents/skills//SKILL.md` (project-level). Legacy path `./.deepcode/skills/` is also supported. Each SKILL.md uses YAML frontmatter with `name` and `description` fields. -- The built-in `agent-drift-guard` skill is always injected into every session. +- **Built-in skills**: `agent-drift-guard` (detects and corrects execution drift) and `plan-and-execute` (structured task planning with progress tracking). Both are defined in `templates/skills/` and always injected into every session. From d80a82354c36ea993a911fd8eadf21132f0d7e25 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 18 May 2026 20:51:33 +0800 Subject: [PATCH 056/129] 0.1.22 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 51b7a95..800d75a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.21", + "version": "0.1.22", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@vegamo/deepcode-cli", - "version": "0.1.21", + "version": "0.1.22", "license": "MIT", "dependencies": { "chalk": "^5.6.2", diff --git a/package.json b/package.json index e61d81d..c438d68 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.21", + "version": "0.1.22", "description": "Deep Code CLI - Vibe coding for the deepseek-v4 model in your terminal", "license": "MIT", "type": "module", From a42d5de1c1c6fbf935e53d0f470cf17c15361d63 Mon Sep 17 00:00:00 2001 From: hcyang Date: Tue, 19 May 2026 08:52:57 +0800 Subject: [PATCH 057/129] =?UTF-8?q?fix(ui):=20=E4=BF=AE=E5=A4=8DMessageVie?= =?UTF-8?q?w=E7=BB=84=E4=BB=B6=E4=B8=ADStatusLine=E6=98=BE=E7=A4=BA?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修改StatusLine组件的params传值逻辑 - 当content存在时,params传入空字符串,避免显示错误 - 保持了内容渲染的兼容性和逻辑清晰性 --- src/ui/compoments/MessageView/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/compoments/MessageView/index.tsx b/src/ui/compoments/MessageView/index.tsx index cc0e4df..dd0ddc5 100644 --- a/src/ui/compoments/MessageView/index.tsx +++ b/src/ui/compoments/MessageView/index.tsx @@ -50,7 +50,7 @@ export function MessageView({ message, collapsed, width = 80 }: MessageViewProps } return ( - + {content ? {renderMarkdown(content)} : null} From 05fed53801c402e78e64464847745ac7e959b119 Mon Sep 17 00:00:00 2001 From: hcyang Date: Tue, 19 May 2026 09:04:14 +0800 Subject: [PATCH 058/129] =?UTF-8?q?test(messageView):=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=B8=B2=E6=9F=93=E5=92=8C=E8=A7=A3=E6=9E=90=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E7=9A=84=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E8=A6=86=E7=9B=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 renderMessageToStdout 函数的多场景测试,包括用户、助手、工具和系统消息的渲染行为 - 添加 getUpdatePlanPreviewLines 对 UpdatePlan 工具消息的计划内容提取测试 - 增加 parseToolPayload 函数对空内容、无效 JSON 和有效负载的解析测试 - 引入辅助函数 makeSessionMessage 以简化测试消息实例构造 - 确保各种边界条件和meta字段的渲染正确性验证 --- src/tests/messageView.test.ts | 178 +++++++++++++++++++++++++++++++++- 1 file changed, 177 insertions(+), 1 deletion(-) diff --git a/src/tests/messageView.test.ts b/src/tests/messageView.test.ts index 0981f91..0cd95da 100644 --- a/src/tests/messageView.test.ts +++ b/src/tests/messageView.test.ts @@ -1,8 +1,15 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { parseDiffPreview } from "../ui"; -import { buildThinkingSummary } from "../ui/compoments/MessageView/utils"; +import { + buildThinkingSummary, + renderMessageToStdout, + getUpdatePlanPreviewLines, + parseToolPayload, +} from "../ui/compoments/MessageView/utils"; import { RawMode } from "../ui/contexts"; +import type { SessionMessage } from "../session"; +import type { ToolSummary } from "../ui/compoments/MessageView/types"; test("parseDiffPreview removes headers and classifies lines", () => { const lines = parseDiffPreview( @@ -52,3 +59,172 @@ test("MessageView shows full reasoning content in Normal/Raw mode", () => { "hidden chain of thought" ); }); + +// --- renderMessageToStdout tests --- + +function makeSessionMessage(overrides: Partial & Pick): SessionMessage { + const now = new Date().toISOString(); + return { + id: `test-${Math.random().toString(36).slice(2)}`, + sessionId: "test-session", + visible: true, + compacted: false, + createTime: now, + updateTime: now, + contentParams: null, + messageParams: null, + ...overrides, + }; +} + +test("renderMessageToStdout returns empty for invisible messages", () => { + const msg = makeSessionMessage({ role: "user", content: "hello", visible: false }); + assert.equal(renderMessageToStdout(msg, RawMode.Raw), ""); +}); + +test("renderMessageToStdout renders user messages with > prefix", () => { + const msg = makeSessionMessage({ role: "user", content: "fix the bug" }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("> fix the bug")); +}); + +test("renderMessageToStdout shows (no content) for empty user messages", () => { + const msg = makeSessionMessage({ role: "user", content: "" }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("(no content)")); +}); + +test("renderMessageToStdout renders assistant non-thinking messages with ✦", () => { + const msg = makeSessionMessage({ role: "assistant", content: "Here is the fix" }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("✦")); + assert.ok(output.includes("Here is the fix")); +}); + +test("renderMessageToStdout renders assistant thinking messages with ✧ Thinking", () => { + const msg = makeSessionMessage({ + role: "assistant", + content: "Plan:\nAnalyze the code", + meta: { asThinking: true }, + }); + const output = renderMessageToStdout(msg, RawMode.Lite); + assert.ok(output.includes("✧")); + assert.ok(output.includes("Thinking")); + assert.ok(output.includes("Plan: Analyze the code")); +}); + +test("renderMessageToStdout renders tool messages with ✧ and tool name", () => { + const payload = JSON.stringify({ name: "read", ok: true }); + const msg = makeSessionMessage({ role: "tool", content: payload }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("✧")); + assert.ok(output.includes("Read")); +}); + +test("renderMessageToStdout renders UpdatePlan tool messages with Plan preview", () => { + const payload = JSON.stringify({ + name: "UpdatePlan", + ok: true, + metadata: { plan: "Step 1: Analyze\nStep 2: Implement\nStep 3: Test" }, + }); + const msg = makeSessionMessage({ role: "tool", content: payload }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("UpdatePlan")); + assert.ok(output.includes("└ Plan")); + assert.ok(output.includes("Step 1: Analyze")); + assert.ok(output.includes("Step 2: Implement")); +}); + +test("renderMessageToStdout renders system model change messages", () => { + const msg = makeSessionMessage({ + role: "system", + content: "Switched to deepseek-v4-pro", + meta: { isModelChange: true }, + }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("> Switched to deepseek-v4-pro")); +}); + +test("renderMessageToStdout renders system skill load messages", () => { + const msg = makeSessionMessage({ + role: "system", + content: "", + meta: { skill: { name: "code-review" } }, + }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("⚡ Loaded skill: code-review")); +}); + +test("renderMessageToStdout renders system summary messages", () => { + const msg = makeSessionMessage({ + role: "system", + content: "", + meta: { isSummary: true }, + }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("(conversation summary inserted)")); +}); + +test("renderMessageToStdout returns empty for unknown system messages", () => { + const msg = makeSessionMessage({ role: "system", content: "" }); + assert.equal(renderMessageToStdout(msg, RawMode.Raw), ""); +}); + +// --- getUpdatePlanPreviewLines tests --- + +test("getUpdatePlanPreviewLines returns empty for failed tool", () => { + const summary: ToolSummary = { name: "UpdatePlan", params: "", ok: false, metadata: { plan: "Step 1" } }; + assert.deepEqual(getUpdatePlanPreviewLines(summary), []); +}); + +test("getUpdatePlanPreviewLines returns empty for non-UpdatePlan tool", () => { + const summary: ToolSummary = { name: "edit", params: "", ok: true, metadata: { plan: "Step 1" } }; + assert.deepEqual(getUpdatePlanPreviewLines(summary), []); +}); + +test("getUpdatePlanPreviewLines returns empty for missing plan metadata", () => { + const summary: ToolSummary = { name: "UpdatePlan", params: "", ok: true, metadata: null }; + assert.deepEqual(getUpdatePlanPreviewLines(summary), []); +}); + +test("getUpdatePlanPreviewLines returns empty for empty plan string", () => { + const summary: ToolSummary = { name: "UpdatePlan", params: "", ok: true, metadata: { plan: "" } }; + assert.deepEqual(getUpdatePlanPreviewLines(summary), []); +}); + +test("getUpdatePlanPreviewLines extracts plan lines and filters empty rows", () => { + const summary: ToolSummary = { + name: "UpdatePlan", + params: "", + ok: true, + metadata: { plan: "Step 1: Analyze\n\nStep 2: Implement\n \nStep 3: Test" }, + }; + assert.deepEqual(getUpdatePlanPreviewLines(summary), ["Step 1: Analyze", "Step 2: Implement", "Step 3: Test"]); +}); + +// --- parseToolPayload tests --- + +test("parseToolPayload returns defaults for null content", () => { + const result = parseToolPayload(null); + assert.deepEqual(result, { name: null, ok: true, metadata: null }); +}); + +test("parseToolPayload returns defaults for invalid JSON", () => { + const result = parseToolPayload("not valid json"); + assert.deepEqual(result, { name: null, ok: true, metadata: null }); +}); + +test("parseToolPayload parses valid JSON with name/ok/metadata", () => { + const result = parseToolPayload(JSON.stringify({ name: "read", ok: true, metadata: { file: "src/index.ts" } })); + assert.deepEqual(result, { name: "read", ok: true, metadata: { file: "src/index.ts" } }); +}); + +test("parseToolPayload respects ok: false", () => { + const result = parseToolPayload(JSON.stringify({ name: "bash", ok: false, metadata: null })); + assert.deepEqual(result, { name: "bash", ok: false, metadata: null }); +}); + +test("parseToolPayload trims whitespace from name", () => { + const result = parseToolPayload(JSON.stringify({ name: " read ", ok: true })); + assert.equal(result.name, "read"); +}); From cc59ae14ce9f1f497334efa97a942c400ea0943d Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Tue, 19 May 2026 09:20:52 +0800 Subject: [PATCH 059/129] feat: add support for file_path in write tool parameters --- src/session.ts | 2 ++ src/tests/session.test.ts | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/session.ts b/src/session.ts index 1c9d3b6..96a9adb 100644 --- a/src/session.ts +++ b/src/session.ts @@ -2050,6 +2050,8 @@ ${skillMd} } } else if (toolName === "UpdatePlan") { return typeof args.explanation === "string" ? args.explanation.trim() : ""; + } else if (toolName === "write") { + return typeof args.file_path === "string" ? args.file_path.trim() : ""; } const firstKey = Object.keys(args)[0]; diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index a178726..b7eadae 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1215,6 +1215,26 @@ test("UpdatePlan tool params only show explanation when provided", () => { assert.equal(withoutExplanation.meta?.paramsMd, ""); }); +test("Write tool params prefer file_path even when content appears first", () => { + const manager = createSessionManager(process.cwd(), "machine-id-write-params"); + const filePath = path.join(process.cwd(), "index.html"); + + const toolMessage = (manager as any).buildToolMessage( + "session-1", + "call-write-1", + JSON.stringify({ ok: true, name: "write", output: "Created file." }), + { + name: "write", + arguments: JSON.stringify({ + content: "// === entry ===\nconsole.log('demo');\n", + file_path: filePath, + }), + } + ) as SessionMessage; + + assert.equal(toolMessage.meta?.paramsMd, filePath); +}); + test("buildOpenAIMessages repairs mixed missing duplicate and orphan tool messages", () => { const manager = createSessionManager(process.cwd(), "machine-id-mixed-tool-badcase"); const assistantMessage = (manager as any).buildAssistantMessage( From 4680a30481cf64352d67099c136d604e00b06022 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Tue, 19 May 2026 10:09:03 +0800 Subject: [PATCH 060/129] feat: implement killProcessTree function for process termination management --- src/common/process-tree.ts | 61 ++++++++++++++ src/mcp/mcp-client.ts | 7 +- src/session.ts | 23 +---- src/tests/process-tree.test.ts | 148 +++++++++++++++++++++++++++++++++ src/updateCheck.ts | 7 +- 5 files changed, 224 insertions(+), 22 deletions(-) create mode 100644 src/common/process-tree.ts create mode 100644 src/tests/process-tree.test.ts diff --git a/src/common/process-tree.ts b/src/common/process-tree.ts new file mode 100644 index 0000000..40a0d1e --- /dev/null +++ b/src/common/process-tree.ts @@ -0,0 +1,61 @@ +import { spawnSync } from "child_process"; + +type TaskkillSpawnSync = ( + command: string, + args: string[], + options: { stdio: "ignore"; windowsHide: true } +) => { status: number | null; error?: Error }; + +export type KillProcessTreeDeps = { + platform?: NodeJS.Platform; + killPid?: (pid: number, signal: NodeJS.Signals) => void; + runTaskkill?: (pid: number) => boolean; + killGroupOnNonWindows?: boolean; +}; + +export function killProcessTree( + pid: number, + signal: NodeJS.Signals = "SIGKILL", + deps: KillProcessTreeDeps = {} +): boolean { + if (!Number.isInteger(pid) || pid <= 0) { + return false; + } + + const platform = deps.platform ?? process.platform; + const killPid = deps.killPid ?? ((targetPid, targetSignal) => process.kill(targetPid, targetSignal)); + + if (platform === "win32") { + const runTaskkill = deps.runTaskkill ?? runWindowsTaskkill; + if (runTaskkill(pid)) { + return true; + } + return killDirectProcess(pid, signal, killPid); + } + + if (deps.killGroupOnNonWindows !== false && killDirectProcess(-pid, signal, killPid)) { + return true; + } + return killDirectProcess(pid, signal, killPid); +} + +export function runWindowsTaskkill(pid: number, spawnSyncImpl: TaskkillSpawnSync = spawnSync): boolean { + const result = spawnSyncImpl("taskkill", ["/PID", String(pid), "/T", "/F"], { + stdio: "ignore", + windowsHide: true, + }); + return !result.error && result.status === 0; +} + +function killDirectProcess( + pid: number, + signal: NodeJS.Signals, + killPid: (pid: number, signal: NodeJS.Signals) => void +): boolean { + try { + killPid(pid, signal); + return true; + } catch { + return false; + } +} diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts index 9636732..2755755 100644 --- a/src/mcp/mcp-client.ts +++ b/src/mcp/mcp-client.ts @@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from "child_process"; import { createInterface, type Interface } from "readline"; import * as os from "os"; import * as path from "path"; +import { killProcessTree } from "../common/process-tree"; type JsonRpcRequest = { jsonrpc: "2.0"; @@ -268,7 +269,11 @@ export class McpClient { this.reader = null; } if (this.process) { - this.process.kill(); + if (typeof this.process.pid === "number") { + killProcessTree(this.process.pid, "SIGTERM", { killGroupOnNonWindows: false }); + } else { + this.process.kill(); + } this.process = null; } } diff --git a/src/session.ts b/src/session.ts index 96a9adb..3b6b67a 100644 --- a/src/session.ts +++ b/src/session.ts @@ -22,6 +22,7 @@ import { McpManager } from "./mcp/mcp-manager"; import type { McpServerConfig } from "./settings"; import { logApiError } from "./common/error-logger"; import { logOpenAIChatCompletionDebug, normalizeDebugError } from "./common/debug-logger"; +import { killProcessTree } from "./common/process-tree"; const MAX_SESSION_ENTRIES = 50; const DEFAULT_NEW_PROMPT_API_URL = "https://deepcode.vegamo.cn/api/plugin/new"; @@ -1359,17 +1360,11 @@ ${skillMd} const killedPids: number[] = []; const failedPids: number[] = []; for (const pid of processIds) { - const killedGroup = this.killProcessGroup(pid); - if (killedGroup) { + if (killProcessTree(pid, "SIGKILL")) { killedPids.push(pid); continue; } - try { - process.kill(pid, "SIGKILL"); - killedPids.push(pid); - } catch { - failedPids.push(pid); - } + failedPids.push(pid); } const controller = this.sessionControllers.get(sessionId); @@ -2186,18 +2181,6 @@ ${skillMd} ); } - private killProcessGroup(pid: number): boolean { - if (process.platform === "win32") { - return false; - } - try { - process.kill(-pid, "SIGKILL"); - return true; - } catch { - return false; - } - } - private normalizeSessionEntry(entry: unknown): SessionEntry { const value = entry && typeof entry === "object" ? (entry as Record) : {}; return { diff --git a/src/tests/process-tree.test.ts b/src/tests/process-tree.test.ts new file mode 100644 index 0000000..1dd08a1 --- /dev/null +++ b/src/tests/process-tree.test.ts @@ -0,0 +1,148 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { killProcessTree, runWindowsTaskkill } from "../common/process-tree"; + +test("runWindowsTaskkill invokes taskkill for the full process tree", () => { + const calls: Array<{ command: string; args: string[]; options: { stdio: "ignore"; windowsHide: true } }> = []; + + const ok = runWindowsTaskkill(1234, (command, args, options) => { + calls.push({ command, args, options }); + return { status: 0 }; + }); + + assert.equal(ok, true); + assert.deepEqual(calls, [ + { + command: "taskkill", + args: ["/PID", "1234", "/T", "/F"], + options: { stdio: "ignore", windowsHide: true }, + }, + ]); +}); + +test("runWindowsTaskkill reports failure for non-zero exits and spawn errors", () => { + assert.equal( + runWindowsTaskkill(1234, () => ({ + status: 1, + })), + false + ); + assert.equal( + runWindowsTaskkill(1234, () => ({ + status: null, + error: new Error("taskkill missing"), + })), + false + ); +}); + +test("killProcessTree uses taskkill on Windows", () => { + const killed: number[] = []; + + const ok = killProcessTree(1234, "SIGKILL", { + platform: "win32", + runTaskkill: (pid) => { + killed.push(pid); + return true; + }, + killPid: () => { + throw new Error("direct kill should not be used"); + }, + }); + + assert.equal(ok, true); + assert.deepEqual(killed, [1234]); +}); + +test("killProcessTree falls back to direct kill on Windows taskkill failure", () => { + const directKills: Array<{ pid: number; signal: NodeJS.Signals }> = []; + + const ok = killProcessTree(1234, "SIGTERM", { + platform: "win32", + runTaskkill: () => false, + killPid: (pid, signal) => { + directKills.push({ pid, signal }); + }, + }); + + assert.equal(ok, true); + assert.deepEqual(directKills, [{ pid: 1234, signal: "SIGTERM" }]); +}); + +test("killProcessTree returns false on Windows when all kill attempts fail", () => { + const ok = killProcessTree(1234, "SIGKILL", { + platform: "win32", + runTaskkill: () => false, + killPid: () => { + throw new Error("missing process"); + }, + }); + + assert.equal(ok, false); +}); + +test("killProcessTree kills a process group before direct PID on non-Windows platforms", () => { + const kills: Array<{ pid: number; signal: NodeJS.Signals }> = []; + + const ok = killProcessTree(1234, "SIGKILL", { + platform: "darwin", + killPid: (pid, signal) => { + kills.push({ pid, signal }); + }, + }); + + assert.equal(ok, true); + assert.deepEqual(kills, [{ pid: -1234, signal: "SIGKILL" }]); +}); + +test("killProcessTree falls back to direct PID on non-Windows group failure", () => { + const kills: Array<{ pid: number; signal: NodeJS.Signals }> = []; + + const ok = killProcessTree(1234, "SIGTERM", { + platform: "linux", + killPid: (pid, signal) => { + kills.push({ pid, signal }); + if (pid < 0) { + throw new Error("no process group"); + } + }, + }); + + assert.equal(ok, true); + assert.deepEqual(kills, [ + { pid: -1234, signal: "SIGTERM" }, + { pid: 1234, signal: "SIGTERM" }, + ]); +}); + +test("killProcessTree can skip non-Windows process group killing", () => { + const kills: Array<{ pid: number; signal: NodeJS.Signals }> = []; + + const ok = killProcessTree(1234, "SIGTERM", { + platform: "linux", + killGroupOnNonWindows: false, + killPid: (pid, signal) => { + kills.push({ pid, signal }); + }, + }); + + assert.equal(ok, true); + assert.deepEqual(kills, [{ pid: 1234, signal: "SIGTERM" }]); +}); + +test("killProcessTree ignores invalid PIDs", () => { + for (const pid of [0, -1, 1.5, Number.NaN]) { + assert.equal( + killProcessTree(pid, "SIGKILL", { + platform: "win32", + runTaskkill: () => { + throw new Error("taskkill should not be used"); + }, + killPid: () => { + throw new Error("direct kill should not be used"); + }, + }), + false + ); + } +}); diff --git a/src/updateCheck.ts b/src/updateCheck.ts index 626e529..81f1ff1 100644 --- a/src/updateCheck.ts +++ b/src/updateCheck.ts @@ -6,6 +6,7 @@ import * as path from "path"; import { render, type Instance } from "ink"; import chalk from "chalk"; import { UpdatePrompt, type UpdatePromptChoice } from "./ui"; +import { killProcessTree } from "./common/process-tree"; export type PackageInfo = { name: string; @@ -222,7 +223,11 @@ function runNpmViewLatestVersion( }; const timer = setTimeout(() => { - child.kill(); + if (typeof child.pid === "number") { + killProcessTree(child.pid, "SIGTERM", { killGroupOnNonWindows: false }); + } else { + child.kill(); + } finish({ ok: false }); }, timeoutMs); From 418294dfd315402e7942a42960239185fa44ef0a Mon Sep 17 00:00:00 2001 From: hcyang Date: Tue, 19 May 2026 10:28:48 +0800 Subject: [PATCH 061/129] =?UTF-8?q?refactor(rawmode):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=20RawMode=20=E7=8A=B6=E6=80=81=E7=AE=A1=E7=90=86=E4=B8=8E?= =?UTF-8?q?=E7=95=8C=E9=9D=A2=E4=BA=A4=E4=BA=92=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 RawModeContext 中增加 previousMode 状态用于保存上一个模式 - 修改 setMode 逻辑以更新 previousMode,支持通过函数设置模式 - RawModeExitPrompt 捕获并使用快照 previousMode 作为退出时目标模式 - 调整 App.tsx 处理 RawMode 切换逻辑,避免界面闪烁并重置欢迎屏幕状态 - 处理无激活会话时显示欢迎屏幕,确保状态正确更新 - 优化 Raw 模式消息加载逻辑,避免活跃会话缺失时的错误 - 更新测试用例中消息构建函数支持更多可选属性与默认值设置 - 修改 renderMessageToStdout 测试示例以配合新的消息结构及元信息 --- src/tests/messageView.test.ts | 23 +++++++------ src/ui/App.tsx | 24 +++++++++----- src/ui/compoments/RawModeExitPrompt/index.tsx | 11 +++++-- src/ui/contexts/RawModeContext.tsx | 32 ++++++++++++++++--- 4 files changed, 65 insertions(+), 25 deletions(-) diff --git a/src/tests/messageView.test.ts b/src/tests/messageView.test.ts index 0cd95da..b97e125 100644 --- a/src/tests/messageView.test.ts +++ b/src/tests/messageView.test.ts @@ -65,15 +65,18 @@ test("MessageView shows full reasoning content in Normal/Raw mode", () => { function makeSessionMessage(overrides: Partial & Pick): SessionMessage { const now = new Date().toISOString(); return { - id: `test-${Math.random().toString(36).slice(2)}`, - sessionId: "test-session", - visible: true, - compacted: false, - createTime: now, - updateTime: now, - contentParams: null, - messageParams: null, - ...overrides, + id: overrides.id ?? `test-${Math.random().toString(36).slice(2)}`, + sessionId: overrides.sessionId ?? "test-session", + role: overrides.role, + content: overrides.content ?? null, + visible: overrides.visible ?? true, + compacted: overrides.compacted ?? false, + createTime: overrides.createTime ?? now, + updateTime: overrides.updateTime ?? now, + contentParams: overrides.contentParams ?? null, + messageParams: overrides.messageParams ?? null, + meta: overrides.meta, + html: overrides.html, }; } @@ -149,7 +152,7 @@ test("renderMessageToStdout renders system skill load messages", () => { const msg = makeSessionMessage({ role: "system", content: "", - meta: { skill: { name: "code-review" } }, + meta: { skill: { name: "code-review", path: "", description: "" } }, }); const output = renderMessageToStdout(msg, RawMode.Raw); assert.ok(output.includes("⚡ Loaded skill: code-review")); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 3d29e32..9189df6 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -374,19 +374,18 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. const handleRawModeChange = useCallback( (nextMode: string) => { const activeSessionId = sessionManager.getActiveSessionId(); - if (!activeSessionId) { - return; - } - setMode(nextMode as RawMode); - + // Reset chat view state synchronously so the transition frame does not + // re-render a stale welcome screen before handleSelectSession runs. + setShowWelcome(false); + setMessages([]); // Clear screen to remove stale formatted text. process.stdout.write("\u001B[2J\u001B[3J\u001B[H"); setTimeout(() => { if (nextMode === RawMode.Raw) { // Write all messages directly to stdout for raw scrollback mode. - const allMessages = loadVisibleMessages(sessionManager, activeSessionId); + const allMessages = activeSessionId ? loadVisibleMessages(sessionManager, activeSessionId) : []; for (const msg of allMessages) { process.stdout.write("\n"); process.stdout.write(renderMessageToStdout(msg, nextMode) + "\n\n"); @@ -394,10 +393,19 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. if (allMessages.length > 0) { process.stdout.write("\n\n"); process.stdout.write(chalk.dim("Press ESC to exit raw mode")); + } else { + process.stdout.write("\n"); + process.stdout.write(chalk.dim("(No messages in this session yet. Start chatting to see them here.)")); + process.stdout.write("\n\n"); + process.stdout.write(chalk.dim("Press ESC to exit raw mode")); } - } else { + } else if (activeSessionId) { // Switch to chat view to render messages. handleSelectSession(activeSessionId); + } else { + // No active session: just show the welcome screen once. + setWelcomeNonce((n) => n + 1); + setShowWelcome(true); } }, 200); }, @@ -499,7 +507,7 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. }, [pendingQuestion]); if (mode === RawMode.Raw) { - return handleRawModeChange(RawMode.None)} />; + return handleRawModeChange(prev)} />; } return ( diff --git a/src/ui/compoments/RawModeExitPrompt/index.tsx b/src/ui/compoments/RawModeExitPrompt/index.tsx index 9b1d218..57ebf07 100644 --- a/src/ui/compoments/RawModeExitPrompt/index.tsx +++ b/src/ui/compoments/RawModeExitPrompt/index.tsx @@ -1,11 +1,16 @@ -import type React from "react"; +import { useRef, type ReactElement } from "react"; import { useInput } from "ink"; +import { useRawModeContext, type RawMode } from "../../contexts"; + +export function RawModeExitPrompt({ onExit }: { onExit: (previousMode: RawMode) => void }): ReactElement | null { + const { previousMode } = useRawModeContext(); + // Snapshot the prior mode at mount so later context updates do not change the ESC target. + const snapshotRef = useRef(previousMode); -export function RawModeExitPrompt({ onExit }: { onExit: () => void }): React.ReactElement | null { useInput( (_input, key) => { if (key.escape) { - onExit(); + onExit(snapshotRef.current); } }, { isActive: true } diff --git a/src/ui/contexts/RawModeContext.tsx b/src/ui/contexts/RawModeContext.tsx index d0c2336..6fbc706 100644 --- a/src/ui/contexts/RawModeContext.tsx +++ b/src/ui/contexts/RawModeContext.tsx @@ -1,4 +1,4 @@ -import React, { createContext, useContext, useState } from "react"; +import React, { createContext, useCallback, useContext, useRef, useState } from "react"; import type { DropdownMenuItem } from "../DropdownMenu"; export enum RawMode { @@ -21,9 +21,17 @@ export const RAW_COMMAND_MODELS: DropdownMenuItem[] = [ }, ] as const; -const RawModeContext = createContext<{ mode: RawMode; setMode: React.Dispatch> }>({ +type RawModeContextValue = { + mode: RawMode; + setMode: React.Dispatch>; + // The mode that was active right before the most recent mode transition. + previousMode: RawMode; +}; + +const RawModeContext = createContext({ mode: RawMode.Lite, setMode: () => {}, + previousMode: RawMode.Lite, }); export function useRawModeContext() { @@ -35,6 +43,22 @@ export function useRawModeContext() { } export const RawModeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { - const [mode, setMode] = useState(RawMode.Lite); - return {children}; + const [mode, _setMode] = useState(RawMode.Lite); + const previousModeRef = useRef(RawMode.Lite); + + const setMode = useCallback>>((next) => { + _setMode((current) => { + const resolved = typeof next === "function" ? (next as (prev: RawMode) => RawMode)(current) : next; + if (resolved !== current) { + previousModeRef.current = current; + } + return resolved; + }); + }, []); + + return ( + + {children} + + ); }; From 8e6e13f3d762395e58e9d74aa375c71e561c6ca8 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Tue, 19 May 2026 10:33:29 +0800 Subject: [PATCH 062/129] feat: improve npm command execution for cross-platform compatibility --- src/updateCheck.ts | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/updateCheck.ts b/src/updateCheck.ts index 81f1ff1..fcd9bfb 100644 --- a/src/updateCheck.ts +++ b/src/updateCheck.ts @@ -1,4 +1,4 @@ -import { spawn } from "child_process"; +import { spawn, type ChildProcess, type SpawnOptions } from "child_process"; import React from "react"; import * as fs from "fs"; import * as os from "os"; @@ -162,9 +162,8 @@ async function promptUpdateChoice({ async function runNpmInstallGlobal(installSpec: string): Promise { return new Promise((resolve) => { - const child = spawn("npm", ["install", "-g", installSpec], { + const child = spawnNpm(["install", "-g", installSpec], { stdio: "inherit", - shell: process.platform === "win32", }); child.on("error", (error) => { process.stderr.write(`Failed to start npm install: ${error.message}\n`); @@ -206,9 +205,8 @@ function runNpmViewLatestVersion( if (registry) { args.push("--registry", registry); } - const child = spawn("npm", args, { + const child = spawnNpm(args, { stdio: ["ignore", "pipe", "pipe"], - shell: process.platform === "win32", }); let stdout = ""; @@ -246,6 +244,24 @@ function runNpmViewLatestVersion( }); } +function spawnNpm(args: string[], options: SpawnOptions): ChildProcess { + if (process.platform === "win32") { + return spawn(["npm", ...args.map(quoteCmdArg)].join(" "), [], { + ...options, + shell: true, + }); + } + + return spawn("npm", args, { + ...options, + shell: false, + }); +} + +function quoteCmdArg(arg: string): string { + return `"${String(arg).replace(/"/g, '\\"')}"`; +} + export function parseNpmViewVersion(output: string): string | null { const trimmed = output.trim(); if (!trimmed) { From 5bfce46d6d17ea88e7f02b56b5f7282b37f9ebd9 Mon Sep 17 00:00:00 2001 From: hcyang Date: Tue, 19 May 2026 11:11:40 +0800 Subject: [PATCH 063/129] =?UTF-8?q?docs(readme):=20=E5=A2=9E=E5=BC=BA=20RE?= =?UTF-8?q?ADME.md=20=E6=96=87=E4=BB=B6=E5=86=85=E5=AE=B9=E5=92=8C?= =?UTF-8?q?=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 README.md 和 README_en.md 文件中新增居中标题和统一头部样式 - README.md 中添加“[English](./README_en.md) · 中文”语言切换链接 - README_en.md 中添加“English · [中文](./README.md)”语言切换链接 - README.md 新增 `/raw` 命令介绍,补充命令表内容 - 删除冗余的 README_cn.md 文件,简化文档管理 --- README.md | 16 +++++- README_cn.md | 154 --------------------------------------------------- README_en.md | 17 +++++- 3 files changed, 31 insertions(+), 156 deletions(-) delete mode 100644 README_cn.md diff --git a/README.md b/README.md index 69d28c8..00167c1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,17 @@ -# Deep Code CLI +
+
+
+

+ + deepcode-cli + +

+

Deep Code CLI

+ +[English](./README_en.md) · 中文 + +
+
[Deep Code](https://github.com/lessweb/deepcode-cli) 是专为 `deepseek-v4` 模型优化的终端 AI 编码助手,支持深度思考、推理强度控制、Agent Skills 以及 MCP 集成。 @@ -53,6 +66,7 @@ Deep Code CLI 支持 agent skills,允许您扩展助手的能力: | `/new` | 开始新对话 | | `/resume` | 选择历史对话继续 | | `/model` | 切换模型、思考模式和推理强度 | +| `/raw` | 切换显示模式(Normal / Lite / Raw 滚动回溯)| | `/init` | 初始化 AGENTS.md 文件 | | `/skills` | 列出可用 skills | | `/mcp` | 查看 MCP 服务器状态和可用工具 | diff --git a/README_cn.md b/README_cn.md deleted file mode 100644 index 69d28c8..0000000 --- a/README_cn.md +++ /dev/null @@ -1,154 +0,0 @@ -# Deep Code CLI - -[Deep Code](https://github.com/lessweb/deepcode-cli) 是专为 `deepseek-v4` 模型优化的终端 AI 编码助手,支持深度思考、推理强度控制、Agent Skills 以及 MCP 集成。 - -## 安装 - -```bash -npm install -g @vegamo/deepcode-cli -``` - -在任意项目目录下运行 `deepcode` 即可启动。 - -![intro2](resources/intro2.png) - -## 配置 - -创建 `~/.deepcode/settings.json` 文件,内容如下: - -```json -{ - "env": { - "MODEL": "deepseek-v4-pro", - "BASE_URL": "https://api.deepseek.com", - "API_KEY": "sk-..." - }, - "thinkingEnabled": true, - "reasoningEffort": "max" -} -``` - -配置文件与 [Deep Code VSCode 插件](https://github.com/lessweb/deepcode) 共享,无需重复配置。 - -完整配置说明(多层级优先级、环境变量等)请参阅 [docs/configuration.md](docs/configuration.md)。 - -## 主要功能 - -### **Skills** -Deep Code CLI 支持 agent skills,允许您扩展助手的能力: - -- **User-level Skills**:从 `~/.agents/skills/` 目录中发现并激活 skills。 -- **Project-level Skills**:从 `./.agents/skills/` 目录中加载项目专属 skills,并兼容旧的 `./.deepcode/skills/` 目录。 - -### **为 DeepSeek 优化** -- 专门为 DeepSeek 模型性能调优。 -- 通过使用[上下文缓存](https://api-docs.deepseek.com/guides/kv_cache)来降低成本。 -- 原生支持[思考模式](https://api-docs.deepseek.com/guides/thinking_mode)和思考强度控制。 - -## 斜杠命令与按键功能 - -| 斜杠命令 | 操作 | -|-----------------|---------------------------------------------| -| `/` | 打开 skills / 命令菜单 | -| `/new` | 开始新对话 | -| `/resume` | 选择历史对话继续 | -| `/model` | 切换模型、思考模式和推理强度 | -| `/init` | 初始化 AGENTS.md 文件 | -| `/skills` | 列出可用 skills | -| `/mcp` | 查看 MCP 服务器状态和可用工具 | -| `/exit` | 退出(也可用连续 `Ctrl+D`) | - -| 按键 | 操作 | -|-----------------|---------------------------------------------| -| `Enter` | 发送消息 | -| `Shift+Enter` | 插入换行(也可用 `Ctrl+J`) | -| `Ctrl+V` | 从剪贴板粘贴图片 | -| `Esc` | 中断当前模型回复 | -| 连续 `Ctrl+D` | 退出 | - -## 支持的模型 - -- `deepseek-v4-pro`(推荐使用) -- `deepseek-v4-flash` -- 任何其他 OpenAI 兼容模型 - - -## 常见问题 - -### Deep Code 是否有 VSCode 插件? - -有的。Deep Code 提供功能完整的 VSCode 插件,可在 [VSCode Marketplace](https://marketplace.visualstudio.com/items?itemName=vegamo.deepcode-vscode) 安装。插件与 CLI 共享 `~/.deepcode/settings.json` 配置文件,可以在终端和编辑器之间无缝切换。 - -### Deep Code 是否支持理解图片? - -Deep Code 支持多模态,可使用ctrl+v从剪贴板粘贴图片。但目前 deepseek-v4 不支持多模态。有些模型虽然有多模态能力,但对多轮对话请求的限制太严。目前多模态输入推荐使用火山方舟的 Doubao-Seed-2.0-pro 模型,适配效果最好。 - -### 怎样在任务完成后自动给 Slack 发消息? - -编写一个调用 Slack webhook 的 Shell 通知脚本,然后在 `~/.deepcode/settings.json` 中将 `notify` 字段设为该脚本的完整路径即可。详细步骤可参考:https://binfer.net/share/jby5xnc-so6g - -### 怎样启用联网搜索功能? - -Deep Code自带免费的、且大部分情况够用的Web Search工具。如果你希望使用自定义脚本进行联网搜索,可以在 `~/.deepcode/settings.json` 中将 `webSearchTool` 设为脚本的完整路径即可。详细步骤可参考:https://github.com/qorzj/web_search_cli - -### 如何配置 MCP? - -Deep Code 支持 MCP(Model Context Protocol),可以连接 GitHub、浏览器、数据库等外部服务。在 `settings.json` 中配置 `mcpServers` 字段即可启用,启动后使用 `/mcp` 命令查看已配置的 MCP 服务器状态和可用工具。 - -详细配置指南:[docs/mcp.md](docs/mcp.md) - - -### 是否支持 Coding Plan? - -支持。只要把 `~/.deepcode/settings.json` 的 `env.BASE_URL` 配置为 OpenAI 兼容的接口地址就行。以火山方舟的 Coding Plan 为例: - -```json -{ - "env": { - "MODEL": "ark-code-latest", - "BASE_URL": "https://ark.cn-beijing.volces.com/api/coding/v3", - "API_KEY": "**************" - }, - "thinkingEnabled": true -} -``` -## 贡献 - -欢迎贡献代码!以下是参与方式: - -```bash -# 克隆仓库 -git clone https://github.com/lessweb/deepcode-cli.git -cd deepcode-cli - -# 安装依赖 -npm install - -# 本地开发(类型检查 + lint + 格式检查 + 构建) -npm run build - -# 运行测试 -npm test - -# 链接到全局(即本地全局安装) -npm link -``` - -- 提交 PR 前请确保 `npm run check` 通过(类型检查 + lint + 格式检查) -- 建议在执行构建前,先执行 `npm run format` 自动格式化代码,避免构建报错 - -## 获取帮助 - -- 在 GitHub Issues 上报告错误或请求功能 (https://github.com/lessweb/deepcode-cli/issues) - -## 协议 - -- MIT - -## 支持我们 - -如果你觉得这个工具对你有帮助,请考虑通过以下方式支持我们: - -- 在 GitHub 上给我们一个 Star (https://github.com/lessweb/deepcode-cli) -- 向我们提交反馈和建议 -- 分享给你的朋友和同事 diff --git a/README_en.md b/README_en.md index ee5a103..4c78cbd 100644 --- a/README_en.md +++ b/README_en.md @@ -1,7 +1,21 @@ -# Deep Code CLI +
+
+
+

+ + deepcode-cli + +

+

Deep Code CLI

+ +English · [中文](./README.md) + +
+
[Deep Code](https://github.com/lessweb/deepcode-cli) is a terminal AI coding assistant optimized for the `deepseek-v4` model, with support for deep thinking, reasoning effort control, Agent Skills, and MCP (Model Context Protocol) integration. + ## Installation ```bash @@ -53,6 +67,7 @@ Deep Code CLI supports agent skills that allow you to extend the assistant's cap | `/new` | Start a fresh conversation | | `/resume` | Choose a previous conversation to continue | | `/model` | Switch model, thinking mode, and reasoning effort | +| `/raw` | Toggle display mode (Normal / Lite / Raw scrollback) | | `/init` | Initialize an AGENTS.md file (LLM project instructions) | | `/skills` | List available skills | | `/mcp` | View MCP server status and available tools | From 7f3d1b87dfb2a79b95d94289ef558d3b04c40e40 Mon Sep 17 00:00:00 2001 From: hcyang Date: Tue, 19 May 2026 13:17:54 +0800 Subject: [PATCH 064/129] =?UTF-8?q?fix(ui):=20=E4=BC=98=E5=8C=96=E4=B8=8A?= =?UTF-8?q?=E4=B8=8B=E6=96=87=E9=92=A9=E5=AD=90=E4=B8=8E=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=E8=A1=8C=E5=AF=BC=E5=85=A5=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修改 useAppContext 钩子,安全处理无上下文情况,返回默认版本信息 - 更新 cli.tsx 中 AppContainer 的导入方式,改为从统一入口导入 - 在 ui/index.ts 中导出 AppContainer 组件 - 新增 UI 共享常量 ARGS_SEPARATOR,提升分隔符一致性 feat(ui): 优化命令行提示参数分隔符显示 - 在 PromptInput 和 SlashCommandMenu 组件中使用 ARGS_SEPARATOR 替代硬编码分隔符 - 调整 SlashCommandMenu 中命令行长度计算逻辑,兼容新分隔符 fix(ui): 修正 slashCommands 过滤匹配逻辑 - 将命令匹配条件从包含改为完全相等,提高准确性 feat(ui): 扩展消息视图工具信息展示 - 增加对 tool 消息中 meta.resultMd 字段的渲染支持 - 在工具状态行后增加 Result 结果块,配合 Plan 预览一同展示 - 更新 renderMessageToStdout 相关测试,覆盖新展示逻辑 --- src/cli.tsx | 2 +- src/tests/messageView.test.ts | 36 ++++++++++++++++++++++++++ src/ui/PromptInput.tsx | 3 ++- src/ui/SlashCommandMenu.tsx | 7 +++-- src/ui/compoments/MessageView/utils.ts | 7 +++-- src/ui/constants.ts | 4 +++ src/ui/contexts/AppContext.tsx | 5 ++-- src/ui/index.ts | 2 +- src/ui/slashCommands.ts | 2 +- 9 files changed, 58 insertions(+), 10 deletions(-) create mode 100644 src/ui/constants.ts diff --git a/src/cli.tsx b/src/cli.tsx index e8e8659..66ceb7d 100644 --- a/src/cli.tsx +++ b/src/cli.tsx @@ -2,7 +2,7 @@ import React from "react"; import { render } from "ink"; import { setShellIfWindows } from "./common/shell-utils"; import { checkForNpmUpdate, promptForPendingUpdate, type PackageInfo } from "./updateCheck"; -import AppContainer from "./ui/AppContainer"; +import { AppContainer } from "./ui"; const args = process.argv.slice(2); const packageInfo = readPackageInfo(); diff --git a/src/tests/messageView.test.ts b/src/tests/messageView.test.ts index b97e125..990c8ff 100644 --- a/src/tests/messageView.test.ts +++ b/src/tests/messageView.test.ts @@ -124,6 +124,40 @@ test("renderMessageToStdout renders tool messages with ✧ and tool name", () => assert.ok(output.includes("Read")); }); +test("renderMessageToStdout renders tool messages with resultMd output", () => { + const payload = JSON.stringify({ name: "read", ok: true }); + const msg = makeSessionMessage({ + role: "tool", + content: payload, + meta: { resultMd: "File content:\n line 1\n line 2" }, + }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("✧")); + assert.ok(output.includes("Read")); + assert.ok(output.includes("└ Result")); + assert.ok(output.includes("File content:")); + assert.ok(output.includes("line 1")); +}); + +test("renderMessageToStdout renders UpdatePlan tool messages with Plan preview and resultMd", () => { + const payload = JSON.stringify({ + name: "UpdatePlan", + ok: true, + metadata: { plan: "Step 1: Analyze\nStep 2: Implement\nStep 3: Test" }, + }); + const msg = makeSessionMessage({ + role: "tool", + content: payload, + meta: { resultMd: "Plan updated successfully" }, + }); + const output = renderMessageToStdout(msg, RawMode.Raw); + assert.ok(output.includes("UpdatePlan")); + assert.ok(output.includes("└ Plan")); + assert.ok(output.includes("Step 1: Analyze")); + assert.ok(output.includes(" Result")); + assert.ok(output.includes("Plan updated successfully")); +}); + test("renderMessageToStdout renders UpdatePlan tool messages with Plan preview", () => { const payload = JSON.stringify({ name: "UpdatePlan", @@ -136,6 +170,8 @@ test("renderMessageToStdout renders UpdatePlan tool messages with Plan preview", assert.ok(output.includes("└ Plan")); assert.ok(output.includes("Step 1: Analyze")); assert.ok(output.includes("Step 2: Implement")); + // Verify resultMd is NOT included when meta.resultMd is absent + assert.ok(!output.includes("└ Result")); }); test("renderMessageToStdout renders system model change messages", () => { diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index d620d24..1096a93 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -1,6 +1,7 @@ import React, { useEffect, useMemo, useState } from "react"; import { Box, Text, useApp, useStdout } from "ink"; import chalk from "chalk"; +import { ARGS_SEPARATOR } from "./constants"; import { EMPTY_BUFFER, backspace, @@ -887,7 +888,7 @@ export const PromptInput = React.memo(function PromptInput({ ); const matchedCommand = slashToken ? findExactSlashCommand(slashItems, slashToken) : null; - const inlineHint = matchedCommand?.args ? ` ${matchedCommand.args.join("|")}` : ""; + const inlineHint = matchedCommand?.args ? ` ${matchedCommand.args.join(ARGS_SEPARATOR)}` : ""; return ( diff --git a/src/ui/SlashCommandMenu.tsx b/src/ui/SlashCommandMenu.tsx index 1c050b9..02ff308 100644 --- a/src/ui/SlashCommandMenu.tsx +++ b/src/ui/SlashCommandMenu.tsx @@ -1,5 +1,6 @@ import { formatSlashCommandDescription, formatSlashCommandLabel } from "./slashCommands"; import type { SlashCommandItem } from "./slashCommands"; +import { ARGS_SEPARATOR } from "./constants"; import React from "react"; import { Box, Text } from "ink"; @@ -21,7 +22,9 @@ const SlashCommandMenu = React.memo(function SlashCommandMenu({ if (items.length === 0) { return 0; } - const longestLabel = Math.max(...items.map((s) => s.label.length + (s.args ? s.args?.join("|")?.length + 4 : 0))); + const longestLabel = Math.max( + ...items.map((s) => s.label.length + (s.args ? s.args?.join(ARGS_SEPARATOR)?.length + 4 : 0)) + ); const contentWidth = longestLabel + 2; // +2 for prefix "> " or " " const maxAllowed = Math.max(10, (width - 2) >> 1); // 容器50%宽度(减去gap),至少保留10列 return Math.min(contentWidth, maxAllowed); @@ -54,7 +57,7 @@ const SlashCommandMenu = React.memo(function SlashCommandMenu({ {actualIndex === activeIndex ? "> " : " "} {formatSlashCommandLabel(item)}
- {item.args ? {item.args.join("|")} : null} + {item.args ? {item.args.join(ARGS_SEPARATOR)} : null}
diff --git a/src/ui/compoments/MessageView/utils.ts b/src/ui/compoments/MessageView/utils.ts index 45eb79c..af5391d 100644 --- a/src/ui/compoments/MessageView/utils.ts +++ b/src/ui/compoments/MessageView/utils.ts @@ -236,6 +236,9 @@ export function renderMessageToStdout(message: SessionMessage, mode: RawMode): s const params = name.toLowerCase() === "bash" ? metaParams : truncate(metaParams, 120); const statusLine = `${chalk("✧")} ${chalk(formatStatusName(name))}${params ? ` ${chalk(params)}` : ""}`; + const metaResultMd = typeof message.meta?.resultMd === "string" ? message.meta.resultMd.trim() : ""; + const result = metaResultMd ? `\n${chalk.dim(" └ Result")}\n${metaResultMd}` : ""; + const summary: ToolSummary = { name, params, @@ -245,10 +248,10 @@ export function renderMessageToStdout(message: SessionMessage, mode: RawMode): s const planLines = getUpdatePlanPreviewLines(summary); if (planLines.length > 0) { const planText = planLines.map((line) => ` ${line}`).join("\n"); - return `${statusLine}\n${chalk.dim(" └ Plan")}\n${planText}`; + return `${statusLine}\n${chalk.dim(" └ Plan")}\n${planText}${result}`; } - return statusLine; + return `${statusLine}${result}`; } if (message.role === "system") { diff --git a/src/ui/constants.ts b/src/ui/constants.ts new file mode 100644 index 0000000..7c74597 --- /dev/null +++ b/src/ui/constants.ts @@ -0,0 +1,4 @@ +// UI-level shared constants used across components. + +/** Separator used when rendering command arguments inline (e.g., `arg1 | arg2 | arg3`). */ +export const ARGS_SEPARATOR = " | "; diff --git a/src/ui/contexts/AppContext.tsx b/src/ui/contexts/AppContext.tsx index 34d4589..41b1d1d 100644 --- a/src/ui/contexts/AppContext.tsx +++ b/src/ui/contexts/AppContext.tsx @@ -6,10 +6,11 @@ export interface AppState { export const AppContext = createContext(null); -export const useAppContext = () => { +export const useAppContext = (): AppState => { const context = useContext(AppContext); if (!context) { - throw new Error("useAppContext must be used within an AppProvider"); + // Safe fallback when App is rendered without AppContainer (e.g., in tests). + return { version: "unknown" }; } return context; }; diff --git a/src/ui/index.ts b/src/ui/index.ts index 3a1ddf4..f2e698c 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -1,5 +1,4 @@ export { - App, readSettings, readProjectSettings, writeSettings, @@ -8,6 +7,7 @@ export { resolveCurrentSettings, createOpenAIClient, } from "./App"; +export { default as AppContainer } from "./AppContainer"; export { AskUserQuestionPrompt } from "./AskUserQuestionPrompt"; export { MessageView } from "./compoments"; export { parseDiffPreview } from "./compoments/MessageView/utils"; diff --git a/src/ui/slashCommands.ts b/src/ui/slashCommands.ts index aab06bd..948a7ab 100644 --- a/src/ui/slashCommands.ts +++ b/src/ui/slashCommands.ts @@ -106,7 +106,7 @@ export function findExactSlashCommand(items: SlashCommandItem[], token: string): return null; } const query = token.slice(1); - const matches = items.filter((item) => item.name.includes(query)); + const matches = items.filter((item) => item.name === query); return matches.find((item) => item.kind !== "skill") ?? matches[0] ?? null; } From 379ffc5b45f9973e5738718657411f87c6db26cf Mon Sep 17 00:00:00 2001 From: hcyang Date: Tue, 19 May 2026 14:30:49 +0800 Subject: [PATCH 065/129] =?UTF-8?q?docs(readme):=20=E6=81=A2=E5=A4=8D=20RE?= =?UTF-8?q?ADME-zh=5FCN.md=20=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README_en.md => README-en.md | 0 README-zh_CN.md | 168 +++++++++++++++++++++++++++++++++++ README.md | 2 +- 3 files changed, 169 insertions(+), 1 deletion(-) rename README_en.md => README-en.md (100%) create mode 100644 README-zh_CN.md diff --git a/README_en.md b/README-en.md similarity index 100% rename from README_en.md rename to README-en.md diff --git a/README-zh_CN.md b/README-zh_CN.md new file mode 100644 index 0000000..98346b6 --- /dev/null +++ b/README-zh_CN.md @@ -0,0 +1,168 @@ +
+
+
+

+ + deepcode-cli + +

+

Deep Code CLI

+ +[English](README-en.md) · 中文 + +
+
+ +[Deep Code](https://github.com/lessweb/deepcode-cli) 是专为 `deepseek-v4` 模型优化的终端 AI 编码助手,支持深度思考、推理强度控制、Agent Skills 以及 MCP 集成。 + +## 安装 + +```bash +npm install -g @vegamo/deepcode-cli +``` + +在任意项目目录下运行 `deepcode` 即可启动。 + +![intro2](resources/intro2.png) + +## 配置 + +创建 `~/.deepcode/settings.json` 文件,内容如下: + +```json +{ + "env": { + "MODEL": "deepseek-v4-pro", + "BASE_URL": "https://api.deepseek.com", + "API_KEY": "sk-..." + }, + "thinkingEnabled": true, + "reasoningEffort": "max" +} +``` + +配置文件与 [Deep Code VSCode 插件](https://github.com/lessweb/deepcode) 共享,无需重复配置。 + +完整配置说明(多层级优先级、环境变量等)请参阅 [docs/configuration.md](docs/configuration.md)。 + +## 主要功能 + +### **Skills** +Deep Code CLI 支持 agent skills,允许您扩展助手的能力: + +- **User-level Skills**:从 `~/.agents/skills/` 目录中发现并激活 skills。 +- **Project-level Skills**:从 `./.agents/skills/` 目录中加载项目专属 skills,并兼容旧的 `./.deepcode/skills/` 目录。 + +### **为 DeepSeek 优化** +- 专门为 DeepSeek 模型性能调优。 +- 通过使用[上下文缓存](https://api-docs.deepseek.com/guides/kv_cache)来降低成本。 +- 原生支持[思考模式](https://api-docs.deepseek.com/guides/thinking_mode)和思考强度控制。 + +## 斜杠命令与按键功能 + +| 斜杠命令 | 操作 | +|-----------------|---------------------------------------------| +| `/` | 打开 skills / 命令菜单 | +| `/new` | 开始新对话 | +| `/resume` | 选择历史对话继续 | +| `/model` | 切换模型、思考模式和推理强度 | +| `/raw` | 切换显示模式(Normal / Lite / Raw 滚动回溯)| +| `/init` | 初始化 AGENTS.md 文件 | +| `/skills` | 列出可用 skills | +| `/mcp` | 查看 MCP 服务器状态和可用工具 | +| `/exit` | 退出(也可用连续 `Ctrl+D`) | + +| 按键 | 操作 | +|-----------------|---------------------------------------------| +| `Enter` | 发送消息 | +| `Shift+Enter` | 插入换行(也可用 `Ctrl+J`) | +| `Ctrl+V` | 从剪贴板粘贴图片 | +| `Esc` | 中断当前模型回复 | +| 连续 `Ctrl+D` | 退出 | + +## 支持的模型 + +- `deepseek-v4-pro`(推荐使用) +- `deepseek-v4-flash` +- 任何其他 OpenAI 兼容模型 + + +## 常见问题 + +### Deep Code 是否有 VSCode 插件? + +有的。Deep Code 提供功能完整的 VSCode 插件,可在 [VSCode Marketplace](https://marketplace.visualstudio.com/items?itemName=vegamo.deepcode-vscode) 安装。插件与 CLI 共享 `~/.deepcode/settings.json` 配置文件,可以在终端和编辑器之间无缝切换。 + +### Deep Code 是否支持理解图片? + +Deep Code 支持多模态,可使用ctrl+v从剪贴板粘贴图片。但目前 deepseek-v4 不支持多模态。有些模型虽然有多模态能力,但对多轮对话请求的限制太严。目前多模态输入推荐使用火山方舟的 Doubao-Seed-2.0-pro 模型,适配效果最好。 + +### 怎样在任务完成后自动给 Slack 发消息? + +编写一个调用 Slack webhook 的 Shell 通知脚本,然后在 `~/.deepcode/settings.json` 中将 `notify` 字段设为该脚本的完整路径即可。详细步骤可参考:https://binfer.net/share/jby5xnc-so6g + +### 怎样启用联网搜索功能? + +Deep Code自带免费的、且大部分情况够用的Web Search工具。如果你希望使用自定义脚本进行联网搜索,可以在 `~/.deepcode/settings.json` 中将 `webSearchTool` 设为脚本的完整路径即可。详细步骤可参考:https://github.com/qorzj/web_search_cli + +### 如何配置 MCP? + +Deep Code 支持 MCP(Model Context Protocol),可以连接 GitHub、浏览器、数据库等外部服务。在 `settings.json` 中配置 `mcpServers` 字段即可启用,启动后使用 `/mcp` 命令查看已配置的 MCP 服务器状态和可用工具。 + +详细配置指南:[docs/mcp.md](docs/mcp.md) + + +### 是否支持 Coding Plan? + +支持。只要把 `~/.deepcode/settings.json` 的 `env.BASE_URL` 配置为 OpenAI 兼容的接口地址就行。以火山方舟的 Coding Plan 为例: + +```json +{ + "env": { + "MODEL": "ark-code-latest", + "BASE_URL": "https://ark.cn-beijing.volces.com/api/coding/v3", + "API_KEY": "**************" + }, + "thinkingEnabled": true +} +``` +## 贡献 + +欢迎贡献代码!以下是参与方式: + +```bash +# 克隆仓库 +git clone https://github.com/lessweb/deepcode-cli.git +cd deepcode-cli + +# 安装依赖 +npm install + +# 本地开发(类型检查 + lint + 格式检查 + 构建) +npm run build + +# 运行测试 +npm test + +# 链接到全局(即本地全局安装) +npm link +``` + +- 提交 PR 前请确保 `npm run check` 通过(类型检查 + lint + 格式检查) +- 建议在执行构建前,先执行 `npm run format` 自动格式化代码,避免构建报错 + +## 获取帮助 + +- 在 GitHub Issues 上报告错误或请求功能 (https://github.com/lessweb/deepcode-cli/issues) + +## 协议 + +- MIT + +## 支持我们 + +如果你觉得这个工具对你有帮助,请考虑通过以下方式支持我们: + +- 在 GitHub 上给我们一个 Star (https://github.com/lessweb/deepcode-cli) +- 向我们提交反馈和建议 +- 分享给你的朋友和同事 diff --git a/README.md b/README.md index 00167c1..98346b6 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@

Deep Code CLI

-[English](./README_en.md) · 中文 +[English](README-en.md) · 中文
From 3fef0fc5137af49f218237fa0e919159fb231122 Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 10:09:38 +0800 Subject: [PATCH 066/129] feat(notify): pass STATUS, FAIL_REASON, BODY as env vars to notify hook - Add NotifyContext type with status, failReason, body fields - buildNotifyEnv injects STATUS, FAIL_REASON, BODY when provided - maybeNotifyTaskCompletion extracts last assistant message as BODY - launchNotifyScript accepts optional context parameter - Add unit tests for new context env var injection - Update docs with env variable table and iTerm2/macOS notify examples --- docs/configuration.md | 34 ++++++ docs/configuration_en.md | 34 ++++++ src/common/notify.ts | 38 ++++++- src/session.ts | 18 +++- src/tests/session.test.ts | 144 ++++++++++++++++++++++++++ src/tests/settings-and-notify.test.ts | 65 +++++++++++- 6 files changed, 324 insertions(+), 9 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index f8e52c3..45aaab0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -67,12 +67,46 @@ Deep Code 使用 `settings.json` 设置文件进行持久化配置,支持两 设置一个 Shell 脚本的完整路径。当 AI 助手完成一轮任务后,会自动执行该脚本,可用于发送通知(如 Slack 消息)。 +通知脚本执行时,会通过环境变量注入以下上下文信息: + +| 环境变量 | 说明 | +|----------|------| +| `DURATION` | 会话耗时,单位秒(整数) | +| `STATUS` | 会话状态:`"completed"` 或 `"failed"` | +| `FAIL_REASON` | 失败原因(仅失败时设置) | +| `BODY` | 最后一条 AI 助手回复的文本内容 | +| `TITLE` | 会话标题(对应 resume 列表中的标题) | + ```json { "notify": "/path/to/slack-notify.sh" } ``` +**iTerm2 终端通知示例**: + +如果你的终端是 iTerm2,可以直接通过 OSC 9 转义序列弹出通知,无需额外脚本。创建以下脚本(如 `~/.deepcode/notify.sh`): + +```bash +#!/bin/bash +# iTerm2 OSC 9 通知 +echo -e "\x1b]9;DeepCode: task ${STATUS:-completed} (${DURATION}s)\x07" +``` + +```json +{ + "notify": "/Users/you/.deepcode/notify.sh" +} +``` + +**macOS 系统通知示例**: + +```bash +#!/bin/bash +# macOS 系统通知 +osascript -e "display notification \"任务已${STATUS:-完成},耗时 ${DURATION}s\" with title \"DeepCode\"" +``` + #### `webSearchTool` — 自定义联网搜索 Deep Code 内置免费可用的 Web Search 工具。如果需要自定义搜索逻辑,可将 `webSearchTool` 设为一个可执行脚本的完整路径: diff --git a/docs/configuration_en.md b/docs/configuration_en.md index 369f8e4..606fcab 100644 --- a/docs/configuration_en.md +++ b/docs/configuration_en.md @@ -67,12 +67,46 @@ When thinking mode is enabled, controls the depth of the model’s reasoning: Set a full path to a shell script. When the AI assistant finishes a round of tasks, the script is executed automatically, which can be used to send notifications (e.g., a Slack message). +The following context is injected as environment variables when the notify script runs: + +| Variable | Description | +|----------|-------------| +| `DURATION` | Session duration in seconds (integer) | +| `STATUS` | Session status: `"completed"` or `"failed"` | +| `FAIL_REASON` | Failure reason (only set on failure) | +| `BODY` | The text content of the last AI assistant reply | +| `TITLE` | Session title (matches the resume list title) | + ```json { "notify": "/path/to/slack-notify.sh" } ``` +**iTerm2 Notification Example**: + +On iTerm2 you can use the OSC 9 escape sequence for native notifications. Create a script (e.g., `~/.deepcode/notify.sh`): + +```bash +#!/bin/bash +# iTerm2 OSC 9 notification +echo -e "\x1b]9;DeepCode: task ${STATUS:-completed} (${DURATION}s)\x07" +``` + +```json +{ + "notify": "/Users/you/.deepcode/notify.sh" +} +``` + +**macOS System Notification Example**: + +```bash +#!/bin/bash +# macOS system notification +osascript -e "display notification \"Task ${STATUS:-completed}, took ${DURATION}s\" with title \"DeepCode\"" +``` + #### `webSearchTool` — Custom Web Search Deep Code has a built-in, free-to-use Web Search tool. If you need custom search logic, set `webSearchTool` to the full path of an executable script: diff --git a/src/common/notify.ts b/src/common/notify.ts index 8878c50..d1b541b 100644 --- a/src/common/notify.ts +++ b/src/common/notify.ts @@ -16,11 +16,40 @@ export function formatDurationSeconds(durationMs: number): string { return String(Math.floor(safeMs / 1000)); } -export function buildNotifyEnv(durationMs: number, baseEnv: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { - return { +export type NotifyContext = { + status?: string; + failReason?: string; + body?: string; + title?: string; +}; + +export function buildNotifyEnv( + durationMs: number, + baseEnv: NodeJS.ProcessEnv = process.env, + context: NotifyContext = {} +): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { ...baseEnv, DURATION: formatDurationSeconds(durationMs), }; + delete env.STATUS; + delete env.FAIL_REASON; + delete env.BODY; + delete env.TITLE; + + if (context.status) { + env.STATUS = context.status; + } + if (context.failReason) { + env.FAIL_REASON = context.failReason; + } + if (context.body) { + env.BODY = context.body; + } + if (context.title) { + env.TITLE = context.title; + } + return env; } export function launchNotifyScript( @@ -28,7 +57,8 @@ export function launchNotifyScript( durationMs: number, workingDirectory?: string, spawnProcess: NotifySpawn = spawn as unknown as NotifySpawn, - configuredEnv: Record = {} + configuredEnv: Record = {}, + context: NotifyContext = {} ): void { const commandPath = notifyPath?.trim(); if (!commandPath) { @@ -38,7 +68,7 @@ export function launchNotifyScript( const options = { cwd: workingDirectory, detached: process.platform !== "win32", - env: buildNotifyEnv(durationMs, { ...process.env, ...configuredEnv }), + env: buildNotifyEnv(durationMs, { ...process.env, ...configuredEnv }, context), stdio: "ignore" as const, }; diff --git a/src/session.ts b/src/session.ts index 96a9adb..3a6e13b 100644 --- a/src/session.ts +++ b/src/session.ts @@ -2124,7 +2124,23 @@ ${skillMd} return; } - launchNotifyScript(notifyCommand, Date.now() - startedAt, this.projectRoot, undefined, configuredEnv); + // Find the last assistant message body for the BODY env variable. + let body: string | undefined; + const messages = this.listSessionMessages(sessionId); + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i]; + if (msg && msg.role === "assistant" && msg.content) { + body = msg.content; + break; + } + } + + launchNotifyScript(notifyCommand, Date.now() - startedAt, this.projectRoot, undefined, configuredEnv, { + status: session.status, + failReason: session.failReason ?? undefined, + body, + title: session.summary ?? undefined, + }); } private addSessionProcess(sessionId: string, processId: string | number, command: string): void { diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index b7eadae..d079949 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -783,6 +783,68 @@ test("reporting a new prompt does not warn when the background request fails", a assert.deepEqual(warnings, []); }); +test( + "SessionManager notifies successful completion with session context", + { skip: process.platform === "win32" }, + async () => { + const workspace = createTempDir("deepcode-notify-success-workspace-"); + const home = createTempDir("deepcode-notify-success-home-"); + setHomeDir(home); + + const notifyOutput = path.join(workspace, "notify.jsonl"); + const notifyScript = createNotifyRecorderScript(workspace); + const manager = createNotifyingSessionManager( + workspace, + [createChatResponse("final answer", { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 })], + notifyScript, + notifyOutput + ); + + await manager.createSession({ text: "notify success" }); + + const records = await waitForNotifyRecords(notifyOutput, 1); + assert.equal(records[0]?.STATUS, "completed"); + assert.equal(records[0]?.FAIL_REASON, null); + assert.equal(records[0]?.BODY, "final answer"); + assert.equal(records[0]?.TITLE, "notify success"); + assert.match(String(records[0]?.DURATION), /^\d+$/); + } +); + +test( + "SessionManager notifies failed completion with failure context", + { skip: process.platform === "win32" }, + async () => { + const workspace = createTempDir("deepcode-notify-failure-workspace-"); + const home = createTempDir("deepcode-notify-failure-home-"); + setHomeDir(home); + + const notifyOutput = path.join(workspace, "notify.jsonl"); + const notifyScript = createNotifyRecorderScript(workspace); + const manager = createNotifyingSessionManager( + workspace, + [ + createChatResponse("first answer", { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }), + new Error("second request failed"), + ], + notifyScript, + notifyOutput + ); + + const sessionId = await manager.createSession({ text: "notify failure" }); + await waitForNotifyRecords(notifyOutput, 1); + await manager.replySession(sessionId, { text: "second prompt" }); + + const records = await waitForNotifyRecords(notifyOutput, 2); + const failedRecord = records[1]; + assert.equal(failedRecord?.STATUS, "failed"); + assert.equal(failedRecord?.FAIL_REASON, "second request failed"); + assert.equal(failedRecord?.BODY, "first answer"); + assert.notEqual(failedRecord?.BODY, "stale-body"); + assert.equal(failedRecord?.TITLE, "notify failure"); + } +); + test("replySession continues without appending /continue as a user message", async () => { const workspace = createTempDir("deepcode-continue-workspace-"); const home = createTempDir("deepcode-continue-home-"); @@ -1657,6 +1719,49 @@ function createSessionManager(projectRoot: string, machineId: string): SessionMa }); } +function createNotifyingSessionManager( + projectRoot: string, + responses: unknown[], + notifyPath: string, + notifyOutput: string +): SessionManager { + const client = { + chat: { + completions: { + create: async () => { + const response = responses.shift(); + assert.ok(response, "expected a queued chat response"); + if (response instanceof Error) { + throw response; + } + return response; + }, + }, + }, + }; + + return new SessionManager({ + projectRoot, + createOpenAIClient: () => ({ + client: client as any, + model: "test-model", + baseURL: "https://api.deepseek.com", + thinkingEnabled: false, + notify: notifyPath, + env: { + NOTIFY_OUTPUT: notifyOutput, + STATUS: "stale-status", + FAIL_REASON: "stale-failure", + BODY: "stale-body", + TITLE: "stale-title", + }, + }), + getResolvedSettings: () => ({ model: "test-model" }), + renderMarkdown: (text) => text, + onAssistantMessage: () => {}, + }); +} + function createMockedClientSessionManager(projectRoot: string, responses: unknown[]): SessionManager { const client = { chat: { @@ -1740,6 +1845,45 @@ function createTempDir(prefix: string): string { return dir; } +function createNotifyRecorderScript(dir: string): string { + const scriptPath = path.join(dir, "notify-recorder.cjs"); + fs.writeFileSync( + scriptPath, + `#!/usr/bin/env node +const fs = require("fs"); +const keys = ["DURATION", "STATUS", "FAIL_REASON", "BODY", "TITLE"]; +const record = {}; +for (const key of keys) { + record[key] = Object.prototype.hasOwnProperty.call(process.env, key) ? process.env[key] : null; +} +fs.appendFileSync(process.env.NOTIFY_OUTPUT, JSON.stringify(record) + "\\n", "utf8"); +`, + "utf8" + ); + fs.chmodSync(scriptPath, 0o755); + return scriptPath; +} + +async function waitForNotifyRecords( + outputPath: string, + expectedCount: number +): Promise>> { + for (let attempt = 0; attempt < 100; attempt += 1) { + if (fs.existsSync(outputPath)) { + const records = fs + .readFileSync(outputPath, "utf8") + .split(/\r?\n/) + .filter(Boolean) + .map((line) => JSON.parse(line) as Record); + if (records.length >= expectedCount) { + return records; + } + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } + assert.fail(`expected ${expectedCount} notify records in ${outputPath}`); +} + function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } diff --git a/src/tests/settings-and-notify.test.ts b/src/tests/settings-and-notify.test.ts index 6990288..202f849 100644 --- a/src/tests/settings-and-notify.test.ts +++ b/src/tests/settings-and-notify.test.ts @@ -1,6 +1,12 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { buildNotifyEnv, formatDurationSeconds, launchNotifyScript, type NotifySpawn } from "../common/notify"; +import { + buildNotifyEnv, + formatDurationSeconds, + launchNotifyScript, + type NotifyContext, + type NotifySpawn, +} from "../common/notify"; import { applyModelConfigSelection, resolveSettings, resolveSettingsSources } from "../settings"; const TEST_PROCESS_ENV = {}; @@ -358,14 +364,52 @@ test("formatDurationSeconds preserves sub-second precision and trims trailing ze assert.equal(formatDurationSeconds(4000), "4"); }); -test("buildNotifyEnv injects DURATION", () => { +test("buildNotifyEnv injects DURATION without context", () => { const env = buildNotifyEnv(2750, { HOME: "/tmp/home" }); assert.equal(env.HOME, "/tmp/home"); assert.equal(env.DURATION, "2"); + assert.equal(env.STATUS, undefined); + assert.equal(env.FAIL_REASON, undefined); + assert.equal(env.BODY, undefined); + assert.equal(env.TITLE, undefined); +}); + +test("buildNotifyEnv injects STATUS, FAIL_REASON, BODY, and TITLE from context", () => { + const context: NotifyContext = { + status: "failed", + failReason: "API key not found", + body: "Hello, this is the last assistant message.", + title: "Fix login bug", + }; + const env = buildNotifyEnv(5000, { HOME: "/tmp/home" }, context); + assert.equal(env.HOME, "/tmp/home"); + assert.equal(env.DURATION, "5"); + assert.equal(env.STATUS, "failed"); + assert.equal(env.FAIL_REASON, "API key not found"); + assert.equal(env.BODY, "Hello, this is the last assistant message."); + assert.equal(env.TITLE, "Fix login bug"); +}); + +test("buildNotifyEnv omits optional context fields when not provided", () => { + const env = buildNotifyEnv( + 1000, + { + HOME: "/tmp/home", + STATUS: "stale-status", + FAIL_REASON: "stale-failure", + BODY: "stale-body", + TITLE: "stale-title", + }, + { status: "completed" } + ); + assert.equal(env.STATUS, "completed"); + assert.equal(env.FAIL_REASON, undefined); + assert.equal(env.BODY, undefined); + assert.equal(env.TITLE, undefined); }); test( - "launchNotifyScript passes DURATION and falls back to /bin/sh for non-executable scripts", + "launchNotifyScript passes DURATION, context vars, and falls back to /bin/sh for non-executable scripts", { skip: process.platform === "win32" }, () => { const calls: Array<{ @@ -390,7 +434,13 @@ test( }; }; - launchNotifyScript("/tmp/notify.sh", 2750, "/tmp/project", spawnProcess, { WEBHOOK: "configured" }); + const context: NotifyContext = { + status: "completed", + body: "Task finished successfully.", + title: "Fix login bug", + }; + + launchNotifyScript("/tmp/notify.sh", 2750, "/tmp/project", spawnProcess, { WEBHOOK: "configured" }, context); assert.equal(calls.length, 2); assert.equal(calls[0]?.command, "/tmp/notify.sh"); @@ -398,9 +448,16 @@ test( assert.equal(calls[0]?.options.cwd, "/tmp/project"); assert.equal(calls[0]?.options.env?.DURATION, "2"); assert.equal(calls[0]?.options.env?.WEBHOOK, "configured"); + assert.equal(calls[0]?.options.env?.STATUS, "completed"); + assert.equal(calls[0]?.options.env?.FAIL_REASON, undefined); + assert.equal(calls[0]?.options.env?.BODY, "Task finished successfully."); + assert.equal(calls[0]?.options.env?.TITLE, "Fix login bug"); assert.equal(calls[1]?.command, "/bin/sh"); assert.deepEqual(calls[1]?.args, ["/tmp/notify.sh"]); assert.equal(calls[1]?.options.cwd, "/tmp/project"); assert.equal(calls[1]?.options.env?.DURATION, "2"); + assert.equal(calls[1]?.options.env?.STATUS, "completed"); + assert.equal(calls[1]?.options.env?.BODY, "Task finished successfully."); + assert.equal(calls[1]?.options.env?.TITLE, "Fix login bug"); } ); From a3ff70e82d548a8c1273ea377844f078cbd0ae00 Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 10:43:55 +0800 Subject: [PATCH 067/129] docs(notify): add Windows Terminal, Linux, and msg popup notification examples; add edge-case tests - Expand OSC 9 example to cover both iTerm2 and Windows Terminal - Add .bat example for Windows Terminal users - Add Linux notify-send example - Add Windows msg popup notification example - Add tests for empty-string rejection and special character preservation --- docs/configuration.md | 32 +++++++++++++++++++++++---- docs/configuration_en.md | 32 +++++++++++++++++++++++---- src/tests/settings-and-notify.test.ts | 27 ++++++++++++++++++++++ 3 files changed, 83 insertions(+), 8 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 45aaab0..7c2880c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -83,14 +83,14 @@ Deep Code 使用 `settings.json` 设置文件进行持久化配置,支持两 } ``` -**iTerm2 终端通知示例**: +**终端内通知示例(支持 iTerm2 / Windows Terminal)**: -如果你的终端是 iTerm2,可以直接通过 OSC 9 转义序列弹出通知,无需额外脚本。创建以下脚本(如 `~/.deepcode/notify.sh`): +如果你的终端是 iTerm2 或 Windows Terminal,可以直接通过 OSC 9 转义序列弹出终端原生通知,无需额外依赖。创建以下脚本(如 `~/.deepcode/notify.sh`): ```bash #!/bin/bash -# iTerm2 OSC 9 通知 -echo -e "\x1b]9;DeepCode: task ${STATUS:-completed} (${DURATION}s)\x07" +# iTerm2 / Windows Terminal OSC 9 通知 +printf '\x1b]9;DeepCode: task %s (%ss)\x07' "${STATUS:-completed}" "${DURATION}" ``` ```json @@ -99,6 +99,14 @@ echo -e "\x1b]9;DeepCode: task ${STATUS:-completed} (${DURATION}s)\x07" } ``` +Windows 用户如使用 Git Bash,上述脚本同样可用;也可创建 `.bat` 脚本: + +```batch +@echo off +REM Windows Terminal OSC 9 通知 +echo \x1b]9;DeepCode: task %STATUS% (%DURATION%s)\x07 +``` + **macOS 系统通知示例**: ```bash @@ -107,6 +115,22 @@ echo -e "\x1b]9;DeepCode: task ${STATUS:-completed} (${DURATION}s)\x07" osascript -e "display notification \"任务已${STATUS:-完成},耗时 ${DURATION}s\" with title \"DeepCode\"" ``` +**Linux 系统通知示例**(需安装 `libnotify-bin`): + +```bash +#!/bin/bash +# Linux notify-send 通知 +notify-send "DeepCode" "任务已${STATUS:-完成},耗时 ${DURATION}s" +``` + +**Windows msg 弹窗通知示例**: + +```batch +@echo off +REM Windows msg 弹窗通知 +msg %USERNAME% "DeepCode: task %STATUS% (%DURATION%s)" +``` + #### `webSearchTool` — 自定义联网搜索 Deep Code 内置免费可用的 Web Search 工具。如果需要自定义搜索逻辑,可将 `webSearchTool` 设为一个可执行脚本的完整路径: diff --git a/docs/configuration_en.md b/docs/configuration_en.md index 606fcab..5d931f4 100644 --- a/docs/configuration_en.md +++ b/docs/configuration_en.md @@ -83,14 +83,14 @@ The following context is injected as environment variables when the notify scrip } ``` -**iTerm2 Notification Example**: +**Terminal Notification Example (iTerm2 / Windows Terminal)**: -On iTerm2 you can use the OSC 9 escape sequence for native notifications. Create a script (e.g., `~/.deepcode/notify.sh`): +On iTerm2 or Windows Terminal you can use the OSC 9 escape sequence for native terminal notifications with zero dependencies. Create a script (e.g., `~/.deepcode/notify.sh`): ```bash #!/bin/bash -# iTerm2 OSC 9 notification -echo -e "\x1b]9;DeepCode: task ${STATUS:-completed} (${DURATION}s)\x07" +# iTerm2 / Windows Terminal OSC 9 notification +printf '\x1b]9;DeepCode: task %s (%ss)\x07' "${STATUS:-completed}" "${DURATION}" ``` ```json @@ -99,6 +99,14 @@ echo -e "\x1b]9;DeepCode: task ${STATUS:-completed} (${DURATION}s)\x07" } ``` +Windows users on Git Bash can use the same script; alternatively create a `.bat` script: + +```batch +@echo off +REM Windows Terminal OSC 9 notification +echo \x1b]9;DeepCode: task %STATUS% (%DURATION%s)\x07 +``` + **macOS System Notification Example**: ```bash @@ -107,6 +115,22 @@ echo -e "\x1b]9;DeepCode: task ${STATUS:-completed} (${DURATION}s)\x07" osascript -e "display notification \"Task ${STATUS:-completed}, took ${DURATION}s\" with title \"DeepCode\"" ``` +**Linux System Notification Example** (requires `libnotify-bin`): + +```bash +#!/bin/bash +# Linux notify-send notification +notify-send "DeepCode" "Task ${STATUS:-completed}, took ${DURATION}s" +``` + +**Windows msg Popup Notification Example**: + +```batch +@echo off +REM Windows msg popup notification +msg %USERNAME% "DeepCode: task %STATUS% (%DURATION%s)" +``` + #### `webSearchTool` — Custom Web Search Deep Code has a built-in, free-to-use Web Search tool. If you need custom search logic, set `webSearchTool` to the full path of an executable script: diff --git a/src/tests/settings-and-notify.test.ts b/src/tests/settings-and-notify.test.ts index 202f849..1707aff 100644 --- a/src/tests/settings-and-notify.test.ts +++ b/src/tests/settings-and-notify.test.ts @@ -408,6 +408,33 @@ test("buildNotifyEnv omits optional context fields when not provided", () => { assert.equal(env.TITLE, undefined); }); +test("buildNotifyEnv ignores empty strings in context", () => { + const env = buildNotifyEnv( + 1000, + { HOME: "/tmp/home" }, + { + status: "", + failReason: "", + body: "", + title: "", + } + ); + assert.equal(env.STATUS, undefined); + assert.equal(env.FAIL_REASON, undefined); + assert.equal(env.BODY, undefined); + assert.equal(env.TITLE, undefined); +}); + +test("buildNotifyEnv preserves special characters in body and title", () => { + const context: NotifyContext = { + body: 'Line 1\nLine 2\tindented "quoted"', + title: "Fix: login & signup (urgent)", + }; + const env = buildNotifyEnv(1000, {}, context); + assert.equal(env.BODY, 'Line 1\nLine 2\tindented "quoted"'); + assert.equal(env.TITLE, "Fix: login & signup (urgent)"); +}); + test( "launchNotifyScript passes DURATION, context vars, and falls back to /bin/sh for non-executable scripts", { skip: process.platform === "win32" }, From 479606f6a7087398302334996e95cb8eb2d841b3 Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 13:33:28 +0800 Subject: [PATCH 068/129] docs(notify): replace terminal notification examples with Feishu webhook example - Remove iTerm2/Windows Terminal OSC 9, macOS osascript, Linux notify-send, and Windows msg examples (OSC 9 is not compatible with current spawn+stdio:ignore architecture) - Add Feishu (Lark) webhook notification example in both Chinese and English docs - Keep the env variable table (DURATION, STATUS, FAIL_REASON, BODY, TITLE) unchanged --- docs/configuration.md | 62 ++++++++++++++-------------------------- docs/configuration_en.md | 62 ++++++++++++++-------------------------- 2 files changed, 44 insertions(+), 80 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 7c2880c..b05a44f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -83,53 +83,35 @@ Deep Code 使用 `settings.json` 设置文件进行持久化配置,支持两 } ``` -**终端内通知示例(支持 iTerm2 / Windows Terminal)**: +**飞书 Webhook 通知示例**: -如果你的终端是 iTerm2 或 Windows Terminal,可以直接通过 OSC 9 转义序列弹出终端原生通知,无需额外依赖。创建以下脚本(如 `~/.deepcode/notify.sh`): +`node` 构建 JSON(自动转义特殊字符),`curl` 发送: ```bash #!/bin/bash -# iTerm2 / Windows Terminal OSC 9 通知 -printf '\x1b]9;DeepCode: task %s (%ss)\x07' "${STATUS:-completed}" "${DURATION}" -``` - -```json -{ - "notify": "/Users/you/.deepcode/notify.sh" -} -``` - -Windows 用户如使用 Git Bash,上述脚本同样可用;也可创建 `.bat` 脚本: - -```batch -@echo off -REM Windows Terminal OSC 9 通知 -echo \x1b]9;DeepCode: task %STATUS% (%DURATION%s)\x07 -``` - -**macOS 系统通知示例**: - -```bash -#!/bin/bash -# macOS 系统通知 -osascript -e "display notification \"任务已${STATUS:-完成},耗时 ${DURATION}s\" with title \"DeepCode\"" -``` - -**Linux 系统通知示例**(需安装 `libnotify-bin`): +WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxx" + +STATUS="${STATUS:-completed}" +TITLE="${TITLE:-Untitled}" +DURATION="${DURATION:-0}" +BODY="${BODY:-(no output)}" + +PAYLOAD=$(node -e " +process.stdout.write(JSON.stringify({ + msg_type: 'interactive', + card: { + header: { title: { tag: 'plain_text', content: 'DeepCode: ' + process.env.TITLE + ' ' + process.env.STATUS + ' [' + process.env.DURATION + 's]' } }, + elements: [{ tag: 'markdown', content: (process.env.BODY || '').slice(0, 2000) || '(no output)' }] + } +})) +") -```bash -#!/bin/bash -# Linux notify-send 通知 -notify-send "DeepCode" "任务已${STATUS:-完成},耗时 ${DURATION}s" +curl -s -X POST "$WEBHOOK_URL" \ + -H "Content-Type: application/json" \ + -d "$PAYLOAD" ``` -**Windows msg 弹窗通知示例**: - -```batch -@echo off -REM Windows msg 弹窗通知 -msg %USERNAME% "DeepCode: task %STATUS% (%DURATION%s)" -``` +将 `WEBHOOK_URL` 替换为你的飞书机器人 Webhook 地址。更多变量参考上表。同样适用于 Slack、企业微信等 webhook 类通知,只需修改 JSON payload 格式。 #### `webSearchTool` — 自定义联网搜索 diff --git a/docs/configuration_en.md b/docs/configuration_en.md index 5d931f4..4f2f94d 100644 --- a/docs/configuration_en.md +++ b/docs/configuration_en.md @@ -83,53 +83,35 @@ The following context is injected as environment variables when the notify scrip } ``` -**Terminal Notification Example (iTerm2 / Windows Terminal)**: +**Feishu (Lark) Webhook Notification Example**: -On iTerm2 or Windows Terminal you can use the OSC 9 escape sequence for native terminal notifications with zero dependencies. Create a script (e.g., `~/.deepcode/notify.sh`): +`node` builds the JSON (auto-escapes special characters), `curl` sends it: ```bash #!/bin/bash -# iTerm2 / Windows Terminal OSC 9 notification -printf '\x1b]9;DeepCode: task %s (%ss)\x07' "${STATUS:-completed}" "${DURATION}" -``` - -```json -{ - "notify": "/Users/you/.deepcode/notify.sh" -} -``` - -Windows users on Git Bash can use the same script; alternatively create a `.bat` script: - -```batch -@echo off -REM Windows Terminal OSC 9 notification -echo \x1b]9;DeepCode: task %STATUS% (%DURATION%s)\x07 -``` - -**macOS System Notification Example**: - -```bash -#!/bin/bash -# macOS system notification -osascript -e "display notification \"Task ${STATUS:-completed}, took ${DURATION}s\" with title \"DeepCode\"" -``` - -**Linux System Notification Example** (requires `libnotify-bin`): +WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxx" + +STATUS="${STATUS:-completed}" +TITLE="${TITLE:-Untitled}" +DURATION="${DURATION:-0}" +BODY="${BODY:-(no output)}" + +PAYLOAD=$(node -e " +process.stdout.write(JSON.stringify({ + msg_type: 'interactive', + card: { + header: { title: { tag: 'plain_text', content: 'DeepCode: ' + process.env.TITLE + ' ' + process.env.STATUS + ' [' + process.env.DURATION + 's]' } }, + elements: [{ tag: 'markdown', content: (process.env.BODY || '').slice(0, 2000) || '(no output)' }] + } +})) +") -```bash -#!/bin/bash -# Linux notify-send notification -notify-send "DeepCode" "Task ${STATUS:-completed}, took ${DURATION}s" +curl -s -X POST "$WEBHOOK_URL" \ + -H "Content-Type: application/json" \ + -d "$PAYLOAD" ``` -**Windows msg Popup Notification Example**: - -```batch -@echo off -REM Windows msg popup notification -msg %USERNAME% "DeepCode: task %STATUS% (%DURATION%s)" -``` +Replace `WEBHOOK_URL` with your Feishu bot webhook URL. See the table above for all available variables. This pattern also works for other webhook-based notifications (Slack, WeCom, etc.) — just adjust the JSON payload format. #### `webSearchTool` — Custom Web Search From 7e5eeda26829b14eb3ed503b550db06c1145acf6 Mon Sep 17 00:00:00 2001 From: hcyang Date: Tue, 19 May 2026 15:05:00 +0800 Subject: [PATCH 069/129] =?UTF-8?q?feat(ui):=20=E6=B7=BB=E5=8A=A0=20raw=20?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E4=B8=8B=E6=B6=88=E6=81=AF=E7=9B=B4=E6=8E=A5?= =?UTF-8?q?=E6=B8=B2=E6=9F=93=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 Raw 模式下,使用 process.stdout.write 直接输出所有可见消息 - 清屏并重置光标位置,避免 Ink 组件干扰 - 显示提示信息,指导用户按 ESC 退出 raw 模式 - 优化终端尺寸变化时的重绘逻辑 - 更新依赖,确保 raw 模式变动触发重新渲染 --- src/ui/App.tsx | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 9189df6..e39fd03 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -434,8 +434,31 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. } lastRenderedColumnsRef.current = stableColumns; + if (mode === RawMode.Raw) { + // In raw mode, re-render all messages directly to stdout at the new width. + // Use process.stdout.write instead of writeRef to avoid Ink interference. + process.stdout.write("\u001B[2J\u001B[3J\u001B[H"); + const activeSessionId = sessionManager.getActiveSessionId(); + const allMessages = activeSessionId ? loadVisibleMessages(sessionManager, activeSessionId) : []; + for (const msg of allMessages) { + process.stdout.write("\n"); + process.stdout.write(renderMessageToStdout(msg, mode) + "\n\n"); + } + if (allMessages.length > 0) { + process.stdout.write("\n\n"); + process.stdout.write(chalk.dim("Press ESC to exit raw mode")); + } else { + process.stdout.write("\n"); + process.stdout.write(chalk.dim("(No messages in this session yet. Start chatting to see them here.)")); + process.stdout.write("\n\n"); + process.stdout.write(chalk.dim("Press ESC to exit raw mode")); + } + return; + } + // Force full redraw on terminal resize to avoid stale wrapped rows. writeRef.current("\u001B[2J\u001B[H"); + setMessages([]); setShowWelcome(false); setWelcomeNonce((n) => n + 1); @@ -447,7 +470,8 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setMessages(nextMessages); setShowWelcome(true); }, 0); - }, [busy, sessionManager, stableColumns, stdout]); + }, [busy, mode, sessionManager, stableColumns, stdout]); + const screenWidth = useMemo(() => stableColumns ?? stdout?.columns ?? 80, [stableColumns, stdout]); const promptHistory = useMemo(() => { return messages From faf10c3e087d214bf863e9df14040176e30de821 Mon Sep 17 00:00:00 2001 From: hcyang Date: Tue, 19 May 2026 15:12:08 +0800 Subject: [PATCH 070/129] =?UTF-8?q?refactor(ui):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E7=AA=97=E5=8F=A3=E5=AE=BD=E5=BA=A6=E7=9B=B8=E5=85=B3=E7=9A=84?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E5=92=8C=E5=BC=95=E7=94=A8=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 合并并调整了关于窗口宽度columns的使用,去除了stableColumns状态 - 引用lastRenderedColumnsRef改为直接使用columns,避免延迟更新 - 将多个相关的useRef(writeRef、rawModeRef、messagesRef、processStdoutRef)移至同一位置声明 - 调整useEffect依赖项,改为监听columns代替stableColumns - 优化RawMode下消息重绘逻辑,确保宽度变化时重新渲染 - 统一了screenWidth的计算逻辑,简化代码结构 --- src/ui/App.tsx | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/src/ui/App.tsx b/src/ui/App.tsx index e39fd03..582abaf 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -55,7 +55,13 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. const { exit } = useApp(); const { stdout, write } = useStdout(); const { columns } = useWindowSize(); + const { mode, setMode } = useRawModeContext(); const initialPromptSubmittedRef = useRef(false); + const processStdoutRef = useRef>(new Map()); + const rawModeRef = useRef(mode); + const writeRef = useRef(write); + const lastRenderedColumnsRef = useRef(null); + const messagesRef = useRef([]); const [view, setView] = useState("chat"); const [busy, setBusy] = useState(false); const [skills, setSkills] = useState([]); @@ -74,13 +80,8 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. const [nowTick, setNowTick] = useState(0); const [mcpStatuses, setMcpStatuses] = useState>([]); const [showProcessStdout, setShowProcessStdout] = useState(false); - const processStdoutRef = useRef>(new Map()); - const { mode, setMode } = useRawModeContext(); - const rawModeRef = useRef(mode); rawModeRef.current = mode; - - const messagesRef = useRef([]); messagesRef.current = messages; const sessionManager = useMemo(() => { @@ -172,7 +173,6 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. }; }, [sessionManager]); - const writeRef = useRef(write); writeRef.current = write; const handlePrompt = useCallback( async (submission: PromptSubmission) => { @@ -412,27 +412,21 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. [handleSelectSession, sessionManager, setMode] ); - const [stableColumns, setStableColumns] = useState(columns); - useEffect(() => { - const timer = setTimeout(() => setStableColumns(columns), 100); - return () => clearTimeout(timer); - }, [columns]); - const lastRenderedColumnsRef = useRef(null); useEffect(() => { if (!stdout?.isTTY) { return; } - if (stableColumns <= 0) { + if (columns <= 0) { return; } if (lastRenderedColumnsRef.current === null) { - lastRenderedColumnsRef.current = stableColumns; + lastRenderedColumnsRef.current = columns; return; } - if (lastRenderedColumnsRef.current === stableColumns) { + if (lastRenderedColumnsRef.current === columns) { return; } - lastRenderedColumnsRef.current = stableColumns; + lastRenderedColumnsRef.current = columns; if (mode === RawMode.Raw) { // In raw mode, re-render all messages directly to stdout at the new width. @@ -470,9 +464,9 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setMessages(nextMessages); setShowWelcome(true); }, 0); - }, [busy, mode, sessionManager, stableColumns, stdout]); + }, [busy, mode, sessionManager, columns, stdout]); - const screenWidth = useMemo(() => stableColumns ?? stdout?.columns ?? 80, [stableColumns, stdout]); + const screenWidth = useMemo(() => columns ?? stdout?.columns ?? 80, [columns, stdout]); const promptHistory = useMemo(() => { return messages .filter((message) => message.role === "user" && typeof message.content === "string") From 32da2ca695e0ff3e135dcbd591ca156554e97108 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Tue, 19 May 2026 15:28:38 +0800 Subject: [PATCH 071/129] =?UTF-8?q?feat(rawmode):=20=E6=B7=BB=E5=8A=A0=20R?= =?UTF-8?q?awMode=20=E6=8F=8F=E8=BF=B0=E4=BF=A1=E6=81=AF=E4=BB=A5=E5=A2=9E?= =?UTF-8?q?=E5=BC=BA=E5=8F=AF=E8=AF=BB=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ui/contexts/RawModeContext.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/ui/contexts/RawModeContext.tsx b/src/ui/contexts/RawModeContext.tsx index 6fbc706..3198a3a 100644 --- a/src/ui/contexts/RawModeContext.tsx +++ b/src/ui/contexts/RawModeContext.tsx @@ -10,14 +10,17 @@ export const RAW_COMMAND_MODELS: DropdownMenuItem[] = [ { label: "Lite mode", key: RawMode.Lite, + description: "Collapse chain-of-thought reasoning.", }, { label: "Normal mode", key: RawMode.None, + description: "Show full chain-of-thought reasoning.", }, { label: "Raw scrollback mode", key: RawMode.Raw, + description: "Show scrollback mode for copy-friendly terminal selection.", }, ] as const; From f9d2737f2737d195ab94e587d378c322f13b411a Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Tue, 19 May 2026 16:04:03 +0800 Subject: [PATCH 072/129] docs(notify): extract notification examples to standalone notify.md - Add docs/notify.md and docs/notify_en.md with Slack, Feishu, terminal, macOS, Linux, Windows msg, and custom notification examples - Simplify notify section in configuration.md / configuration_en.md to field description + env table + reference to notify docs - Replace external binfer.net link with docs/notify.md in README FAQ across README.md, README-zh_CN.md, README-en.md --- README-en.md | 2 +- README-zh_CN.md | 2 +- README.md | 2 +- docs/configuration.md | 32 +----- docs/configuration_en.md | 32 +----- docs/notify.md | 211 +++++++++++++++++++++++++++++++++++++++ docs/notify_en.md | 211 +++++++++++++++++++++++++++++++++++++++ 7 files changed, 429 insertions(+), 63 deletions(-) create mode 100644 docs/notify.md create mode 100644 docs/notify_en.md diff --git a/README-en.md b/README-en.md index 4c78cbd..55d0cf6 100644 --- a/README-en.md +++ b/README-en.md @@ -99,7 +99,7 @@ Deep Code supports multimodal input — you can paste images from the clipboard ### How to automatically send a Slack message after a task completes? -Write a shell notification script that calls a Slack webhook, then set the `notify` field in `~/.deepcode/settings.json` to the full path of the script. For detailed steps, refer to: https://binfer.net/share/jby5xnc-so6g +Write a shell notification script that calls a Slack webhook, then set the `notify` field in `~/.deepcode/settings.json` to the full path of the script. For detailed steps, see [docs/notify_en.md](docs/notify_en.md). ### How do I enable web search? diff --git a/README-zh_CN.md b/README-zh_CN.md index 98346b6..8a427de 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -99,7 +99,7 @@ Deep Code 支持多模态,可使用ctrl+v从剪贴板粘贴图片。但目前 ### 怎样在任务完成后自动给 Slack 发消息? -编写一个调用 Slack webhook 的 Shell 通知脚本,然后在 `~/.deepcode/settings.json` 中将 `notify` 字段设为该脚本的完整路径即可。详细步骤可参考:https://binfer.net/share/jby5xnc-so6g +编写一个调用 Slack webhook 的 Shell 通知脚本,然后在 `~/.deepcode/settings.json` 中将 `notify` 字段设为该脚本的完整路径即可。详细步骤请参考 [docs/notify.md](docs/notify.md)。 ### 怎样启用联网搜索功能? diff --git a/README.md b/README.md index 98346b6..8a427de 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ Deep Code 支持多模态,可使用ctrl+v从剪贴板粘贴图片。但目前 ### 怎样在任务完成后自动给 Slack 发消息? -编写一个调用 Slack webhook 的 Shell 通知脚本,然后在 `~/.deepcode/settings.json` 中将 `notify` 字段设为该脚本的完整路径即可。详细步骤可参考:https://binfer.net/share/jby5xnc-so6g +编写一个调用 Slack webhook 的 Shell 通知脚本,然后在 `~/.deepcode/settings.json` 中将 `notify` 字段设为该脚本的完整路径即可。详细步骤请参考 [docs/notify.md](docs/notify.md)。 ### 怎样启用联网搜索功能? diff --git a/docs/configuration.md b/docs/configuration.md index b05a44f..1cce9a1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -79,39 +79,11 @@ Deep Code 使用 `settings.json` 设置文件进行持久化配置,支持两 ```json { - "notify": "/path/to/slack-notify.sh" + "notify": "/path/to/notify-script.sh" } ``` -**飞书 Webhook 通知示例**: - -`node` 构建 JSON(自动转义特殊字符),`curl` 发送: - -```bash -#!/bin/bash -WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxx" - -STATUS="${STATUS:-completed}" -TITLE="${TITLE:-Untitled}" -DURATION="${DURATION:-0}" -BODY="${BODY:-(no output)}" - -PAYLOAD=$(node -e " -process.stdout.write(JSON.stringify({ - msg_type: 'interactive', - card: { - header: { title: { tag: 'plain_text', content: 'DeepCode: ' + process.env.TITLE + ' ' + process.env.STATUS + ' [' + process.env.DURATION + 's]' } }, - elements: [{ tag: 'markdown', content: (process.env.BODY || '').slice(0, 2000) || '(no output)' }] - } -})) -") - -curl -s -X POST "$WEBHOOK_URL" \ - -H "Content-Type: application/json" \ - -d "$PAYLOAD" -``` - -将 `WEBHOOK_URL` 替换为你的飞书机器人 Webhook 地址。更多变量参考上表。同样适用于 Slack、企业微信等 webhook 类通知,只需修改 JSON payload 格式。 +> 详细的 Slack、飞书、终端通知、系统通知等配置示例,请参阅 [notify.md](notify.md)。 #### `webSearchTool` — 自定义联网搜索 diff --git a/docs/configuration_en.md b/docs/configuration_en.md index 4f2f94d..fa396f9 100644 --- a/docs/configuration_en.md +++ b/docs/configuration_en.md @@ -79,39 +79,11 @@ The following context is injected as environment variables when the notify scrip ```json { - "notify": "/path/to/slack-notify.sh" + "notify": "/path/to/notify-script.sh" } ``` -**Feishu (Lark) Webhook Notification Example**: - -`node` builds the JSON (auto-escapes special characters), `curl` sends it: - -```bash -#!/bin/bash -WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxx" - -STATUS="${STATUS:-completed}" -TITLE="${TITLE:-Untitled}" -DURATION="${DURATION:-0}" -BODY="${BODY:-(no output)}" - -PAYLOAD=$(node -e " -process.stdout.write(JSON.stringify({ - msg_type: 'interactive', - card: { - header: { title: { tag: 'plain_text', content: 'DeepCode: ' + process.env.TITLE + ' ' + process.env.STATUS + ' [' + process.env.DURATION + 's]' } }, - elements: [{ tag: 'markdown', content: (process.env.BODY || '').slice(0, 2000) || '(no output)' }] - } -})) -") - -curl -s -X POST "$WEBHOOK_URL" \ - -H "Content-Type: application/json" \ - -d "$PAYLOAD" -``` - -Replace `WEBHOOK_URL` with your Feishu bot webhook URL. See the table above for all available variables. This pattern also works for other webhook-based notifications (Slack, WeCom, etc.) — just adjust the JSON payload format. +> For detailed configuration examples (Slack, Feishu, terminal notifications, system notifications, etc.), see [notify_en.md](notify_en.md). #### `webSearchTool` — Custom Web Search diff --git a/docs/notify.md b/docs/notify.md new file mode 100644 index 0000000..d73eef4 --- /dev/null +++ b/docs/notify.md @@ -0,0 +1,211 @@ +# Deep Code 任务完成通知 + +当 AI 助手完成一轮任务后,Deep Code 可以自动执行一个通知脚本,将任务结果发送到你指定的渠道(如 Slack、系统通知等)。 + +## 工作原理 + +在 `settings.json` 中配置 `notify` 字段,指向一个可执行脚本的完整路径。每次 AI 助手完成任务应答后,Deep Code 会执行该脚本,并通过环境变量注入上下文信息。 + +## 注入的环境变量 + +| 环境变量 | 说明 | +|----------|------| +| `DURATION` | 会话耗时,单位秒(整数) | +| `STATUS` | 会话状态:`"completed"` 或 `"failed"` | +| `FAIL_REASON` | 失败原因(仅失败时设置) | +| `BODY` | 最后一条 AI 助手回复的文本内容 | +| `TITLE` | 会话标题(对应 resume 列表中的标题) | + +## 配置方法 + +编辑 `~/.deepcode/settings.json`,添加 `notify` 字段: + +```json +{ + "env": { + "MODEL": "deepseek-v4-pro", + "BASE_URL": "https://api.deepseek.com", + "API_KEY": "sk-..." + }, + "thinkingEnabled": true, + "reasoningEffort": "max", + "notify": "/path/to/your-notify-script.sh" +} +``` + +你也可以在 `env` 中配置通知脚本所需的自定义环境变量,例如 Slack Webhook URL: + +```json +{ + "env": { + "MODEL": "deepseek-v4-pro", + "BASE_URL": "https://api.deepseek.com", + "API_KEY": "sk-...", + "SLACK_WEBHOOK_URL": "https://hooks.slack.com/services/*****/****/**********" + }, + "notify": "/Users/you/.deepcode/notify-slack.sh" +} +``` + +这些 `env` 中的变量会被注入到脚本的执行环境中。 + +## Slack 通知 + +### 1. 获取 Slack Webhook URL + +1. 创建 [Slack App](https://api.slack.com/apps) +2. 在 App 页面点击 **Incoming Webhooks** → **Add New Webhook to Workspace**,生成 Webhook URL + +### 2. 创建通知脚本 + +创建 `~/.deepcode/notify-slack.sh`: + +```bash +#!/usr/bin/env bash +SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}" +CURRENT_DIR=$(pwd) +BRANCH=$(git branch --show-current 2>/dev/null) +curl -X POST "$SLACK_WEBHOOK_URL" \ + -H "Content-type: application/json" \ + --data "{ + \"text\": \"✅ Deep Code 任务已完成\n · cwd: $CURRENT_DIR\n · Branch: $BRANCH\n · Duration: $DURATION 秒\" + }" +``` + +给脚本添加可执行权限: + +```bash +chmod +x ~/.deepcode/notify-slack.sh +``` + +### 3. 配置 settings.json + +```json +{ + "env": { + "SLACK_WEBHOOK_URL": "https://hooks.slack.com/services/*****/****/**********" + }, + "notify": "/Users/you/.deepcode/notify-slack.sh" +} +``` + +> Python 版本的脚本同样支持,你可以在 `env` 中传入并引用任意自定义环境变量。 + +## 飞书 / 企业微信等 Webhook 通知 + +以下示例使用 `node` 构建 JSON(自动转义特殊字符),`curl` 发送。通过 `env` 传入 `WEBHOOK_URL`: + +```bash +#!/bin/bash +WEBHOOK_URL="${WEBHOOK_URL:-}" + +STATUS="${STATUS:-completed}" +TITLE="${TITLE:-Untitled}" +DURATION="${DURATION:-0}" +BODY="${BODY:-(no output)}" + +PAYLOAD=$(node -e " +process.stdout.write(JSON.stringify({ + msg_type: 'interactive', + card: { + header: { title: { tag: 'plain_text', content: 'DeepCode: ' + process.env.TITLE + ' ' + process.env.STATUS + ' [' + process.env.DURATION + 's]' } }, + elements: [{ tag: 'markdown', content: (process.env.BODY || '').slice(0, 2000) || '(no output)' }] + } +})) +") + +curl -s -X POST "$WEBHOOK_URL" \ + -H "Content-Type: application/json" \ + -d "$PAYLOAD" +``` + +```json +{ + "env": { + "WEBHOOK_URL": "https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxx" + }, + "notify": "/Users/you/.deepcode/notify-feishu.sh" +} +``` + +将 `WEBHOOK_URL` 替换为你的飞书机器人 Webhook 地址。此模式同样适用于 Slack、企业微信等 webhook 类通知,只需修改 JSON payload 格式。 + +## 终端通知(iTerm2 / Windows Terminal) + +如果你的终端是 iTerm2 或 Windows Terminal,可以直接通过 OSC 9 转义序列弹出终端原生通知,无需额外依赖。 + +创建 `~/.deepcode/notify.sh`: + +```bash +#!/bin/bash +# iTerm2 / Windows Terminal OSC 9 通知 +printf '\x1b]9;DeepCode: task %s (%ss)\x07' "${STATUS:-completed}" "${DURATION}" +``` + +```json +{ + "notify": "/Users/you/.deepcode/notify.sh" +} +``` + +Windows 用户如使用 Git Bash,上述脚本同样可用;也可创建 `.bat` 脚本: + +```batch +@echo off +REM Windows Terminal OSC 9 通知 +echo \x1b]9;DeepCode: task %STATUS% (%DURATION%s)\x07 +``` + +## macOS 系统通知 + +```bash +#!/bin/bash +# macOS 系统通知 +osascript -e "display notification \"任务已${STATUS:-完成},耗时 ${DURATION}s\" with title \"DeepCode\"" +``` + +```json +{ + "notify": "/Users/you/.deepcode/notify.sh" +} +``` + +## Linux 系统通知 + +需要安装 `libnotify-bin`: + +```bash +sudo apt install libnotify-bin # Debian/Ubuntu +``` + +创建 `~/.deepcode/notify.sh`: + +```bash +#!/bin/bash +# Linux notify-send 通知 +notify-send "DeepCode" "任务已${STATUS:-完成},耗时 ${DURATION}s" +``` + +```json +{ + "notify": "/home/you/.deepcode/notify.sh" +} +``` + +## Windows msg 弹窗通知 + +```batch +@echo off +REM Windows msg 弹窗通知 +msg %USERNAME% "DeepCode: task %STATUS% (%DURATION%s)" +``` + +```json +{ + "notify": "C:\\Users\\you\\.deepcode\\notify.bat" +} +``` + +## 自定义通知脚本 + +你可以根据通知脚本注入的环境变量自行编写任意逻辑的通知脚本(Python、Node.js、Ruby 等均可),只要脚本可执行即可。脚本中可通过 `env` 字段传入额外需要的配置变量。 diff --git a/docs/notify_en.md b/docs/notify_en.md new file mode 100644 index 0000000..b949161 --- /dev/null +++ b/docs/notify_en.md @@ -0,0 +1,211 @@ +# Deep Code Task Completion Notification + +When the AI assistant finishes a round of tasks, Deep Code can automatically execute a notification script to send task results to your chosen channel (Slack, system notifications, etc.). + +## How It Works + +Configure the `notify` field in `settings.json` with the full path to an executable script. Every time the AI assistant completes a task response, Deep Code executes that script and injects context as environment variables. + +## Injected Environment Variables + +| Variable | Description | +|----------|-------------| +| `DURATION` | Session duration in seconds (integer) | +| `STATUS` | Session status: `"completed"` or `"failed"` | +| `FAIL_REASON` | Failure reason (only set on failure) | +| `BODY` | The text content of the last AI assistant reply | +| `TITLE` | Session title (matches the resume list title) | + +## Configuration + +Edit `~/.deepcode/settings.json` and add the `notify` field: + +```json +{ + "env": { + "MODEL": "deepseek-v4-pro", + "BASE_URL": "https://api.deepseek.com", + "API_KEY": "sk-..." + }, + "thinkingEnabled": true, + "reasoningEffort": "max", + "notify": "/path/to/your-notify-script.sh" +} +``` + +You can also configure custom environment variables for the notify script in `env`, such as a Slack Webhook URL: + +```json +{ + "env": { + "MODEL": "deepseek-v4-pro", + "BASE_URL": "https://api.deepseek.com", + "API_KEY": "sk-...", + "SLACK_WEBHOOK_URL": "https://hooks.slack.com/services/*****/****/**********" + }, + "notify": "/Users/you/.deepcode/notify-slack.sh" +} +``` + +These `env` variables are injected into the script's execution environment. + +## Slack Notification + +### 1. Get a Slack Webhook URL + +1. Create a [Slack App](https://api.slack.com/apps) +2. In the App page, go to **Incoming Webhooks** → **Add New Webhook to Workspace** to generate a Webhook URL + +### 2. Create the Notification Script + +Create `~/.deepcode/notify-slack.sh`: + +```bash +#!/usr/bin/env bash +SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}" +CURRENT_DIR=$(pwd) +BRANCH=$(git branch --show-current 2>/dev/null) +curl -X POST "$SLACK_WEBHOOK_URL" \ + -H "Content-type: application/json" \ + --data "{ + \"text\": \"✅ Deep Code task completed\n · cwd: $CURRENT_DIR\n · Branch: $BRANCH\n · Duration: $DURATION s\" + }" +``` + +Make the script executable: + +```bash +chmod +x ~/.deepcode/notify-slack.sh +``` + +### 3. Configure settings.json + +```json +{ + "env": { + "SLACK_WEBHOOK_URL": "https://hooks.slack.com/services/*****/****/**********" + }, + "notify": "/Users/you/.deepcode/notify-slack.sh" +} +``` + +> A Python version is also supported; you can pass and reference any custom environment variables via `env`. + +## Feishu / WeCom Webhook Notification + +Use `node` to build JSON (auto-escapes special characters) and `curl` to send. Pass `WEBHOOK_URL` via `env`: + +```bash +#!/bin/bash +WEBHOOK_URL="${WEBHOOK_URL:-}" + +STATUS="${STATUS:-completed}" +TITLE="${TITLE:-Untitled}" +DURATION="${DURATION:-0}" +BODY="${BODY:-(no output)}" + +PAYLOAD=$(node -e " +process.stdout.write(JSON.stringify({ + msg_type: 'interactive', + card: { + header: { title: { tag: 'plain_text', content: 'DeepCode: ' + process.env.TITLE + ' ' + process.env.STATUS + ' [' + process.env.DURATION + 's]' } }, + elements: [{ tag: 'markdown', content: (process.env.BODY || '').slice(0, 2000) || '(no output)' }] + } +})) +") + +curl -s -X POST "$WEBHOOK_URL" \ + -H "Content-Type: application/json" \ + -d "$PAYLOAD" +``` + +```json +{ + "env": { + "WEBHOOK_URL": "https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxx" + }, + "notify": "/Users/you/.deepcode/notify-feishu.sh" +} +``` + +Replace `WEBHOOK_URL` with your Feishu bot webhook URL. This pattern also works for other webhook-based notifications (Slack, WeCom, etc.) — just adjust the JSON payload format. + +## Terminal Notification (iTerm2 / Windows Terminal) + +On iTerm2 or Windows Terminal, you can use the OSC 9 escape sequence for native terminal notifications with zero dependencies. + +Create `~/.deepcode/notify.sh`: + +```bash +#!/bin/bash +# iTerm2 / Windows Terminal OSC 9 notification +printf '\x1b]9;DeepCode: task %s (%ss)\x07' "${STATUS:-completed}" "${DURATION}" +``` + +```json +{ + "notify": "/Users/you/.deepcode/notify.sh" +} +``` + +Windows users on Git Bash can use the same script; alternatively, create a `.bat` script: + +```batch +@echo off +REM Windows Terminal OSC 9 notification +echo \x1b]9;DeepCode: task %STATUS% (%DURATION%s)\x07 +``` + +## macOS System Notification + +```bash +#!/bin/bash +# macOS system notification +osascript -e "display notification \"Task ${STATUS:-completed}, took ${DURATION}s\" with title \"DeepCode\"" +``` + +```json +{ + "notify": "/Users/you/.deepcode/notify.sh" +} +``` + +## Linux System Notification + +Requires `libnotify-bin`: + +```bash +sudo apt install libnotify-bin # Debian/Ubuntu +``` + +Create `~/.deepcode/notify.sh`: + +```bash +#!/bin/bash +# Linux notify-send notification +notify-send "DeepCode" "Task ${STATUS:-completed}, took ${DURATION}s" +``` + +```json +{ + "notify": "/home/you/.deepcode/notify.sh" +} +``` + +## Windows msg Popup Notification + +```batch +@echo off +REM Windows msg popup notification +msg %USERNAME% "DeepCode: task %STATUS% (%DURATION%s)" +``` + +```json +{ + "notify": "C:\\Users\\you\\.deepcode\\notify.bat" +} +``` + +## Custom Notification Scripts + +You can write your own notification scripts in any language (Python, Node.js, Ruby, etc.) using the injected environment variables and any additional variables passed via `env`. From 1bd7e6a38c3f0f58a9b6971ba31d8c888d9f975d Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 16:24:40 +0800 Subject: [PATCH 073/129] perf: reuse OpenAI client instance and add connection warmup Cache the OpenAI client at module level keyed by (apiKey, baseURL) to avoid creating a fresh HTTP connection pool on every LLM turn. The client is a stateless fetch wrapper so sharing across calls is safe. Model, thinking-mode and other settings are still read fresh from config files each time. Also add a mount-time warmup effect that eagerly creates the client so the TCP+TLS connection is established while the user composes their first prompt. --- .gitignore | 1 + src/ui/App.tsx | 41 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 11b67ce..dd972a7 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ dist/ .vscode/ *.tgz *.log +scripts/ diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 582abaf..e82e5f3 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -162,6 +162,13 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. void refreshSkills(); }, [refreshSessionsList, refreshSkills]); + // Eagerly create the OpenAI client on mount so the TCP+TLS connection + // warmup (fire-and-forget inside createOpenAIClient) starts before the + // user sends their first prompt. + useEffect(() => { + createOpenAIClient(projectRoot); + }, [projectRoot]); + useLayoutEffect(() => { const settings = resolveCurrentSettings(projectRoot); void sessionManager.initMcpServers(settings.mcpServers); @@ -721,6 +728,13 @@ export function resolveCurrentSettings(projectRoot: string = process.cwd()): Res ); } +// Module-level cache for the OpenAI client instance. The client itself is +// a stateless fetch wrapper, so it is safe to share across calls as long as +// the apiKey + baseURL stay the same. Model, thinking-mode and other +// settings are always read fresh from the project / user config files. +let _cachedOpenAI: OpenAI | null = null; +let _cachedOpenAIKey = ""; + export function createOpenAIClient(projectRoot: string = process.cwd()): { client: OpenAI | null; model: string; @@ -749,12 +763,35 @@ export function createOpenAIClient(projectRoot: string = process.cwd()): { }; } - const client = new OpenAI({ + const cacheKey = `${settings.apiKey}::${settings.baseURL}`; + if (_cachedOpenAI && _cachedOpenAIKey === cacheKey) { + return { + client: _cachedOpenAI, + model: settings.model, + baseURL: settings.baseURL, + thinkingEnabled: settings.thinkingEnabled, + reasoningEffort: settings.reasoningEffort, + debugLogEnabled: settings.debugLogEnabled, + notify: settings.notify, + webSearchTool: settings.webSearchTool, + env: settings.env, + machineId: getMachineId(), + }; + } + + _cachedOpenAI = new OpenAI({ apiKey: settings.apiKey, baseURL: settings.baseURL || undefined, }); + _cachedOpenAIKey = cacheKey; + + // Fire-and-forget warmup: pre-establish TCP+TLS connection to the API + // server while the user is composing their first prompt. Errors are + // silently ignored — the real request will retry on its own if needed. + void _cachedOpenAI.models.list().catch(() => {}); + return { - client, + client: _cachedOpenAI, model: settings.model, baseURL: settings.baseURL, thinkingEnabled: settings.thinkingEnabled, From 2e5b2ed2a4eed8c463546385ecbf374002a8d6c6 Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 16:54:30 +0800 Subject: [PATCH 074/129] perf: replace undici fetch with custom https.Agent for long keepAlive MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The default undici-based global fetch only keeps connections alive for 4 seconds, which is too short for a CLI where the user may spend 10–30 seconds reading output before typing the next prompt. Add a custom fetch implementation backed by node:https.Agent with keepAlive: true and a 60-second idle timeout. The custom fetch is passed to the OpenAI SDK constructor so every LLM API request benefits from persistent connections across conversational turns. Also handles streaming request bodies (ReadableStream) for SDK features like file uploads. --- src/ui/App.tsx | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/src/ui/App.tsx b/src/ui/App.tsx index e82e5f3..1cdd855 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useSta import { Box, Static, Text, useApp, useStdout, useWindowSize } from "ink"; import chalk from "chalk"; import * as fs from "fs"; +import https from "node:https"; import * as os from "os"; import * as path from "path"; import OpenAI from "openai"; @@ -728,6 +729,99 @@ export function resolveCurrentSettings(projectRoot: string = process.cwd()): Res ); } +// Custom fetch implementation that uses node:https.Agent with a configurable +// keepAlive timeout. The default undici-based global fetch only keeps +// connections alive for 4 seconds, which is too short for a CLI where the +// user may spend 10–30 seconds reading output before typing the next prompt. +// With this custom Agent we get full control over idle connection lifetime. +const KEEP_ALIVE_MSEC = 60_000; // 1 minute + +function createCustomFetch(keepAliveMsecs: number = KEEP_ALIVE_MSEC) { + const agent = new https.Agent({ keepAlive: true, keepAliveMsecs }); + + return async function customFetch(url: string | URL | Request, init?: RequestInit): Promise { + const urlObj = typeof url === "string" ? new URL(url) : url instanceof URL ? url : new URL(url.url); + const { method = "GET", headers = {}, body: reqBody, signal } = init ?? {}; + + // Normalize Headers to a plain Record + const plainHeaders: Record = {}; + if (headers instanceof Headers) { + for (const [k, v] of headers) plainHeaders[k] = v; + } else if (Array.isArray(headers)) { + for (const [k, v] of headers) plainHeaders[k] = v; + } else { + Object.assign(plainHeaders, headers); + } + + const port = urlObj.port ? Number(urlObj.port) : 443; + + return new Promise((resolve, reject) => { + const req = https.request( + { + hostname: urlObj.hostname, + port, + path: urlObj.pathname + urlObj.search, + method, + headers: plainHeaders, + agent, + signal: signal ?? undefined, + }, + (res) => { + const resHeaders = new Headers(); + for (const [k, v] of Object.entries(res.headers)) { + if (v) (Array.isArray(v) ? v : [v]).forEach((val) => resHeaders.append(k, val)); + } + + const body = new ReadableStream({ + start(controller) { + res.on("data", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk))); + res.on("end", () => controller.close()); + res.on("error", (err) => controller.error(err)); + }, + cancel() { + res.destroy(); + }, + }); + + resolve( + new Response(body, { + status: res.statusCode, + statusText: res.statusMessage, + headers: resHeaders, + }) + ); + } + ); + + req.on("error", reject); + + if (reqBody) { + if (typeof reqBody === "string" || reqBody instanceof Uint8Array || ArrayBuffer.isView(reqBody)) { + req.write(reqBody as Parameters[0]); + } else if (reqBody instanceof ReadableStream) { + // Pipe streaming request body (used for file uploads by the SDK) + const reader = (reqBody as ReadableStream).getReader(); + (async () => { + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value) req.write(value); + } + req.end(); + } catch (err) { + req.destroy(err instanceof Error ? err : new Error(String(err))); + } + })(); + return; // req.end() is called inside the async IIFE + } + } + + req.end(); + }); + }; +} + // Module-level cache for the OpenAI client instance. The client itself is // a stateless fetch wrapper, so it is safe to share across calls as long as // the apiKey + baseURL stay the same. Model, thinking-mode and other @@ -782,6 +876,7 @@ export function createOpenAIClient(projectRoot: string = process.cwd()): { _cachedOpenAI = new OpenAI({ apiKey: settings.apiKey, baseURL: settings.baseURL || undefined, + fetch: createCustomFetch(), }); _cachedOpenAIKey = cacheKey; From 6f8d2e228d853f8014741c8108f6936e7d037c82 Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 17:04:09 +0800 Subject: [PATCH 075/129] refactor: replace custom fetch wrapper with undici Agent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use npm undici's Agent with keepAliveTimeout: 60s instead of the 90-line custom https.Agent-based fetch wrapper. The approach is the same but much simpler — just pass undiciFetch with a configured Agent dispatcher to the OpenAI SDK. --- src/ui/App.tsx | 103 +++++-------------------------------------------- 1 file changed, 9 insertions(+), 94 deletions(-) diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 1cdd855..42397a5 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -2,10 +2,10 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useSta import { Box, Static, Text, useApp, useStdout, useWindowSize } from "ink"; import chalk from "chalk"; import * as fs from "fs"; -import https from "node:https"; import * as os from "os"; import * as path from "path"; import OpenAI from "openai"; +import { Agent, fetch as undiciFetch } from "undici"; import { type LlmStreamProgress, type MessageMeta, @@ -729,98 +729,12 @@ export function resolveCurrentSettings(projectRoot: string = process.cwd()): Res ); } -// Custom fetch implementation that uses node:https.Agent with a configurable -// keepAlive timeout. The default undici-based global fetch only keeps -// connections alive for 4 seconds, which is too short for a CLI where the -// user may spend 10–30 seconds reading output before typing the next prompt. -// With this custom Agent we get full control over idle connection lifetime. -const KEEP_ALIVE_MSEC = 60_000; // 1 minute - -function createCustomFetch(keepAliveMsecs: number = KEEP_ALIVE_MSEC) { - const agent = new https.Agent({ keepAlive: true, keepAliveMsecs }); - - return async function customFetch(url: string | URL | Request, init?: RequestInit): Promise { - const urlObj = typeof url === "string" ? new URL(url) : url instanceof URL ? url : new URL(url.url); - const { method = "GET", headers = {}, body: reqBody, signal } = init ?? {}; - - // Normalize Headers to a plain Record - const plainHeaders: Record = {}; - if (headers instanceof Headers) { - for (const [k, v] of headers) plainHeaders[k] = v; - } else if (Array.isArray(headers)) { - for (const [k, v] of headers) plainHeaders[k] = v; - } else { - Object.assign(plainHeaders, headers); - } - - const port = urlObj.port ? Number(urlObj.port) : 443; - - return new Promise((resolve, reject) => { - const req = https.request( - { - hostname: urlObj.hostname, - port, - path: urlObj.pathname + urlObj.search, - method, - headers: plainHeaders, - agent, - signal: signal ?? undefined, - }, - (res) => { - const resHeaders = new Headers(); - for (const [k, v] of Object.entries(res.headers)) { - if (v) (Array.isArray(v) ? v : [v]).forEach((val) => resHeaders.append(k, val)); - } - - const body = new ReadableStream({ - start(controller) { - res.on("data", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk))); - res.on("end", () => controller.close()); - res.on("error", (err) => controller.error(err)); - }, - cancel() { - res.destroy(); - }, - }); - - resolve( - new Response(body, { - status: res.statusCode, - statusText: res.statusMessage, - headers: resHeaders, - }) - ); - } - ); - - req.on("error", reject); - - if (reqBody) { - if (typeof reqBody === "string" || reqBody instanceof Uint8Array || ArrayBuffer.isView(reqBody)) { - req.write(reqBody as Parameters[0]); - } else if (reqBody instanceof ReadableStream) { - // Pipe streaming request body (used for file uploads by the SDK) - const reader = (reqBody as ReadableStream).getReader(); - (async () => { - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - if (value) req.write(value); - } - req.end(); - } catch (err) { - req.destroy(err instanceof Error ? err : new Error(String(err))); - } - })(); - return; // req.end() is called inside the async IIFE - } - } - - req.end(); - }); - }; -} +// Custom undici Agent with a 60-second keepAlive timeout. The default +// global fetch (undici) only keeps connections alive for 4 seconds, which +// is too short for a CLI where the user may spend 10–30 seconds reading +// output between prompts. By passing a dedicated Agent to undiciFetch we +// keep connections reusable for a full minute after the last request. +const _keepAliveAgent = new Agent({ keepAliveTimeout: 60_000 }); // Module-level cache for the OpenAI client instance. The client itself is // a stateless fetch wrapper, so it is safe to share across calls as long as @@ -876,7 +790,8 @@ export function createOpenAIClient(projectRoot: string = process.cwd()): { _cachedOpenAI = new OpenAI({ apiKey: settings.apiKey, baseURL: settings.baseURL || undefined, - fetch: createCustomFetch(), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + fetch: (url: any, init: any) => undiciFetch(url, { ...init, dispatcher: _keepAliveAgent }), }); _cachedOpenAIKey = cacheKey; From 5d48d41b0c46813478f1b055671e9e32181c840f Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Tue, 19 May 2026 17:31:52 +0800 Subject: [PATCH 076/129] feat(bash): Add Bash timeout control feature and related adjustments --- src/common/bash-timeout.ts | 12 +++ src/session.ts | 138 +++++++++++++++++++++++++++++--- src/tests/session.test.ts | 34 ++++++++ src/tests/tool-handlers.test.ts | 54 ++++++++++++- src/tools/bash-handler.ts | 106 ++++++++++++++++++++++-- src/tools/executor.ts | 17 ++++ src/ui/App.tsx | 10 ++- src/ui/ProcessStdoutView.tsx | 111 +++++++++++++++++++++---- src/ui/PromptInput.tsx | 4 +- 9 files changed, 450 insertions(+), 36 deletions(-) create mode 100644 src/common/bash-timeout.ts diff --git a/src/common/bash-timeout.ts b/src/common/bash-timeout.ts new file mode 100644 index 0000000..0a76d21 --- /dev/null +++ b/src/common/bash-timeout.ts @@ -0,0 +1,12 @@ +export const DEFAULT_BASH_TIMEOUT_MS = 10 * 60 * 1000; +export const MIN_BASH_TIMEOUT_MS = 60 * 1000; +export const BASH_TIMEOUT_INCREMENT_MS = 5 * 60 * 1000; +export const BASH_TIMEOUT_DECREMENT_MS = 60 * 1000; + +export function clampBashTimeoutMs(timeoutMs: number, minTimeoutMs: number = MIN_BASH_TIMEOUT_MS): number { + if (!Number.isFinite(timeoutMs)) { + return DEFAULT_BASH_TIMEOUT_MS; + } + const minimum = Number.isFinite(minTimeoutMs) ? Math.max(1, Math.round(minTimeoutMs)) : MIN_BASH_TIMEOUT_MS; + return Math.max(minimum, Math.round(timeoutMs)); +} diff --git a/src/session.ts b/src/session.ts index 3b6b67a..10e0782 100644 --- a/src/session.ts +++ b/src/session.ts @@ -17,7 +17,12 @@ import { getTools, type ToolDefinition, } from "./prompt"; -import { ToolExecutor, type CreateOpenAIClient } from "./tools/executor"; +import { + ToolExecutor, + type CreateOpenAIClient, + type ProcessTimeoutControl, + type ProcessTimeoutInfo, +} from "./tools/executor"; import { McpManager } from "./mcp/mcp-manager"; import type { McpServerConfig } from "./settings"; import { logApiError } from "./common/error-logger"; @@ -134,6 +139,21 @@ export type ModelUsage = { total_reqs?: number; }; +export type SessionProcessEntry = { + startTime: string; + command: string; + timeoutMs?: number; + deadlineAt?: string; + timedOut?: boolean; +}; + +export type BashTimeoutAdjustment = { + processId: string; + timeoutMs: number; + deadlineAt: string; + timedOut: boolean; +}; + export type SessionEntry = { id: string; summary: string | null; @@ -148,7 +168,7 @@ export type SessionEntry = { activeTokens: number; createTime: string; updateTime: string; - processes: Map | null; // {pid: {startTime, command}} + processes: Map | null; // {pid: process info} }; export type SessionsIndex = { @@ -234,6 +254,7 @@ export class SessionManager { private activeSessionId: string | null = null; private activePromptController: AbortController | null = null; private readonly sessionControllers = new Map(); + private readonly processTimeoutControls = new Map(); private readonly toolExecutor: ToolExecutor; private readonly mcpManager = new McpManager(); private mcpToolDefinitions: ToolDefinition[] = []; @@ -1360,6 +1381,7 @@ ${skillMd} const killedPids: number[] = []; const failedPids: number[] = []; for (const pid of processIds) { + this.processTimeoutControls.delete(this.getProcessControlKey(sessionId, pid)); if (killProcessTree(pid, "SIGKILL")) { killedPids.push(pid); continue; @@ -1397,6 +1419,37 @@ ${skillMd} return !this.sessionControllers.has(sessionId); } + adjustActiveBashTimeout(deltaMs: number): BashTimeoutAdjustment | null { + const sessionId = this.activeSessionId; + if (!sessionId || !Number.isFinite(deltaMs)) { + return null; + } + const session = this.getSession(sessionId); + if (!session?.processes) { + return null; + } + + let selectedPid: string | null = null; + for (const pid of session.processes.keys()) { + if (this.processTimeoutControls.has(this.getProcessControlKey(sessionId, pid))) { + selectedPid = pid; + } + } + if (!selectedPid) { + return null; + } + + const control = this.processTimeoutControls.get(this.getProcessControlKey(sessionId, selectedPid)); + if (!control) { + return null; + } + + const current = control.getInfo(); + const next = control.setTimeoutMs(current.timeoutMs + deltaMs); + this.updateSessionProcessTimeout(sessionId, selectedPid, next); + return this.buildBashTimeoutAdjustment(selectedPid, next); + } + listSessions(): SessionEntry[] { const index = this.loadSessionsIndex(); return index.entries; @@ -1741,6 +1794,7 @@ ${skillMd} onProcessStart: (pid, command) => this.addSessionProcess(sessionId, pid, command), onProcessExit: (pid) => this.removeSessionProcess(sessionId, pid), onProcessStdout: (pid, chunk) => this.onProcessStdout?.(Number(pid), chunk), + onProcessTimeoutControl: (pid, control) => this.setSessionProcessTimeoutControl(sessionId, pid, control), shouldStop: () => this.isInterrupted(sessionId), }); if (this.isInterrupted(sessionId)) { @@ -2137,6 +2191,7 @@ ${skillMd} private removeSessionProcess(sessionId: string, processId: string | number): void { const now = new Date().toISOString(); + this.processTimeoutControls.delete(this.getProcessControlKey(sessionId, processId)); this.updateSessionEntry(sessionId, (entry) => { const processes = new Map(entry.processes ?? []); processes.delete(String(processId)); @@ -2148,7 +2203,58 @@ ${skillMd} }); } - private getProcessIds(processes: Map | null): number[] { + private setSessionProcessTimeoutControl( + sessionId: string, + processId: string | number, + control: ProcessTimeoutControl | null + ): void { + const key = this.getProcessControlKey(sessionId, processId); + if (!control) { + this.processTimeoutControls.delete(key); + return; + } + + this.processTimeoutControls.set(key, control); + this.updateSessionProcessTimeout(sessionId, processId, control.getInfo()); + } + + private updateSessionProcessTimeout(sessionId: string, processId: string | number, info: ProcessTimeoutInfo): void { + const now = new Date().toISOString(); + this.updateSessionEntry(sessionId, (entry) => { + const processes = new Map(entry.processes ?? []); + const pid = String(processId); + const processInfo = processes.get(pid); + if (!processInfo) { + return entry; + } + processes.set(pid, { + ...processInfo, + timeoutMs: info.timeoutMs, + deadlineAt: new Date(info.deadlineAtMs).toISOString(), + timedOut: info.timedOut, + }); + return { + ...entry, + processes, + updateTime: now, + }; + }); + } + + private buildBashTimeoutAdjustment(processId: string, info: ProcessTimeoutInfo): BashTimeoutAdjustment { + return { + processId, + timeoutMs: info.timeoutMs, + deadlineAt: new Date(info.deadlineAtMs).toISOString(), + timedOut: info.timedOut, + }; + } + + private getProcessControlKey(sessionId: string, processId: string | number): string { + return `${sessionId}:${String(processId)}`; + } + + private getProcessIds(processes: Map | null): number[] { if (!processes) { return []; } @@ -2232,11 +2338,11 @@ ${skillMd} return usagePerModel; } - private deserializeProcesses(value: unknown): Map | null { + private deserializeProcesses(value: unknown): Map | null { if (!value || typeof value !== "object") { return null; } - const processes = new Map(); + const processes = new Map(); for (const [pid, entry] of Object.entries(value as Record)) { if (!pid) { continue; @@ -2245,22 +2351,34 @@ ${skillMd} // Backward compatibility for old format where just stored start time processes.set(pid, { startTime: entry, command: "Running process..." }); } else if (typeof entry === "object" && entry !== null) { - const obj = entry as { startTime?: unknown; command?: unknown }; + const obj = entry as { + startTime?: unknown; + command?: unknown; + timeoutMs?: unknown; + deadlineAt?: unknown; + timedOut?: unknown; + }; const startTime = typeof obj.startTime === "string" ? obj.startTime : new Date().toISOString(); const command = typeof obj.command === "string" ? obj.command : "Running process..."; - processes.set(pid, { startTime, command }); + processes.set(pid, { + startTime, + command, + timeoutMs: typeof obj.timeoutMs === "number" ? obj.timeoutMs : undefined, + deadlineAt: typeof obj.deadlineAt === "string" ? obj.deadlineAt : undefined, + timedOut: typeof obj.timedOut === "boolean" ? obj.timedOut : undefined, + }); } } return processes.size > 0 ? processes : null; } private serializeProcesses( - processes: Map | null - ): Record | null { + processes: Map | null + ): Record | null { if (!processes || processes.size === 0) { return null; } - const serialized: Record = {}; + const serialized: Record = {}; for (const [pid, entry] of processes.entries()) { serialized[pid] = entry; } diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index b7eadae..2ab4fe9 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1641,6 +1641,40 @@ test("SessionManager treats OpenAI APIUserAbortError as interrupted", async () = assert.equal(session?.failReason, "interrupted"); }); +test("SessionManager adjusts the active Bash timeout control and session metadata", async () => { + const workspace = createTempDir("deepcode-bash-timeout-session-"); + const manager = createSessionManager(workspace, ""); + const sessionId = await manager.createSession({ text: "hello" }); + + (manager as any).addSessionProcess(sessionId, 123, "sleep 10"); + + let timeoutInfo = { + timeoutMs: 10 * 60 * 1000, + startedAtMs: 1000, + deadlineAtMs: 1000 + 10 * 60 * 1000, + timedOut: false, + }; + (manager as any).setSessionProcessTimeoutControl(sessionId, 123, { + getInfo: () => timeoutInfo, + setTimeoutMs: (timeoutMs: number) => { + timeoutInfo = { + ...timeoutInfo, + timeoutMs, + deadlineAtMs: timeoutInfo.startedAtMs + timeoutMs, + }; + return timeoutInfo; + }, + }); + + const adjustment = manager.adjustActiveBashTimeout(5 * 60 * 1000); + const processInfo = manager.getSession(sessionId)?.processes?.get("123"); + + assert.equal(adjustment?.processId, "123"); + assert.equal(adjustment?.timeoutMs, 15 * 60 * 1000); + assert.equal(processInfo?.timeoutMs, 15 * 60 * 1000); + assert.equal(processInfo?.deadlineAt, new Date(timeoutInfo.deadlineAtMs).toISOString()); +}); + function createSessionManager(projectRoot: string, machineId: string): SessionManager { return new SessionManager({ projectRoot, diff --git a/src/tests/tool-handlers.test.ts b/src/tests/tool-handlers.test.ts index 0b21edd..f66153c 100644 --- a/src/tests/tool-handlers.test.ts +++ b/src/tests/tool-handlers.test.ts @@ -4,7 +4,7 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; import { setTimeout as delay } from "node:timers/promises"; -import type { ToolExecutionContext } from "../tools/executor"; +import type { ProcessTimeoutControl, ToolExecutionContext } from "../tools/executor"; import { handleBashTool } from "../tools/bash-handler"; import { handleEditTool } from "../tools/edit-handler"; import { handleReadTool } from "../tools/read-handler"; @@ -52,6 +52,58 @@ test("Bash streams stdout and stderr before command completion", async () => { assert.match(streamedOutput, /err/); }); +test("Bash terminates commands that exceed the configured timeout", async () => { + const workspace = createTempWorkspace(); + const exitedPids: Array = []; + + const result = await handleBashTool( + { + command: "printf 'start\\n'; sleep 5; printf 'done\\n'", + }, + createContext("bash-timeout", workspace, { + bashTimeoutMs: 100, + bashMinTimeoutMs: 1, + onProcessExit: (pid) => { + exitedPids.push(pid); + }, + }) + ); + + assert.equal(result.ok, false); + assert.equal(result.error, "Command timed out."); + assert.equal(result.metadata?.timedOut, true); + assert.equal(result.metadata?.timeoutMs, 100); + assert.doesNotMatch(result.output ?? "", /done/); + assert.equal(exitedPids.length, 1); +}); + +test("Bash timeout control can extend the active command deadline", async () => { + const workspace = createTempWorkspace(); + let timeoutControl: ProcessTimeoutControl | null = null; + + const result = await handleBashTool( + { + command: "sleep 0.2; printf 'done\\n'", + }, + createContext("bash-timeout-extend", workspace, { + bashTimeoutMs: 100, + bashMinTimeoutMs: 1, + onProcessTimeoutControl: (_pid, control) => { + if (control) { + timeoutControl = control; + control.setTimeoutMs(1000); + } + }, + }) + ); + + assert.ok(timeoutControl); + assert.equal(result.ok, true); + assert.match(result.output ?? "", /done/); + assert.equal(result.metadata?.timedOut, false); + assert.equal(result.metadata?.timeoutMs, 1000); +}); + test("UpdatePlan accepts a markdown task list string", async () => { const workspace = createTempWorkspace(); const plan = ["## Task List", "", "- [>] Inspect current behavior", "- [ ] Implement UpdatePlan"].join("\n"); diff --git a/src/tools/bash-handler.ts b/src/tools/bash-handler.ts index 071da53..4272271 100644 --- a/src/tools/bash-handler.ts +++ b/src/tools/bash-handler.ts @@ -1,5 +1,7 @@ import { spawn } from "child_process"; -import type { ToolExecutionContext, ToolExecutionResult } from "./executor"; +import { DEFAULT_BASH_TIMEOUT_MS, clampBashTimeoutMs } from "../common/bash-timeout"; +import { killProcessTree } from "../common/process-tree"; +import type { ProcessTimeoutControl, ProcessTimeoutInfo, ToolExecutionContext, ToolExecutionResult } from "./executor"; import { buildDisableExtglobCommand, buildShellEnv, @@ -22,6 +24,9 @@ type ToolCommandResult = { truncated: boolean; shellPath?: string; startCwd?: string; + timedOut?: boolean; + timeoutMs?: number; + deadlineAt?: string; }; export async function handleBashTool( @@ -48,12 +53,15 @@ export async function handleBashTool( execution.exitCode, execution.signal, shellPath, - startCwd + startCwd, + execution.timedOut, + execution.timeoutMs, + execution.deadlineAtMs ); updateSessionCwd(context.sessionId, startCwd, result.cwd); if (execution.error || result.exitCode !== 0 || result.signal !== null) { - const errorMessage = buildErrorMessage(result.exitCode, result.signal, execution.error); + const errorMessage = buildErrorMessage(result.exitCode, result.signal, execution.error, execution.timedOut); return formatResult({ ...result, ok: false }, "bash", errorMessage); } @@ -102,10 +110,27 @@ async function executeShellCommand( cwd: string, command: string, context: ToolExecutionContext -): Promise<{ stdout: string; stderr: string; exitCode: number | null; signal: string | null; error?: string }> { +): Promise<{ + stdout: string; + stderr: string; + exitCode: number | null; + signal: string | null; + error?: string; + timedOut: boolean; + timeoutMs: number; + deadlineAtMs: number; +}> { return new Promise((resolve) => { const detached = process.platform !== "win32"; const configuredEnv = context.createOpenAIClient?.().env ?? {}; + const minTimeoutMs = context.bashMinTimeoutMs; + const initialTimeoutMs = clampBashTimeoutMs(context.bashTimeoutMs ?? DEFAULT_BASH_TIMEOUT_MS, minTimeoutMs); + const startedAtMs = Date.now(); + let timeoutMs = initialTimeoutMs; + let deadlineAtMs = startedAtMs + timeoutMs; + let timedOut = false; + let settled = false; + let timeoutTimer: ReturnType | null = null; const child = spawn(shellPath, shellArgs, { cwd, env: buildShellEnv(shellPath, configuredEnv), @@ -114,8 +139,53 @@ async function executeShellCommand( stdio: ["ignore", "pipe", "pipe"], }); const pid = child.pid; + + const getTimeoutInfo = (): ProcessTimeoutInfo => ({ + timeoutMs, + startedAtMs, + deadlineAtMs, + timedOut, + }); + const stopTimeoutTimer = () => { + if (timeoutTimer) { + clearTimeout(timeoutTimer); + timeoutTimer = null; + } + }; + const triggerTimeout = () => { + if (settled || timedOut || typeof pid !== "number") { + return; + } + timedOut = true; + stopTimeoutTimer(); + killProcessTree(pid, "SIGKILL"); + }; + const scheduleTimeout = () => { + stopTimeoutTimer(); + if (settled) { + return; + } + const remainingMs = Math.max(0, deadlineAtMs - Date.now()); + timeoutTimer = setTimeout(triggerTimeout, remainingMs); + }; + const timeoutControl: ProcessTimeoutControl = { + getInfo: getTimeoutInfo, + setTimeoutMs: (nextTimeoutMs) => { + timeoutMs = clampBashTimeoutMs(nextTimeoutMs, minTimeoutMs); + deadlineAtMs = startedAtMs + timeoutMs; + if (deadlineAtMs <= Date.now()) { + triggerTimeout(); + } else { + scheduleTimeout(); + } + return getTimeoutInfo(); + }, + }; + if (typeof pid === "number") { context.onProcessStart?.(pid, command); + context.onProcessTimeoutControl?.(pid, timeoutControl); + scheduleTimeout(); } let stdout = ""; @@ -138,7 +208,10 @@ async function executeShellCommand( }); child.on("close", (code, signal) => { + settled = true; + stopTimeoutTimer(); if (typeof pid === "number") { + context.onProcessTimeoutControl?.(pid, null); context.onProcessExit?.(pid); } resolve({ @@ -147,6 +220,9 @@ async function executeShellCommand( exitCode: typeof code === "number" ? code : null, signal: signal ?? null, error, + timedOut, + timeoutMs, + deadlineAtMs, }); }); }); @@ -173,7 +249,10 @@ function buildToolCommandResult( exitCode: number | null, signal: string | null, shellPath: string, - startCwd: string + startCwd: string, + timedOut: boolean = false, + timeoutMs?: number, + deadlineAtMs?: number ): ToolCommandResult { const { output: cleanedStdout, cwd } = stripMarker(stdout, marker); const combined = joinOutput(cleanedStdout, stderr); @@ -187,6 +266,9 @@ function buildToolCommandResult( truncated, shellPath, startCwd, + timedOut, + timeoutMs, + deadlineAt: typeof deadlineAtMs === "number" ? new Date(deadlineAtMs).toISOString() : undefined, }; } @@ -231,10 +313,13 @@ function truncateOutput(output: string): { text: string; truncated: boolean } { return { text: output.slice(0, MAX_OUTPUT_CHARS), truncated: true }; } -function buildErrorMessage(exitCode: number | null, signal: string | null, error?: string): string { +function buildErrorMessage(exitCode: number | null, signal: string | null, error?: string, timedOut = false): string { if (error) { return error; } + if (timedOut) { + return "Command timed out."; + } if (signal) { return `Command terminated by signal ${signal}.`; } @@ -253,6 +338,15 @@ function formatResult(result: ToolCommandResult, name: string, errorMessage?: st shellPath: result.shellPath, startCwd: result.startCwd, }; + if (typeof result.timedOut === "boolean") { + metadata.timedOut = result.timedOut; + } + if (typeof result.timeoutMs === "number") { + metadata.timeoutMs = result.timeoutMs; + } + if (result.deadlineAt) { + metadata.deadlineAt = result.deadlineAt; + } const outputValue = result.output ? result.output : undefined; diff --git a/src/tools/executor.ts b/src/tools/executor.ts index 70ceab1..093e9f3 100644 --- a/src/tools/executor.ts +++ b/src/tools/executor.ts @@ -39,15 +39,31 @@ export type ToolExecutionContext = { onProcessStart?: (processId: string | number, command: string) => void; onProcessExit?: (processId: string | number) => void; onProcessStdout?: (processId: string | number, chunk: string) => void; + onProcessTimeoutControl?: (processId: string | number, control: ProcessTimeoutControl | null) => void; + bashTimeoutMs?: number; + bashMinTimeoutMs?: number; }; export type ToolExecutionHooks = { onProcessStart?: (processId: string | number, command: string) => void; onProcessExit?: (processId: string | number) => void; onProcessStdout?: (processId: string | number, chunk: string) => void; + onProcessTimeoutControl?: (processId: string | number, control: ProcessTimeoutControl | null) => void; shouldStop?: () => boolean; }; +export type ProcessTimeoutInfo = { + timeoutMs: number; + startedAtMs: number; + deadlineAtMs: number; + timedOut: boolean; +}; + +export type ProcessTimeoutControl = { + getInfo: () => ProcessTimeoutInfo; + setTimeoutMs: (timeoutMs: number) => ProcessTimeoutInfo; +}; + export type ToolExecutionResult = { ok: boolean; name: string; @@ -200,6 +216,7 @@ export class ToolExecutor { onProcessStart: hooks?.onProcessStart, onProcessExit: hooks?.onProcessExit, onProcessStdout: hooks?.onProcessStdout, + onProcessTimeoutControl: hooks?.onProcessTimeoutControl, }); } catch (error) { const message = error instanceof Error ? error.message : String(error); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 582abaf..c729dc0 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -54,7 +54,7 @@ type AppProps = { export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React.ReactElement { const { exit } = useApp(); const { stdout, write } = useStdout(); - const { columns } = useWindowSize(); + const { columns, rows } = useWindowSize(); const { mode, setMode } = useRawModeContext(); const initialPromptSubmittedRef = useRef(false); const processStdoutRef = useRef>(new Map()); @@ -281,6 +281,11 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setShowProcessStdout(false); }, []); + const handleAdjustBashTimeout = useCallback( + (deltaMs: number) => sessionManager.adjustActiveBashTimeout(deltaMs), + [sessionManager] + ); + const handleModelConfigChange = useCallback( (selection: ModelConfigSelection): string => { const current = resolveCurrentSettings(projectRoot); @@ -467,6 +472,7 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. }, [busy, mode, sessionManager, columns, stdout]); const screenWidth = useMemo(() => columns ?? stdout?.columns ?? 80, [columns, stdout]); + const screenHeight = useMemo(() => rows ?? stdout?.rows ?? 24, [rows, stdout]); const promptHistory = useMemo(() => { return messages .filter((message) => message.role === "user" && typeof message.content === "string") @@ -568,7 +574,9 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. processStdoutRef={processStdoutRef} runningProcesses={runningProcesses} onDismiss={handleDismissProcessStdout} + onAdjustTimeout={handleAdjustBashTimeout} screenWidth={screenWidth} + screenHeight={screenHeight} /> ) : view === "session-list" ? ( >; runningProcesses: RunningProcesses; onDismiss: () => void; + onAdjustTimeout: (deltaMs: number) => BashTimeoutAdjustment | null; screenWidth: number; + screenHeight: number; }; const REFRESH_INTERVAL_MS = 150; -const MAX_VISIBLE_LINES = 100; +const MAX_PANEL_HEIGHT = 30; +const MIN_PANEL_HEIGHT = 5; export const ProcessStdoutView = React.memo(function ProcessStdoutView({ processStdoutRef, runningProcesses, onDismiss, + onAdjustTimeout, screenWidth, + screenHeight, }: ProcessStdoutViewProps): React.ReactElement { const [stdoutText, setStdoutText] = useState(""); const [scrollOffset, setScrollOffset] = useState(0); - const containerRef = useRef<{ lineCount: number }>({ lineCount: 0 }); + const [statusMessage, setStatusMessage] = useState(""); + const statusTimerRef = useRef | null>(null); + + const panelHeight = Math.max(MIN_PANEL_HEIGHT, Math.min(screenHeight - 1, MAX_PANEL_HEIGHT)); + const reservedRows = statusMessage ? 2 : 1; + const visibleLineLimit = Math.max(1, panelHeight - reservedRows); useEffect(() => { const updateStdout = () => { @@ -51,21 +62,37 @@ export const ProcessStdoutView = React.memo(function ProcessStdoutView({ return () => clearInterval(interval); }, [processStdoutRef, runningProcesses]); - // Update container line count for scroll awareness + useEffect(() => { + return () => { + if (statusTimerRef.current) { + clearTimeout(statusTimerRef.current); + } + }; + }, []); + const lines = useMemo(() => stdoutText.split("\n"), [stdoutText]); - containerRef.current.lineCount = lines.length; + const timeoutProcess = useMemo(() => getLatestTimeoutProcess(runningProcesses), [runningProcesses]); const visibleLines = useMemo(() => { - if (lines.length <= MAX_VISIBLE_LINES) { + if (lines.length <= visibleLineLimit) { return lines; } - const start = Math.max(0, lines.length - MAX_VISIBLE_LINES - scrollOffset); - const slice = lines.slice(start, start + MAX_VISIBLE_LINES); - if (lines.length > MAX_VISIBLE_LINES) { + const outputLineLimit = Math.max(1, visibleLineLimit - 1); + const start = Math.max(0, lines.length - outputLineLimit - scrollOffset); + const slice = lines.slice(start, start + outputLineLimit); + if (lines.length > visibleLineLimit) { slice.unshift(`... (${start} lines above · ↑/↓ to scroll · ${lines.length} total lines) ...`); } return slice; - }, [lines, scrollOffset]); + }, [lines, scrollOffset, visibleLineLimit]); + + const setTemporaryStatus = (message: string) => { + setStatusMessage(message); + if (statusTimerRef.current) { + clearTimeout(statusTimerRef.current); + } + statusTimerRef.current = setTimeout(() => setStatusMessage(""), 2000); + }; useTerminalInput( (input, key) => { @@ -73,8 +100,18 @@ export const ProcessStdoutView = React.memo(function ProcessStdoutView({ onDismiss(); return; } + if (input === "+") { + const adjustment = onAdjustTimeout(BASH_TIMEOUT_INCREMENT_MS); + setTemporaryStatus(formatAdjustmentStatus(adjustment)); + return; + } + if (input === "-") { + const adjustment = onAdjustTimeout(-BASH_TIMEOUT_DECREMENT_MS); + setTemporaryStatus(formatAdjustmentStatus(adjustment)); + return; + } if (key.upArrow) { - setScrollOffset((s) => Math.min(s + 10, Math.max(0, lines.length - MAX_VISIBLE_LINES))); + setScrollOffset((s) => Math.min(s + 10, Math.max(0, lines.length - visibleLineLimit))); return; } if (key.downArrow) { @@ -82,11 +119,11 @@ export const ProcessStdoutView = React.memo(function ProcessStdoutView({ return; } if (key.pageUp) { - setScrollOffset((s) => Math.min(s + MAX_VISIBLE_LINES, Math.max(0, lines.length - MAX_VISIBLE_LINES))); + setScrollOffset((s) => Math.min(s + visibleLineLimit, Math.max(0, lines.length - visibleLineLimit))); return; } if (key.pageDown) { - setScrollOffset((s) => Math.max(s - MAX_VISIBLE_LINES, 0)); + setScrollOffset((s) => Math.max(s - visibleLineLimit, 0)); return; } }, @@ -94,16 +131,58 @@ export const ProcessStdoutView = React.memo(function ProcessStdoutView({ ); return ( - + 📟 Process Output - (Ctrl+O or Esc to close · ↑↓ PageUp/PageDown to scroll) + {` (${formatTimeoutHint( + timeoutProcess?.entry + )} · +/- adjust · Ctrl+O or Esc to close · ↑↓ PageUp/PageDown to scroll)`} - + {visibleLines.map((line, index) => ( {line} ))} + {statusMessage ? ( + + {statusMessage} + + ) : null} ); }); + +function getLatestTimeoutProcess( + runningProcesses: RunningProcesses +): { pid: string; entry: SessionProcessEntry } | null { + if (!runningProcesses) { + return null; + } + let latest: { pid: string; entry: SessionProcessEntry } | null = null; + for (const [pid, entry] of runningProcesses.entries()) { + if (typeof entry.timeoutMs !== "number") { + continue; + } + latest = { pid, entry }; + } + return latest; +} + +function formatTimeoutHint(entry?: SessionProcessEntry): string { + if (!entry || typeof entry.timeoutMs !== "number") { + return "timeout unavailable"; + } + return `timeout ${formatDuration(entry.timeoutMs)}`; +} + +function formatAdjustmentStatus(adjustment: BashTimeoutAdjustment | null): string { + if (!adjustment) { + return "No adjustable Bash timeout"; + } + return `Timeout set to ${formatDuration(adjustment.timeoutMs)}`; +} + +function formatDuration(ms: number): string { + const totalMinutes = Math.max(1, Math.round(ms / 60000)); + return `${totalMinutes}m`; +} diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 1096a93..b35f72e 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -39,7 +39,7 @@ import { } from "./fileMentions"; import type { FileMentionItem } from "./fileMentions"; import { readClipboardImageAsync } from "./clipboard"; -import type { SkillInfo } from "../session"; +import type { SessionEntry, SkillInfo } from "../session"; // Re-exported from prompt modules for backward compatibility export { useTerminalInput, parseTerminalInput } from "./prompt"; @@ -70,7 +70,7 @@ type Props = { loadingText?: string | null; disabled?: boolean; placeholder?: string; - runningProcesses?: Map | null; + runningProcesses?: SessionEntry["processes"]; onSubmit: (submission: PromptSubmission) => void; onModelConfigChange: (selection: ModelConfigSelection) => string | Promise; onRawModeChange?: (mode: string) => void; From c081efd169a7c2c47a503eb540b538640ac8810a Mon Sep 17 00:00:00 2001 From: dengmik-commits <270912164+dengmik-commits@users.noreply.github.com> Date: Tue, 19 May 2026 18:16:19 +0800 Subject: [PATCH 077/129] Revert "fix: re-apply dynamic modifier parsing for Shift+Enter after upstream sync" This reverts commit 52dafba25903dc70258d7e59dbe86e283a0f091f. --- src/tests/promptInputKeys.test.ts | 6 ++--- src/ui/prompt/cursor.ts | 4 +-- src/ui/prompt/useTerminalInput.ts | 43 +++---------------------------- 3 files changed, 9 insertions(+), 44 deletions(-) diff --git a/src/tests/promptInputKeys.test.ts b/src/tests/promptInputKeys.test.ts index 8952a3d..69d2075 100644 --- a/src/tests/promptInputKeys.test.ts +++ b/src/tests/promptInputKeys.test.ts @@ -80,7 +80,7 @@ test("parseTerminalInput keeps BS payload for meta+backspace", () => { test("parseTerminalInput recognizes shifted return sequences", () => { const { input, key } = parseTerminalInput("\u001B\r"); - assert.equal(input, ""); + assert.equal(input, "\r"); assert.equal(key.return, true); assert.equal(key.shift, true); assert.equal(key.meta, false); @@ -108,8 +108,8 @@ test("parseTerminalInput recognizes alternate shifted return sequences", () => { }); test("terminal extended key helpers request and restore modifyOtherKeys mode", () => { - assert.equal(enableTerminalExtendedKeys(), "\u001B[>4;1m\u001B[>1u"); - assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m\u001B[4;1m"); + assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m"); }); test("parseTerminalInput recognizes terminal focus events", () => { diff --git a/src/ui/prompt/cursor.ts b/src/ui/prompt/cursor.ts index 59b24f2..2668470 100644 --- a/src/ui/prompt/cursor.ts +++ b/src/ui/prompt/cursor.ts @@ -41,11 +41,11 @@ function disableTerminalFocusReporting(): string { } export function enableTerminalExtendedKeys(): string { - return "\u001B[>4;1m\u001B[>1u"; + return "\u001B[>4;1m"; } export function disableTerminalExtendedKeys(): string { - return "\u001B[>4;0m\u001B[4;0m"; } export function getPromptCursorPlacement( diff --git a/src/ui/prompt/useTerminalInput.ts b/src/ui/prompt/useTerminalInput.ts index f448d4f..8013ff6 100644 --- a/src/ui/prompt/useTerminalInput.ts +++ b/src/ui/prompt/useTerminalInput.ts @@ -26,42 +26,7 @@ const BACKSPACE_BYTES = new Set(["\u007F", "\b"]); const FORWARD_DELETE_SEQUENCES = new Set(["\u001B[3~", "\u001B[P"]); const HOME_SEQUENCES = new Set(["\u001B[H", "\u001B[1~", "\u001B[7~", "\u001BOH"]); const END_SEQUENCES = new Set(["\u001B[F", "\u001B[4~", "\u001B[8~", "\u001BOF"]); -const SHIFT_RETURN_SEQUENCES = new Set([ - "\u001B\r", - "\u001B[13;2u", - "\u001B[13;1u", - "\u001B[13;2~", - "\u001B[13;1~", - "\u001B[27;2;13~", - "\u001B[27;1;13~", -]); - -const CSI_SHIFT_RETURN_RE = /^\u001B\[13;(\d+)[u~]$/; -const CSI_EXTENDED_SHIFT_RETURN_RE = /^\u001B\[27;(\d+);13~$/; - -function isShiftReturn(raw: string): boolean { - if (SHIFT_RETURN_SEQUENCES.has(raw)) return true; - let m: RegExpMatchArray | null; - if ((m = raw.match(CSI_SHIFT_RETURN_RE)) !== null) { - const mod = parseInt(m[1], 10); - return (mod & 2) !== 0 || (mod & 1) !== 0; - } - if ((m = raw.match(CSI_EXTENDED_SHIFT_RETURN_RE)) !== null) { - const mod = parseInt(m[1], 10); - return (mod & 2) !== 0 || (mod & 1) !== 0; - } - return false; -} - -const CSI_RETURN_RE = /^\u001B\[13;(\d+)[u~]$/; -const CSI_EXTENDED_RETURN_RE = /^\u001B\[27;(\d+);13~$/; - -function isReturn(raw: string): boolean { - if (raw === "\r") return true; - if (SHIFT_RETURN_SEQUENCES.has(raw)) return true; - if (META_RETURN_SEQUENCES.has(raw)) return true; - return CSI_RETURN_RE.test(raw) || CSI_EXTENDED_RETURN_RE.test(raw); -} +const SHIFT_RETURN_SEQUENCES = new Set(["\u001B\r", "\u001B[13;2u", "\u001B[13;2~", "\u001B[27;2;13~"]); const META_RETURN_SEQUENCES = new Set(["\u001B[13;3u", "\u001B[13;4u"]); const CTRL_LEFT_SEQUENCES = new Set(["\u001B[1;5D", "\u001B[5D"]); const CTRL_RIGHT_SEQUENCES = new Set(["\u001B[1;5C", "\u001B[5C"]); @@ -148,10 +113,10 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: end: END_SEQUENCES.has(raw), pageDown: raw === "\u001B[6~", pageUp: raw === "\u001B[5~", - return: isReturn(raw), + return: raw === "\r" || SHIFT_RETURN_SEQUENCES.has(raw) || META_RETURN_SEQUENCES.has(raw), escape: raw === "\u001B", ctrl: CTRL_LEFT_SEQUENCES.has(raw) || CTRL_RIGHT_SEQUENCES.has(raw), - shift: isShiftReturn(raw), + shift: SHIFT_RETURN_SEQUENCES.has(raw), tab: raw === "\t" || raw === "\u001B[Z", backspace: BACKSPACE_BYTES.has(raw), delete: FORWARD_DELETE_SEQUENCES.has(raw), @@ -197,7 +162,7 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: key.shift = true; } - if (key.tab || key.backspace || key.delete || key.return) { + if (key.tab || key.backspace || key.delete) { input = ""; } From 255226a3c9bdd7254dd8b5728a0e1bff7de28707 Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 18:33:10 +0800 Subject: [PATCH 078/129] chore: add undici devDependency for custom keepAlive Agent Required by the custom fetch wrapper that replaces the default 4s keepAlive undici global dispatcher with a custom Agent (60s). --- package-lock.json | 13 ++++++++++++- package.json | 3 ++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index 800d75a..0b43587 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,7 +38,8 @@ "prettier": "^3.8.3", "tsx": "^4.21.0", "typescript": "^6.0.3", - "typescript-eslint": "^8.59.2" + "typescript-eslint": "^8.59.2", + "undici": "^8.3.0" }, "engines": { "node": ">=22" @@ -4096,6 +4097,16 @@ "typescript": ">=4.8.4 <6.1.0" } }, + "node_modules/undici": { + "version": "8.3.0", + "resolved": "https://registry.npmmirror.com/undici/-/undici-8.3.0.tgz", + "integrity": "sha512-TkUDgb6tl7KOGZ+7e8E3d2FYgUQgF6z5YypqjWmixVQSQERFcVrVg0ySADm2LVLRh5ljAaHTCR5Fmz3Q34rB7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/undici-types": { "version": "7.19.2", "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.19.2.tgz", diff --git a/package.json b/package.json index c438d68..b805d18 100644 --- a/package.json +++ b/package.json @@ -65,6 +65,7 @@ "prettier": "^3.8.3", "tsx": "^4.21.0", "typescript": "^6.0.3", - "typescript-eslint": "^8.59.2" + "typescript-eslint": "^8.59.2", + "undici": "^8.3.0" } } From 5b74c00db5bf16e1519c6aaafb233c4c2b78bf1a Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 18:33:59 +0800 Subject: [PATCH 079/129] fix: move undici from devDependencies to dependencies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit undici is imported at runtime in App.tsx for the custom keepAlive Agent. When bundled with --packages=external, end users need the package installed — it cannot be a devDependency. --- package-lock.json | 5 ++--- package.json | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0b43587..7d68f74 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,7 @@ "ink-gradient": "^4.0.0", "openai": "^6.35.0", "react": "^19.2.5", + "undici": "^8.3.0", "zod": "^4.4.3" }, "bin": { @@ -38,8 +39,7 @@ "prettier": "^3.8.3", "tsx": "^4.21.0", "typescript": "^6.0.3", - "typescript-eslint": "^8.59.2", - "undici": "^8.3.0" + "typescript-eslint": "^8.59.2" }, "engines": { "node": ">=22" @@ -4101,7 +4101,6 @@ "version": "8.3.0", "resolved": "https://registry.npmmirror.com/undici/-/undici-8.3.0.tgz", "integrity": "sha512-TkUDgb6tl7KOGZ+7e8E3d2FYgUQgF6z5YypqjWmixVQSQERFcVrVg0ySADm2LVLRh5ljAaHTCR5Fmz3Q34rB7Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=22.19.0" diff --git a/package.json b/package.json index b805d18..6d58864 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "ink-gradient": "^4.0.0", "openai": "^6.35.0", "react": "^19.2.5", + "undici": "^8.3.0", "zod": "^4.4.3" }, "devDependencies": { @@ -65,7 +66,6 @@ "prettier": "^3.8.3", "tsx": "^4.21.0", "typescript": "^6.0.3", - "typescript-eslint": "^8.59.2", - "undici": "^8.3.0" + "typescript-eslint": "^8.59.2" } } From db78e2b1756e2e9e2f9eea008e30e2f4638e0856 Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 18:47:23 +0800 Subject: [PATCH 080/129] fix: downgrade undici to v7 for Node 20 compatibility undici v8 requires Node >=22, but the CI matrix includes Node 20 which the project intentionally supports. v7 works on >=20.18.1. --- package-lock.json | 10 +++++----- package.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 7d68f74..82db9af 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,7 @@ "ink-gradient": "^4.0.0", "openai": "^6.35.0", "react": "^19.2.5", - "undici": "^8.3.0", + "undici": "^7.25.0", "zod": "^4.4.3" }, "bin": { @@ -4098,12 +4098,12 @@ } }, "node_modules/undici": { - "version": "8.3.0", - "resolved": "https://registry.npmmirror.com/undici/-/undici-8.3.0.tgz", - "integrity": "sha512-TkUDgb6tl7KOGZ+7e8E3d2FYgUQgF6z5YypqjWmixVQSQERFcVrVg0ySADm2LVLRh5ljAaHTCR5Fmz3Q34rB7Q==", + "version": "7.25.0", + "resolved": "https://registry.npmmirror.com/undici/-/undici-7.25.0.tgz", + "integrity": "sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==", "license": "MIT", "engines": { - "node": ">=22.19.0" + "node": ">=20.18.1" } }, "node_modules/undici-types": { diff --git a/package.json b/package.json index 6d58864..b2826c2 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "ink-gradient": "^4.0.0", "openai": "^6.35.0", "react": "^19.2.5", - "undici": "^8.3.0", + "undici": "^7.25.0", "zod": "^4.4.3" }, "devDependencies": { From 87d52ade53833a18118e23a595f511a4823b0a6c Mon Sep 17 00:00:00 2001 From: lellansin Date: Tue, 19 May 2026 19:00:28 +0800 Subject: [PATCH 081/129] fix: add 3s timeout to warmup request to prevent exit hang Codex review found that the fire-and-forget warmup models.list() had no timeout. The OpenAI client defaults to a 10-minute timeout, so an unreachable API could keep the Node process alive long after the user exits. --- src/ui/App.tsx | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 42397a5..515d5e6 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -796,9 +796,17 @@ export function createOpenAIClient(projectRoot: string = process.cwd()): { _cachedOpenAIKey = cacheKey; // Fire-and-forget warmup: pre-establish TCP+TLS connection to the API - // server while the user is composing their first prompt. Errors are - // silently ignored — the real request will retry on its own if needed. - void _cachedOpenAI.models.list().catch(() => {}); + // server while the user is composing their first prompt. Bounded by a + // short timeout so a slow / unreachable API never blocks process exit. + void (async () => { + const ac = new AbortController(); + const timer = setTimeout(() => ac.abort(), 3000); + try { + await _cachedOpenAI.models.list({ signal: ac.signal }).catch(() => {}); + } finally { + clearTimeout(timer); + } + })(); return { client: _cachedOpenAI, From 38246a0192a6c20f7eec6e1d6d904cd5ab335925 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Tue, 19 May 2026 19:40:37 +0800 Subject: [PATCH 082/129] 0.1.23 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 800d75a..17a77ca 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.22", + "version": "0.1.23", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@vegamo/deepcode-cli", - "version": "0.1.22", + "version": "0.1.23", "license": "MIT", "dependencies": { "chalk": "^5.6.2", diff --git a/package.json b/package.json index c438d68..b72fd96 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.22", + "version": "0.1.23", "description": "Deep Code CLI - Vibe coding for the deepseek-v4 model in your terminal", "license": "MIT", "type": "module", From f28cbce383fe342e4815f54db084ffec359a8006 Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 09:02:30 +0800 Subject: [PATCH 083/129] =?UTF-8?q?fix(ui):=20=E4=BF=AE=E6=AD=A3=E7=BB=84?= =?UTF-8?q?=E4=BB=B6=E8=B7=AF=E5=BE=84=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将所有导入路径中的 "compoments" 修正为 "components" - 更新多个文件中相关的导入语句,包括 App.tsx、index.ts、messageView.test.ts 和 PromptInput.tsx - 保证组件引用路径正确,避免运行时找不到模块错误 - 提升代码的可维护性和一致性 --- src/tests/messageView.test.ts | 4 ++-- src/ui/App.tsx | 4 ++-- src/ui/PromptInput.tsx | 2 +- src/ui/{compoments => components}/MessageView/index.tsx | 0 src/ui/{compoments => components}/MessageView/markdown.ts | 0 src/ui/{compoments => components}/MessageView/types.ts | 0 src/ui/{compoments => components}/MessageView/utils.ts | 0 .../{compoments => components}/RawModeExitPrompt/index.tsx | 0 .../{compoments => components}/RawModelDropdown/index.tsx | 0 src/ui/{compoments => components}/index.ts | 0 src/ui/index.ts | 6 +++--- 11 files changed, 8 insertions(+), 8 deletions(-) rename src/ui/{compoments => components}/MessageView/index.tsx (100%) rename src/ui/{compoments => components}/MessageView/markdown.ts (100%) rename src/ui/{compoments => components}/MessageView/types.ts (100%) rename src/ui/{compoments => components}/MessageView/utils.ts (100%) rename src/ui/{compoments => components}/RawModeExitPrompt/index.tsx (100%) rename src/ui/{compoments => components}/RawModelDropdown/index.tsx (100%) rename src/ui/{compoments => components}/index.ts (100%) diff --git a/src/tests/messageView.test.ts b/src/tests/messageView.test.ts index 990c8ff..b806dbd 100644 --- a/src/tests/messageView.test.ts +++ b/src/tests/messageView.test.ts @@ -6,10 +6,10 @@ import { renderMessageToStdout, getUpdatePlanPreviewLines, parseToolPayload, -} from "../ui/compoments/MessageView/utils"; +} from "../ui/components/MessageView/utils"; import { RawMode } from "../ui/contexts"; import type { SessionMessage } from "../session"; -import type { ToolSummary } from "../ui/compoments/MessageView/types"; +import type { ToolSummary } from "../ui/components/MessageView/types"; test("parseDiffPreview removes headers and classifies lines", () => { const lines = parseDiffPreview( diff --git a/src/ui/App.tsx b/src/ui/App.tsx index c729dc0..8ba842a 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -23,7 +23,7 @@ import { resolveSettingsSources, } from "../settings"; import { PromptInput, type PromptSubmission } from "./PromptInput"; -import { MessageView, RawModeExitPrompt } from "./compoments"; +import { MessageView, RawModeExitPrompt } from "./components"; import { SessionList } from "./SessionList"; import { buildLoadingText } from "./loadingText"; import { findExpandedThinkingId } from "./thinkingState"; @@ -38,7 +38,7 @@ import { } from "./askUserQuestion"; import { buildExitSummaryText } from "./exitSummary"; import { RawMode, useRawModeContext } from "./contexts"; -import { renderMessageToStdout } from "./compoments/MessageView/utils"; +import { renderMessageToStdout } from "./components/MessageView/utils"; const DEFAULT_MODEL = "deepseek-v4-pro"; const DEFAULT_BASE_URL = "https://api.deepseek.com"; diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index b35f72e..b9b1f8e 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -51,7 +51,7 @@ import { useHiddenTerminalCursor, useTerminalExtendedKeys, useTerminalFocusRepor import SlashCommandMenu from "./SlashCommandMenu"; import type { ModelConfigSelection, ReasoningEffort } from "../settings"; import DropdownMenu from "./DropdownMenu"; -import { RawModelDropdown } from "./compoments"; +import { RawModelDropdown } from "./components"; export type PromptSubmission = { text: string; diff --git a/src/ui/compoments/MessageView/index.tsx b/src/ui/components/MessageView/index.tsx similarity index 100% rename from src/ui/compoments/MessageView/index.tsx rename to src/ui/components/MessageView/index.tsx diff --git a/src/ui/compoments/MessageView/markdown.ts b/src/ui/components/MessageView/markdown.ts similarity index 100% rename from src/ui/compoments/MessageView/markdown.ts rename to src/ui/components/MessageView/markdown.ts diff --git a/src/ui/compoments/MessageView/types.ts b/src/ui/components/MessageView/types.ts similarity index 100% rename from src/ui/compoments/MessageView/types.ts rename to src/ui/components/MessageView/types.ts diff --git a/src/ui/compoments/MessageView/utils.ts b/src/ui/components/MessageView/utils.ts similarity index 100% rename from src/ui/compoments/MessageView/utils.ts rename to src/ui/components/MessageView/utils.ts diff --git a/src/ui/compoments/RawModeExitPrompt/index.tsx b/src/ui/components/RawModeExitPrompt/index.tsx similarity index 100% rename from src/ui/compoments/RawModeExitPrompt/index.tsx rename to src/ui/components/RawModeExitPrompt/index.tsx diff --git a/src/ui/compoments/RawModelDropdown/index.tsx b/src/ui/components/RawModelDropdown/index.tsx similarity index 100% rename from src/ui/compoments/RawModelDropdown/index.tsx rename to src/ui/components/RawModelDropdown/index.tsx diff --git a/src/ui/compoments/index.ts b/src/ui/components/index.ts similarity index 100% rename from src/ui/compoments/index.ts rename to src/ui/components/index.ts diff --git a/src/ui/index.ts b/src/ui/index.ts index f2e698c..aa757f9 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -9,8 +9,8 @@ export { } from "./App"; export { default as AppContainer } from "./AppContainer"; export { AskUserQuestionPrompt } from "./AskUserQuestionPrompt"; -export { MessageView } from "./compoments"; -export { parseDiffPreview } from "./compoments/MessageView/utils"; +export { MessageView } from "./components"; +export { parseDiffPreview } from "./components/MessageView/utils"; export { PromptInput, IMAGE_ATTACHMENT_CLEAR_HINT, @@ -48,7 +48,7 @@ export { } from "./askUserQuestion"; export { readClipboardImage, type ClipboardImage } from "./clipboard"; export { buildLoadingText, type LoadingTextInput } from "./loadingText"; -export { renderMarkdown } from "./compoments/MessageView/markdown"; +export { renderMarkdown } from "./components/MessageView/markdown"; export { EMPTY_BUFFER, insertText, From bbf810d1a55bfa2c45cdf576ed186f7d0c606715 Mon Sep 17 00:00:00 2001 From: Seunghoon Shin Date: Wed, 20 May 2026 12:13:43 +0900 Subject: [PATCH 084/129] fix: resolve CJK composition bug on iOS terminals (backspace packet splitting) --- src/ui/prompt/useTerminalInput.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/ui/prompt/useTerminalInput.ts b/src/ui/prompt/useTerminalInput.ts index 8013ff6..8fe0d60 100644 --- a/src/ui/prompt/useTerminalInput.ts +++ b/src/ui/prompt/useTerminalInput.ts @@ -193,6 +193,30 @@ export function useTerminalInput( return; } const handleData = (data: Buffer | string) => { + const raw = String(data); + + // Fix CJK composition bug on iOS terminals (Moshi, Blink, etc.). + // iOS keyboards send composed characters as a single packet like: + // "가\x7f나" (character + backspace + new character) + // Without splitting, parseTerminalInput treats the whole packet as + // one input and drops the composition backspaces, corrupting the text. + if (raw.includes("\x7f") && raw.length > 1) { + const parts = raw.split("\x7f"); + if (parts[0]) { + const { input, key } = parseTerminalInput(parts[0]); + handlerRef.current(input, key); + } + for (let i = 1; i < parts.length; i++) { + const bs = parseTerminalInput("\x7f"); + handlerRef.current(bs.input, bs.key); + if (parts[i]) { + const { input, key } = parseTerminalInput(parts[i]); + handlerRef.current(input, key); + } + } + return; + } + const { input, key } = parseTerminalInput(data); handlerRef.current(input, key); }; From 4605be4e3ccffa9a48d9203a32a1f5db5f0a0516 Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 11:18:23 +0800 Subject: [PATCH 085/129] =?UTF-8?q?feat(ui):=20=E6=96=B0=E5=A2=9E=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E5=92=8C=E6=8A=80=E8=83=BD=E9=80=89=E6=8B=A9=E4=B8=8B?= =?UTF-8?q?=E6=8B=89=E8=8F=9C=E5=8D=95=E7=BB=84=E4=BB=B6=E5=B9=B6=E9=9B=86?= =?UTF-8?q?=E6=88=90=E5=88=B0PromptInput?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 创建 ModelsDropdown 组件支持选择模型及思考模式 - 创建 SkillsDropdown 组件支持选择和切换技能 - 在 ui/components/index.ts 中导出新增组件 - 在 ui/index.ts 中导出 ModelsDropdown 相关辅助方法 - 在 PromptInput 组件中替换旧模型选择逻辑,改用新增下拉组件 - 优化 PromptInput 的快捷键处理,实现技能和模型菜单切换 - 移除 PromptInput 内部的模型选择状态及逻辑,简化代码结构 - 保持现有功能一致,增加用户界面交互的灵活性与可用性 --- src/ui/PromptInput.tsx | 231 +++------------------ src/ui/components/ModelsDropdown/index.tsx | 165 +++++++++++++++ src/ui/components/SkillsDropdown/index.tsx | 74 +++++++ src/ui/components/index.ts | 2 + src/ui/index.ts | 10 +- 5 files changed, 275 insertions(+), 207 deletions(-) create mode 100644 src/ui/components/ModelsDropdown/index.tsx create mode 100644 src/ui/components/SkillsDropdown/index.tsx diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index b9b1f8e..a79fe30 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -49,9 +49,9 @@ import { useTerminalInput } from "./prompt"; import type { InputKey } from "./prompt"; import { useHiddenTerminalCursor, useTerminalExtendedKeys, useTerminalFocusReporting } from "./prompt"; import SlashCommandMenu from "./SlashCommandMenu"; -import type { ModelConfigSelection, ReasoningEffort } from "../settings"; +import type { ModelConfigSelection } from "../settings"; import DropdownMenu from "./DropdownMenu"; -import { RawModelDropdown } from "./components"; +import { ModelsDropdown, RawModelDropdown, SkillsDropdown } from "./components"; export type PromptSubmission = { text: string; @@ -79,21 +79,6 @@ type Props = { }; const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; -export const MODEL_COMMAND_MODELS = ["deepseek-v4-pro", "deepseek-v4-flash"] as const; - -type ThinkingModeOption = { - label: string; - thinkingEnabled: boolean; - reasoningEffort?: ReasoningEffort; -}; - -export const MODEL_COMMAND_THINKING_OPTIONS: ThinkingModeOption[] = [ - { label: "Thinking mode [max]", thinkingEnabled: true, reasoningEffort: "max" }, - { label: "Thinking mode [high]", thinkingEnabled: true, reasoningEffort: "high" }, - { label: "No thinking", thinkingEnabled: false }, -]; - -type ModelDropdownStep = "model" | "thinking"; const PromptPrefixLine = React.memo(function PromptPrefixLine({ busy }: { busy: boolean }): React.ReactElement { const [spinnerIndex, setSpinnerIndex] = useState(0); @@ -140,10 +125,7 @@ export const PromptInput = React.memo(function PromptInput({ const [menuIndex, setMenuIndex] = useState(0); const [showSkillsDropdown, setShowSkillsDropdown] = useState(false); const [openRawModelDropdown, setOpenRawModelDropdown] = useState(false); - const [skillsDropdownIndex, setSkillsDropdownIndex] = useState(0); - const [modelDropdownStep, setModelDropdownStep] = useState(null); - const [modelDropdownIndex, setModelDropdownIndex] = useState(0); - const [pendingModel, setPendingModel] = useState(null); + const [showModelDropdown, setShowModelDropdown] = useState(false); const [fileMentionItems, setFileMentionItems] = useState(() => scanFileMentionItems(projectRoot)); const [fileMentionIndex, setFileMentionIndex] = useState(0); const [dismissedFileMentionKey, setDismissedFileMentionKey] = useState(null); @@ -164,19 +146,19 @@ export const PromptInput = React.memo(function PromptInput({ ); const showFileMentionMenu = !showSkillsDropdown && - !modelDropdownStep && + !showModelDropdown && fileMentionToken !== null && fileMentionKey !== dismissedFileMentionKey; const slashItems = React.useMemo(() => buildSlashCommands(skills), [skills]); const slashToken = getCurrentSlashToken(buffer); const slashMenu = React.useMemo( () => - showSkillsDropdown || modelDropdownStep || showFileMentionMenu + showSkillsDropdown || showModelDropdown || showFileMentionMenu ? [] : slashToken ? filterSlashCommands(slashItems, slashToken) : [], - [showSkillsDropdown, modelDropdownStep, showFileMentionMenu, slashToken, slashItems] + [showSkillsDropdown, showModelDropdown, showFileMentionMenu, slashToken, slashItems] ); const showMenu = slashMenu.length > 0; const promptHistoryKey = React.useMemo(() => promptHistory.join("\0"), [promptHistory]); @@ -241,23 +223,6 @@ export const PromptInput = React.memo(function PromptInput({ } }, [fileMentionMatches.length, fileMentionIndex, showFileMentionMenu]); - useEffect(() => { - if (skillsDropdownIndex >= skills.length) { - setSkillsDropdownIndex(Math.max(0, skills.length - 1)); - } - }, [skills.length, skillsDropdownIndex]); - - useEffect(() => { - if (!modelDropdownStep) { - return; - } - const optionCount = - modelDropdownStep === "model" ? MODEL_COMMAND_MODELS.length : MODEL_COMMAND_THINKING_OPTIONS.length; - if (modelDropdownIndex >= optionCount) { - setModelDropdownIndex(Math.max(0, optionCount - 1)); - } - }, [modelDropdownIndex, modelDropdownStep]); - useEffect(() => { if (!statusMessage) { return; @@ -287,14 +252,6 @@ export const PromptInput = React.memo(function PromptInput({ } if (key.escape) { - if (modelDropdownStep) { - closeModelDropdown(); - return; - } - if (showSkillsDropdown) { - setShowSkillsDropdown(false); - return; - } if (showFileMentionMenu && fileMentionKey) { setDismissedFileMentionKey(fileMentionKey); return; @@ -348,7 +305,7 @@ export const PromptInput = React.memo(function PromptInput({ setPendingExit(false); } - if (openRawModelDropdown) { + if (openRawModelDropdown || showSkillsDropdown || showModelDropdown) { return; } @@ -356,53 +313,6 @@ export const PromptInput = React.memo(function PromptInput({ exitHistoryBrowsing(); } - if (showSkillsDropdown) { - if (skills.length === 0) { - setShowSkillsDropdown(false); - } else { - if (key.upArrow) { - setSkillsDropdownIndex((idx) => (idx - 1 + skills.length) % skills.length); - return; - } - if (key.downArrow) { - setSkillsDropdownIndex((idx) => (idx + 1) % skills.length); - return; - } - if ((input === " " && !key.ctrl && !key.meta) || (key.return && !key.shift && !key.meta)) { - const skill = skills[skillsDropdownIndex]; - if (skill) { - toggleSelectedSkill(skill); - } - return; - } - if (key.tab) { - setShowSkillsDropdown(false); - return; - } - } - } - - if (modelDropdownStep) { - const optionCount = - modelDropdownStep === "model" ? MODEL_COMMAND_MODELS.length : MODEL_COMMAND_THINKING_OPTIONS.length; - if (key.upArrow) { - setModelDropdownIndex((idx) => (idx - 1 + optionCount) % optionCount); - return; - } - if (key.downArrow) { - setModelDropdownIndex((idx) => (idx + 1) % optionCount); - return; - } - if ((input === " " && !key.ctrl && !key.meta) || (key.return && !key.shift && !key.meta)) { - selectModelDropdownItem(); - return; - } - if (key.tab) { - closeModelDropdown(); - return; - } - } - if (key.ctrl && (input === "v" || input === "V")) { setStatusMessage("Reading clipboard..."); readClipboardImageAsync() @@ -722,7 +632,8 @@ export const PromptInput = React.memo(function PromptInput({ } if (item.kind === "model") { clearSlashToken(); - openModelDropdown(); + setShowSkillsDropdown(false); + setShowModelDropdown(true); return; } if (item.kind === "raw") { @@ -828,63 +739,9 @@ export const PromptInput = React.memo(function PromptInput({ clearUndoRedoStacks(); } - function openModelDropdown(): void { - const currentModelIndex = MODEL_COMMAND_MODELS.findIndex((model) => model === modelConfig.model); - setPendingModel(null); - setModelDropdownStep("model"); - setModelDropdownIndex(currentModelIndex >= 0 ? currentModelIndex : 0); - setShowSkillsDropdown(false); - } - - function closeModelDropdown(): void { - setModelDropdownStep(null); - setPendingModel(null); - } - - function selectModelDropdownItem(): void { - if (modelDropdownStep === "model") { - const model = MODEL_COMMAND_MODELS[modelDropdownIndex] ?? modelConfig.model; - setPendingModel(model); - setModelDropdownStep("thinking"); - setModelDropdownIndex(getThinkingOptionIndex(modelConfig)); - return; - } - - const option = MODEL_COMMAND_THINKING_OPTIONS[modelDropdownIndex] ?? MODEL_COMMAND_THINKING_OPTIONS[0]; - const selection: ModelConfigSelection = { - model: pendingModel ?? modelConfig.model, - thinkingEnabled: option.thinkingEnabled, - reasoningEffort: option.reasoningEffort ?? modelConfig.reasoningEffort, - }; - closeModelDropdown(); - Promise.resolve(onModelConfigChange(selection)) - .then((message) => { - if (message) { - setStatusMessage(message); - } - }) - .catch((error) => { - const message = error instanceof Error ? error.message : String(error); - setStatusMessage(`Failed to update model settings: ${message}`); - }); - } - - const modelDropdownItems = - modelDropdownStep === "model" - ? MODEL_COMMAND_MODELS.map((model) => ({ - label: model, - selected: model === (pendingModel ?? modelConfig.model), - description: model === modelConfig.model ? "current model" : "", - })) - : MODEL_COMMAND_THINKING_OPTIONS.map((option) => ({ - label: option.label, - selected: getThinkingOptionIndex(modelConfig) === MODEL_COMMAND_THINKING_OPTIONS.indexOf(option), - description: option.thinkingEnabled ? `reasoningEffort: ${option.reasoningEffort}` : "thinking disabled", - })); - const showFooterText = useMemo( - () => showMenu || showSkillsDropdown || openRawModelDropdown || modelDropdownStep !== null || showFileMentionMenu, - [showMenu, showSkillsDropdown, modelDropdownStep, openRawModelDropdown, showFileMentionMenu] + () => showMenu || showSkillsDropdown || openRawModelDropdown || showModelDropdown || showFileMentionMenu, + [showMenu, showSkillsDropdown, showModelDropdown, openRawModelDropdown, showFileMentionMenu] ); const matchedCommand = slashToken ? findExactSlashCommand(slashItems, slashToken) : null; @@ -925,44 +782,22 @@ export const PromptInput = React.memo(function PromptInput({ onSelect={(mode) => onRawModeChange?.(mode)} screenWidth={screenWidth} /> - {showSkillsDropdown ? ( - ({ - key: skill.path || skill.name, - label: skill.name, - description: skill.path, - selected: isSkillSelected(selectedSkills, skill), - statusIndicator: skill.isLoaded ? { symbol: "✓", color: "green" } : undefined, - }))} - activeIndex={skillsDropdownIndex} - activeColor="#229ac3" - maxVisible={6} - /> - ) : null} - {modelDropdownStep ? ( - ({ - key: item.label, - label: item.label, - description: item.description, - selected: item.selected, - }))} - activeIndex={modelDropdownIndex} - activeColor="#229ac3" - maxVisible={6} - /> - ) : null} + + setShowModelDropdown(false)} + onModelConfigChange={onModelConfigChange} + onStatusMessage={setStatusMessage} + /> {showFileMentionMenu ? ( -): number { - const index = MODEL_COMMAND_THINKING_OPTIONS.findIndex((option) => { - if (!config.thinkingEnabled) { - return !option.thinkingEnabled; - } - return option.thinkingEnabled && option.reasoningEffort === config.reasoningEffort; - }); - return index >= 0 ? index : 0; -} - export function removeCurrentSlashToken(state: PromptBufferState): PromptBufferState { let start = state.cursor; while (start > 0 && !/\s/.test(state.text[start - 1] ?? "")) { diff --git a/src/ui/components/ModelsDropdown/index.tsx b/src/ui/components/ModelsDropdown/index.tsx new file mode 100644 index 0000000..bdd68ab --- /dev/null +++ b/src/ui/components/ModelsDropdown/index.tsx @@ -0,0 +1,165 @@ +import React, { useEffect, useState } from "react"; +import { useInput } from "ink"; +import DropdownMenu from "../../DropdownMenu"; +import type { ModelConfigSelection, ReasoningEffort } from "../../../settings"; + +type ModelStep = "model" | "thinking"; + +type ThinkingModeOption = { + label: string; + thinkingEnabled: boolean; + reasoningEffort?: ReasoningEffort; +}; + +export const MODEL_COMMAND_MODELS = ["deepseek-v4-pro", "deepseek-v4-flash"] as const; + +export const MODEL_COMMAND_THINKING_OPTIONS: ThinkingModeOption[] = [ + { label: "Thinking mode [max]", thinkingEnabled: true, reasoningEffort: "max" }, + { label: "Thinking mode [high]", thinkingEnabled: true, reasoningEffort: "high" }, + { label: "No thinking", thinkingEnabled: false }, +]; + +function getThinkingOptionIndex(config: Pick): number { + const index = MODEL_COMMAND_THINKING_OPTIONS.findIndex((option) => { + if (!config.thinkingEnabled) { + return !option.thinkingEnabled; + } + return option.thinkingEnabled && option.reasoningEffort === config.reasoningEffort; + }); + return index >= 0 ? index : 0; +} + +type Props = { + open: boolean; + modelConfig: ModelConfigSelection; + width: number; + onClose: () => void; + onModelConfigChange: (selection: ModelConfigSelection) => string | Promise; + onStatusMessage?: (message: string | null) => void; +}; + +const ModelsDropdown: React.FC = ({ + open, + modelConfig, + width, + onClose, + onModelConfigChange, + onStatusMessage, +}) => { + const [step, setStep] = useState(null); + const [activeIndex, setActiveIndex] = useState(0); + const [pendingModel, setPendingModel] = useState(null); + + // Initialize state when opened + useEffect(() => { + if (open) { + const currentIndex = MODEL_COMMAND_MODELS.findIndex((m) => m === modelConfig.model); + setPendingModel(null); + setStep("model"); + setActiveIndex(currentIndex >= 0 ? currentIndex : 0); + } else { + setStep(null); + } + }, [open, modelConfig.model]); + + // Validate activeIndex bounds + useEffect(() => { + if (!step) { + return; + } + const optionCount = step === "model" ? MODEL_COMMAND_MODELS.length : MODEL_COMMAND_THINKING_OPTIONS.length; + if (activeIndex >= optionCount) { + setActiveIndex(Math.max(0, optionCount - 1)); + } + }, [activeIndex, step]); + + function selectItem(): void { + if (step === "model") { + const model = MODEL_COMMAND_MODELS[activeIndex] ?? modelConfig.model; + setPendingModel(model); + setStep("thinking"); + setActiveIndex(getThinkingOptionIndex(modelConfig)); + return; + } + + const option = MODEL_COMMAND_THINKING_OPTIONS[activeIndex] ?? MODEL_COMMAND_THINKING_OPTIONS[0]!; + const selection: ModelConfigSelection = { + model: pendingModel ?? modelConfig.model, + thinkingEnabled: option.thinkingEnabled, + reasoningEffort: option.reasoningEffort ?? modelConfig.reasoningEffort, + }; + onClose(); + Promise.resolve(onModelConfigChange(selection)) + .then((message) => { + if (message) { + onStatusMessage?.(message); + } + }) + .catch((error) => { + const msg = error instanceof Error ? error.message : String(error); + onStatusMessage?.(`Failed to update model settings: ${msg}`); + }); + } + + useInput( + (input, key) => { + if (!step) { + return; + } + + const optionCount = step === "model" ? MODEL_COMMAND_MODELS.length : MODEL_COMMAND_THINKING_OPTIONS.length; + + if (key.upArrow) { + setActiveIndex((idx) => (idx - 1 + optionCount) % optionCount); + return; + } + if (key.downArrow) { + setActiveIndex((idx) => (idx + 1) % optionCount); + return; + } + if ((input === " " && !key.ctrl && !key.meta) || (key.return && !key.shift && !key.meta)) { + selectItem(); + return; + } + if (key.tab || key.escape) { + onClose(); + return; + } + }, + { isActive: open } + ); + + if (!open || !step) { + return null; + } + + const items = + step === "model" + ? MODEL_COMMAND_MODELS.map((model) => ({ + key: model, + label: model, + description: model === modelConfig.model ? "current model" : "", + selected: model === (pendingModel ?? modelConfig.model), + })) + : MODEL_COMMAND_THINKING_OPTIONS.map((option, i) => ({ + key: option.label, + label: option.label, + description: option.thinkingEnabled ? `reasoningEffort: ${option.reasoningEffort}` : "thinking disabled", + selected: getThinkingOptionIndex(modelConfig) === i, + })); + + return ( + + ); +}; + +export { getThinkingOptionIndex }; +export default ModelsDropdown; diff --git a/src/ui/components/SkillsDropdown/index.tsx b/src/ui/components/SkillsDropdown/index.tsx new file mode 100644 index 0000000..545e2ab --- /dev/null +++ b/src/ui/components/SkillsDropdown/index.tsx @@ -0,0 +1,74 @@ +import DropdownMenu from "../../DropdownMenu"; +import React, { useEffect, useState } from "react"; +import { isSkillSelected } from "../../PromptInput"; +import type { SkillInfo } from "../../../session"; +import { useInput } from "ink"; + +const SkillsDropdown: React.FC<{ + open: boolean; + onClose?: (value: boolean) => void; + width: number; + skills: SkillInfo[]; + selectedSkills: SkillInfo[]; + onSelect?: (skill: SkillInfo) => void; +}> = ({ open, width, skills, selectedSkills, onSelect, onClose }) => { + const [skillsDropdownIndex, setSkillsDropdownIndex] = useState(0); + useInput( + (input, key) => { + if (key.upArrow) { + setSkillsDropdownIndex((idx) => (idx - 1 + skills.length) % skills.length); + return; + } + if (key.downArrow) { + setSkillsDropdownIndex((idx) => (idx + 1) % skills.length); + return; + } + if ((input === " " && !key.ctrl && !key.meta) || (key.return && !key.shift && !key.meta)) { + const skill = skills[skillsDropdownIndex]; + if (skill) { + onSelect?.(skill); + } + return; + } + if (key.tab) { + onClose?.(false); + return; + } + if (key.escape) { + onClose?.(false); + } + }, + { isActive: open } + ); + + useEffect(() => { + if (skillsDropdownIndex >= skills.length) { + setSkillsDropdownIndex(Math.max(0, skills.length - 1)); + } + }, [skills.length, skillsDropdownIndex]); + + if (!open) { + return null; + } + + return ( + ({ + key: skill.path || skill.name, + label: skill.name, + description: skill.path, + selected: isSkillSelected(selectedSkills, skill), + statusIndicator: skill.isLoaded ? { symbol: "✓", color: "green" } : undefined, + }))} + activeIndex={skillsDropdownIndex} + activeColor="#229ac3" + maxVisible={6} + /> + ); +}; + +export default SkillsDropdown; diff --git a/src/ui/components/index.ts b/src/ui/components/index.ts index 942d3ed..1d929f3 100644 --- a/src/ui/components/index.ts +++ b/src/ui/components/index.ts @@ -1,3 +1,5 @@ export { default as RawModelDropdown } from "./RawModelDropdown"; export { MessageView } from "./MessageView"; export { RawModeExitPrompt } from "./RawModeExitPrompt"; +export { default as SkillsDropdown } from "./SkillsDropdown"; +export { default as ModelsDropdown } from "./ModelsDropdown"; diff --git a/src/ui/index.ts b/src/ui/index.ts index aa757f9..efb4edd 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -1,3 +1,9 @@ +import { + getThinkingOptionIndex, + MODEL_COMMAND_MODELS, + MODEL_COMMAND_THINKING_OPTIONS, +} from "./components/ModelsDropdown"; + export { readSettings, readProjectSettings, @@ -24,14 +30,12 @@ export { getPromptReturnKeyAction, renderBufferWithCursor, buildInitPromptSubmission, - getThinkingOptionIndex, - MODEL_COMMAND_MODELS, - MODEL_COMMAND_THINKING_OPTIONS, useTerminalInput, parseTerminalInput, type PromptSubmission, type InputKey, } from "./PromptInput"; +export { getThinkingOptionIndex, MODEL_COMMAND_MODELS, MODEL_COMMAND_THINKING_OPTIONS }; export { disableTerminalExtendedKeys, enableTerminalExtendedKeys, getPromptCursorPlacement } from "./prompt/cursor"; export { SessionList, formatSessionTitle } from "./SessionList"; export { ThemedGradient } from "./ThemedGradient"; From 02865704effba4ee50201fd6389f48744293e108 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Wed, 20 May 2026 11:35:20 +0800 Subject: [PATCH 086/129] feat: add undo functionality and enhance session management --- src/session.ts | 302 ++++++++++++++++++++++++++++++ src/tests/promptInputKeys.test.ts | 28 ++- src/tests/session.test.ts | 296 +++++++++++++++++++++++++++++ src/tests/slashCommands.test.ts | 20 +- src/tools/edit-handler.ts | 2 + src/tools/executor.ts | 6 + src/tools/write-handler.ts | 2 + src/ui/App.tsx | 106 ++++++++++- src/ui/PromptInput.tsx | 36 +++- src/ui/UndoSelector.tsx | 195 +++++++++++++++++++ src/ui/index.ts | 2 + src/ui/slashCommands.ts | 7 + 12 files changed, 997 insertions(+), 5 deletions(-) create mode 100644 src/ui/UndoSelector.tsx diff --git a/src/session.ts b/src/session.ts index 3f79481..6b2ceee 100644 --- a/src/session.ts +++ b/src/session.ts @@ -2,6 +2,7 @@ import * as fs from "fs"; import * as path from "path"; import * as os from "os"; import * as crypto from "crypto"; +import * as childProcess from "child_process"; import { fileURLToPath } from "url"; import matter from "gray-matter"; import ejs from "ejs"; @@ -34,6 +35,8 @@ const DEFAULT_NEW_PROMPT_API_URL = "https://deepcode.vegamo.cn/api/plugin/new"; const NEW_PROMPT_REPORT_TIMEOUT_MS = 3000; const DEFAULT_COMPACT_PROMPT_TOKEN_THRESHOLD = 128 * 1024; const DEEPSEEK_V4_COMPACT_PROMPT_TOKEN_THRESHOLD = 512 * 1024; +const FILE_HISTORY_AUTHOR_NAME = "DeepCode Checkpoint"; +const FILE_HISTORY_AUTHOR_EMAIL = "deepcode-checkpoint@localhost"; type ChatCompletionDebugOptions = { enabled?: boolean; @@ -202,6 +205,13 @@ export type SessionMessage = { updateTime: string; meta?: MessageMeta; html?: string; + checkpointHash?: string; +}; + +export type UndoTarget = { + message: SessionMessage; + index: number; + canRestoreCode: boolean; }; export type UserPromptContent = { @@ -902,6 +912,7 @@ The candidate skills are as follows:\n\n`; userPrompt.skills = await this.normalizeSkills(userPrompt.skills); this.throwIfAborted(signal); const sessionId = crypto.randomUUID(); + this.ensureFileHistorySession(sessionId); const now = new Date().toISOString(); const index = this.loadSessionsIndex(); const entry: SessionEntry = { @@ -1022,6 +1033,7 @@ ${skillMd} userPrompt.skills = await this.normalizeSkills(userPrompt.skills, sessionId); this.throwIfAborted(signal); + this.ensureFileHistorySession(sessionId); const userMessage = this.buildUserMessage(sessionId, userPrompt); this.appendSessionMessage(sessionId, userMessage); @@ -1480,6 +1492,61 @@ ${skillMd} return messages; } + listUndoTargets(sessionId: string): UndoTarget[] { + return this.listSessionMessages(sessionId) + .map((message, index) => ({ message, index })) + .filter(({ message }) => this.isUndoTargetMessage(message)) + .map(({ message, index }) => ({ + message, + index, + canRestoreCode: Boolean( + message.checkpointHash && this.canRestoreCheckpointHash(sessionId, message.checkpointHash) + ), + })); + } + + restoreSessionConversation(sessionId: string, messageId: string): SessionMessage[] { + const messages = this.listSessionMessages(sessionId); + const targetIndex = messages.findIndex((message) => message.id === messageId); + if (targetIndex === -1) { + throw new Error("Selected message was not found in this session."); + } + + const keptMessages = messages.slice(0, targetIndex); + this.saveSessionMessages(sessionId, keptMessages); + const now = new Date().toISOString(); + const latestAssistant = [...keptMessages].reverse().find((message) => message.role === "assistant"); + const latestAssistantParams = latestAssistant?.messageParams as + | { tool_calls?: unknown[]; reasoning_content?: string } + | null + | undefined; + + this.updateSessionEntry(sessionId, (entry) => ({ + ...entry, + assistantReply: latestAssistant?.content ?? null, + assistantThinking: + typeof latestAssistantParams?.reasoning_content === "string" ? latestAssistantParams.reasoning_content : null, + assistantRefusal: null, + toolCalls: null, + status: "completed", + failReason: null, + processes: null, + updateTime: now, + })); + return keptMessages; + } + + restoreSessionCode(sessionId: string, messageId: string): void { + const message = this.listSessionMessages(sessionId).find((item) => item.id === messageId); + if (!message) { + throw new Error("Selected message was not found in this session."); + } + if (!message.checkpointHash) { + throw new Error("Selected message has no code checkpoint."); + } + this.restoreCheckpointHash(sessionId, message.checkpointHash); + } + private normalizeSessionMessage(message: SessionMessage): SessionMessage { if (message.role !== "tool") { return message; @@ -1518,6 +1585,238 @@ ${skillMd} return { projectCode, projectDir, sessionsIndexPath }; } + private getFileHistoryGitDir(): string { + const { projectDir } = this.getProjectStorage(); + return path.join(projectDir, "file-history", ".git"); + } + + private getSessionBranchRef(sessionId: string): string | null { + if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) { + return null; + } + return `refs/heads/${sessionId}`; + } + + private ensureFileHistorySession(sessionId: string): string | undefined { + const branchRef = this.getSessionBranchRef(sessionId); + if (!branchRef) { + return undefined; + } + + try { + const gitDir = this.getFileHistoryGitDir(); + if (!fs.existsSync(gitDir)) { + fs.mkdirSync(path.dirname(gitDir), { recursive: true }); + this.runFileHistoryGit(["init"], { includeWorkTree: true }); + } + + const current = this.getCurrentCheckpointHash(sessionId); + if (current) { + return current; + } + + const emptyTree = this.runFileHistoryGit(["mktree"], { includeWorkTree: false, input: "" }).trim(); + const commitHash = this.createFileHistoryCommit(emptyTree, null, "Initial checkpoint"); + this.runFileHistoryGit(["update-ref", branchRef, commitHash], { includeWorkTree: false }); + return commitHash; + } catch { + return undefined; + } + } + + private getCurrentCheckpointHash(sessionId: string): string | undefined { + const gitDir = this.getFileHistoryGitDir(); + const branchRef = this.getSessionBranchRef(sessionId); + if (!branchRef || !fs.existsSync(gitDir)) { + return undefined; + } + + try { + const hash = this.runFileHistoryGit(["rev-parse", "--verify", `${branchRef}^{commit}`], { + includeWorkTree: false, + }).trim(); + return this.isCommitHash(hash) ? hash : undefined; + } catch { + return undefined; + } + } + + private prepareFileMutationCheckpoint(sessionId: string, filePath: string): void { + const previousHash = this.ensureFileHistorySession(sessionId); + if (!previousHash) { + return; + } + this.updateLatestUserCheckpointHash(sessionId, undefined, previousHash); + const nextHash = this.recordFileHistoryCheckpoint(sessionId, [filePath], "Pre-mutation checkpoint"); + if (nextHash && nextHash !== previousHash) { + this.updateLatestUserCheckpointHash(sessionId, previousHash, nextHash); + } + } + + private recordFileMutationCheckpoint(sessionId: string, filePath: string): void { + this.ensureFileHistorySession(sessionId); + this.recordFileHistoryCheckpoint(sessionId, [filePath], "File mutation checkpoint"); + } + + private recordFileHistoryCheckpoint(sessionId: string, filePaths: string[], message: string): string | undefined { + const branchRef = this.getSessionBranchRef(sessionId); + if (!branchRef) { + return undefined; + } + + const relativePaths = filePaths + .map((filePath) => this.toProjectRelativeGitPath(filePath)) + .filter((filePath): filePath is string => Boolean(filePath)); + if (relativePaths.length === 0) { + return this.getCurrentCheckpointHash(sessionId); + } + + try { + const parentHash = this.ensureFileHistorySession(sessionId); + if (!parentHash) { + return undefined; + } + this.runFileHistoryGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); + this.runFileHistoryGit(["add", "-f", "-A", "--", ...relativePaths], { includeWorkTree: true }); + const treeHash = this.runFileHistoryGit(["write-tree"], { includeWorkTree: false }).trim(); + const parentTreeHash = this.runFileHistoryGit(["rev-parse", `${parentHash}^{tree}`], { + includeWorkTree: false, + }).trim(); + if (treeHash === parentTreeHash) { + return parentHash; + } + + const commitHash = this.createFileHistoryCommit(treeHash, parentHash, message); + this.runFileHistoryGit(["update-ref", branchRef, commitHash, parentHash], { includeWorkTree: false }); + return commitHash; + } catch { + return undefined; + } + } + + private updateLatestUserCheckpointHash(sessionId: string, previousHash: string | undefined, nextHash: string): void { + const messages = this.listSessionMessages(sessionId); + for (let index = messages.length - 1; index >= 0; index -= 1) { + const message = messages[index]; + if (!message || !this.isUndoTargetMessage(message)) { + continue; + } + if (message.checkpointHash && message.checkpointHash !== previousHash) { + return; + } + messages[index] = { + ...message, + checkpointHash: nextHash, + updateTime: new Date().toISOString(), + }; + this.saveSessionMessages(sessionId, messages); + return; + } + } + + private createFileHistoryCommit(treeHash: string, parentHash: string | null, message: string): string { + const args = ["commit-tree", treeHash]; + if (parentHash) { + args.push("-p", parentHash); + } + args.push("-m", message); + return this.runFileHistoryGit(args, { + includeWorkTree: false, + env: this.getFileHistoryGitEnv(), + }).trim(); + } + + private getFileHistoryGitEnv(): NodeJS.ProcessEnv { + return { + ...process.env, + GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || FILE_HISTORY_AUTHOR_NAME, + GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || FILE_HISTORY_AUTHOR_EMAIL, + GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || FILE_HISTORY_AUTHOR_NAME, + GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || FILE_HISTORY_AUTHOR_EMAIL, + }; + } + + private toProjectRelativeGitPath(filePath: string): string | null { + const absolutePath = path.resolve(filePath); + const relativePath = path.relative(this.projectRoot, absolutePath); + if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) { + return null; + } + return relativePath.split(path.sep).join("/"); + } + + private canRestoreCheckpointHash(sessionId: string, checkpointHash: string): boolean { + if (!this.isCommitHash(checkpointHash)) { + return false; + } + if (!this.getSessionBranchRef(sessionId)) { + return false; + } + const gitDir = this.getFileHistoryGitDir(); + if (!fs.existsSync(gitDir)) { + return false; + } + + try { + this.runFileHistoryGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); + return true; + } catch { + return false; + } + } + + private restoreCheckpointHash(sessionId: string, checkpointHash: string): void { + if (!this.isCommitHash(checkpointHash)) { + throw new Error("Invalid checkpoint hash."); + } + const gitDir = this.getFileHistoryGitDir(); + const branchRef = this.getSessionBranchRef(sessionId); + if (!branchRef || !fs.existsSync(gitDir)) { + throw new Error("File history Git repository was not found for this project."); + } + this.runFileHistoryGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); + + try { + this.runFileHistoryGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); + } catch { + // If the session branch is missing, fall back to the target tree only. + // The target checkpoint has already been validated above. + } + this.runFileHistoryGit(["read-tree", "--reset", "-u", checkpointHash], { includeWorkTree: true }); + this.runFileHistoryGit(["update-ref", branchRef, checkpointHash], { includeWorkTree: false }); + } + + private runFileHistoryGit( + args: string[], + options: { includeWorkTree: boolean; input?: string; env?: NodeJS.ProcessEnv } + ): string { + const gitDir = this.getFileHistoryGitDir(); + const gitArgs = [`--git-dir=${gitDir}`]; + if (options.includeWorkTree) { + gitArgs.push(`--work-tree=${this.projectRoot}`); + } + gitArgs.push(...args); + const result = childProcess.spawnSync("git", gitArgs, { + encoding: "utf8", + input: options.input, + env: options.env, + stdio: ["pipe", "pipe", "pipe"], + }); + if (result.status !== 0) { + const detail = (result.stderr || result.stdout || "").trim(); + throw new Error(detail || `git ${args.join(" ")} failed`); + } + return result.stdout ?? ""; + } + + private isCommitHash(value: string): boolean { + return /^[0-9a-f]{40}$/i.test(value); + } + + private isUndoTargetMessage(message: SessionMessage): boolean { + return message.role === "user" && message.visible && !message.compacted; + } + private ensureProjectDir(): string { const { projectDir } = this.getProjectStorage(); fs.mkdirSync(projectDir, { recursive: true }); @@ -1628,6 +1927,7 @@ ${skillMd} visible: true, createTime: now, updateTime: now, + checkpointHash: this.getCurrentCheckpointHash(sessionId), }; } @@ -1795,6 +2095,8 @@ ${skillMd} onProcessExit: (pid) => this.removeSessionProcess(sessionId, pid), onProcessStdout: (pid, chunk) => this.onProcessStdout?.(Number(pid), chunk), onProcessTimeoutControl: (pid, control) => this.setSessionProcessTimeoutControl(sessionId, pid, control), + onBeforeFileMutation: (filePath) => this.prepareFileMutationCheckpoint(sessionId, filePath), + onAfterFileMutation: (filePath) => this.recordFileMutationCheckpoint(sessionId, filePath), shouldStop: () => this.isInterrupted(sessionId), }); if (this.isInterrupted(sessionId)) { diff --git a/src/tests/promptInputKeys.test.ts b/src/tests/promptInputKeys.test.ts index 69d2075..54213a1 100644 --- a/src/tests/promptInputKeys.test.ts +++ b/src/tests/promptInputKeys.test.ts @@ -19,10 +19,11 @@ import { toggleSkillSelection, renderBufferWithCursor, buildInitPromptSubmission, + buildPromptDraftFromSessionMessage, disableTerminalExtendedKeys, enableTerminalExtendedKeys, } from "../ui"; -import type { SkillInfo } from "../session"; +import type { SessionMessage, SkillInfo } from "../session"; test("parseTerminalInput treats DEL bytes as backspace", () => { const { input, key } = parseTerminalInput("\u007F"); @@ -112,6 +113,31 @@ test("terminal extended key helpers request and restore modifyOtherKeys mode", ( assert.equal(disableTerminalExtendedKeys(), "\u001B[>4;0m"); }); +test("buildPromptDraftFromSessionMessage restores text and image urls", () => { + const message: SessionMessage = { + id: "user-with-images", + sessionId: "session-1", + role: "user", + content: "revise this prompt", + contentParams: [ + { type: "image_url", image_url: { url: "data:image/png;base64,abc" } }, + { type: "text", text: "ignored" }, + { type: "image_url", image_url: { url: "data:image/jpeg;base64,def" } }, + ], + messageParams: null, + compacted: false, + visible: true, + createTime: "2026-01-01T00:00:00.000Z", + updateTime: "2026-01-01T00:00:00.000Z", + }; + + assert.deepEqual(buildPromptDraftFromSessionMessage(message, 7), { + nonce: 7, + text: "revise this prompt", + imageUrls: ["data:image/png;base64,abc", "data:image/jpeg;base64,def"], + }); +}); + test("parseTerminalInput recognizes terminal focus events", () => { const focusIn = parseTerminalInput("\u001B[I"); const focusOut = parseTerminalInput("\u001B[O"); diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index bfe5bad..c02c0fa 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1,5 +1,6 @@ import { afterEach, test } from "node:test"; import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; @@ -887,6 +888,219 @@ test("replySession continues without appending /continue as a user message", asy assert.equal(fetchCalls.length, 0); }); +test("replySession records the current file-history branch head as checkpointHash", async (t) => { + if (!hasGit()) { + t.skip("git is not available"); + return; + } + + const workspace = createTempDir("deepcode-checkpoint-hash-workspace-"); + const home = createTempDir("deepcode-checkpoint-hash-home-"); + setHomeDir(home); + + const manager = createSessionManager(workspace, "machine-id-checkpoint-hash"); + (manager as any).activateSession = async () => {}; + + const sessionId = await manager.createSession({ text: "first prompt" }); + const checkpointHash = createFileHistoryCommit(home, workspace, sessionId, { "note.txt": "checkpoint\n" }); + + await manager.replySession(sessionId, { text: "second prompt" }); + + const userMessages = manager.listSessionMessages(sessionId).filter((message) => message.role === "user"); + assert.equal(userMessages[userMessages.length - 1]?.checkpointHash, checkpointHash); +}); + +test("createSession initializes file-history repo and session branch", async (t) => { + if (!hasGit()) { + t.skip("git is not available"); + return; + } + + const workspace = createTempDir("deepcode-file-history-init-workspace-"); + const home = createTempDir("deepcode-file-history-init-home-"); + setHomeDir(home); + + const manager = createSessionManager(workspace, "machine-id-file-history-init"); + (manager as any).activateSession = async () => {}; + + const sessionId = await manager.createSession({ text: "first prompt" }); + const userMessage = manager.listSessionMessages(sessionId).find((message) => message.role === "user"); + const gitDir = path.join( + home, + ".deepcode", + "projects", + workspace.replace(/[\\/]/g, "-").replace(/:/g, ""), + "file-history", + ".git" + ); + + assert.ok(fs.existsSync(gitDir)); + assert.ok(userMessage?.checkpointHash); + assert.equal( + runFileHistoryGit(gitDir, workspace, ["rev-parse", "--verify", `refs/heads/${sessionId}^{commit}`]).trim(), + userMessage.checkpointHash + ); +}); + +test("Write tool advances file-history while preserving the user prompt checkpoint", async (t) => { + if (!hasGit()) { + t.skip("git is not available"); + return; + } + + const workspace = createTempDir("deepcode-write-checkpoint-workspace-"); + const home = createTempDir("deepcode-write-checkpoint-home-"); + setHomeDir(home); + + const filePath = path.join(workspace, "index.html"); + const manager = createMockedClientSessionManager(workspace, [ + { + choices: [ + { + message: { + content: "", + tool_calls: [ + { + id: "call-write-index", + type: "function", + function: { + name: "write", + arguments: JSON.stringify({ file_path: filePath, content: "

Hello

\n" }), + }, + }, + ], + }, + }, + ], + }, + createChatResponse("done", { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }), + ]); + + const sessionId = await manager.createSession({ text: "create an index page" }); + const userMessage = manager.listSessionMessages(sessionId).find((message) => message.role === "user"); + assert.ok(userMessage?.checkpointHash); + assert.equal(fs.existsSync(filePath), true); + + manager.restoreSessionCode(sessionId, userMessage.id); + + assert.equal(fs.existsSync(filePath), false); +}); + +test("missing git executable does not block sessions or Write tool calls", async () => { + const workspace = createTempDir("deepcode-no-git-write-workspace-"); + const home = createTempDir("deepcode-no-git-write-home-"); + setHomeDir(home); + + const originalPath = process.env.PATH; + process.env.PATH = ""; + try { + const filePath = path.join(workspace, "index.html"); + const manager = createMockedClientSessionManager(workspace, [ + { + choices: [ + { + message: { + content: "", + tool_calls: [ + { + id: "call-write-no-git", + type: "function", + function: { + name: "write", + arguments: JSON.stringify({ file_path: filePath, content: "

No Git

\n" }), + }, + }, + ], + }, + }, + ], + }, + createChatResponse("done", { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }), + ]); + + const sessionId = await manager.createSession({ text: "create an index page" }); + const userMessage = manager.listSessionMessages(sessionId).find((message) => message.role === "user"); + + assert.equal(fs.readFileSync(filePath, "utf8"), "

No Git

\n"); + assert.equal(userMessage?.checkpointHash, undefined); + assert.equal(manager.getSession(sessionId)?.status, "completed"); + } finally { + if (originalPath === undefined) { + delete process.env.PATH; + } else { + process.env.PATH = originalPath; + } + } +}); + +test("restoreSessionConversation truncates messages before the selected user prompt", async () => { + const workspace = createTempDir("deepcode-undo-conversation-workspace-"); + const home = createTempDir("deepcode-undo-conversation-home-"); + setHomeDir(home); + + const manager = createSessionManager(workspace, "machine-id-undo-conversation"); + (manager as any).activateSession = async () => {}; + + const sessionId = await manager.createSession({ text: "first prompt" }); + const firstAssistant = (manager as any).buildAssistantMessage( + sessionId, + "first answer", + null, + null + ) as SessionMessage; + (manager as any).appendSessionMessage(sessionId, firstAssistant); + await manager.replySession(sessionId, { text: "second prompt" }); + const secondUserMessage = manager + .listSessionMessages(sessionId) + .filter((message) => message.role === "user") + .at(-1); + assert.ok(secondUserMessage); + const secondAssistant = (manager as any).buildAssistantMessage( + sessionId, + "second answer", + null, + null + ) as SessionMessage; + (manager as any).appendSessionMessage(sessionId, secondAssistant); + + manager.restoreSessionConversation(sessionId, secondUserMessage.id); + + const contents = manager.listSessionMessages(sessionId).map((message) => message.content); + assert.ok(contents.includes("first prompt")); + assert.ok(contents.includes("first answer")); + assert.ok(!contents.includes("second prompt")); + assert.ok(!contents.includes("second answer")); + assert.equal(manager.getSession(sessionId)?.assistantReply, "first answer"); +}); + +test("restoreSessionCode restores project files from the recorded Git checkpoint", async (t) => { + if (!hasGit()) { + t.skip("git is not available"); + return; + } + + const workspace = createTempDir("deepcode-undo-code-workspace-"); + const home = createTempDir("deepcode-undo-code-home-"); + setHomeDir(home); + + const manager = createSessionManager(workspace, "machine-id-undo-code"); + const sessionId = "session-code-restore"; + const checkpointHash = createFileHistoryCommit(home, workspace, sessionId, { "tracked.txt": "before\n" }); + createFileHistoryCommit(home, workspace, sessionId, { "tracked.txt": "after\n", "new.txt": "remove me\n" }); + fs.writeFileSync(path.join(workspace, "tracked.txt"), "after\n", "utf8"); + fs.writeFileSync(path.join(workspace, "new.txt"), "remove me\n", "utf8"); + + (manager as any).appendSessionMessage(sessionId, { + ...buildTestMessage("user-with-checkpoint", sessionId, "user", "restore here"), + checkpointHash, + }); + + manager.restoreSessionCode(sessionId, "user-with-checkpoint"); + + assert.equal(fs.readFileSync(path.join(workspace, "tracked.txt"), "utf8"), "before\n"); + assert.equal(fs.existsSync(path.join(workspace, "new.txt")), false); +}); + test("replySession /continue runs trailing pending tool calls before requesting another response", async () => { const workspace = createTempDir("deepcode-continue-tool-workspace-"); const home = createTempDir("deepcode-continue-tool-home-"); @@ -1737,6 +1951,88 @@ test("SessionManager adjusts the active Bash timeout control and session metadat assert.equal(processInfo?.deadlineAt, new Date(timeoutInfo.deadlineAtMs).toISOString()); }); +function hasGit(): boolean { + try { + execFileSync("git", ["--version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +} + +function createFileHistoryCommit( + home: string, + workspace: string, + sessionId: string, + files: Record +): string { + const projectCode = workspace.replace(/[\\/]/g, "-").replace(/:/g, ""); + const gitDir = path.join(home, ".deepcode", "projects", projectCode, "file-history", ".git"); + const branchRef = `refs/heads/${sessionId}`; + fs.mkdirSync(path.dirname(gitDir), { recursive: true }); + if (!fs.existsSync(gitDir)) { + runFileHistoryGit(gitDir, workspace, ["init"]); + } + + let parentHash = ""; + try { + parentHash = runFileHistoryGit(gitDir, workspace, ["rev-parse", "--verify", `${branchRef}^{commit}`]).trim(); + } catch { + const emptyTree = runFileHistoryGit(gitDir, workspace, ["mktree"], ""); + parentHash = runFileHistoryGit( + gitDir, + workspace, + ["commit-tree", emptyTree.trim(), "-m", "initial checkpoint"], + "", + fileHistoryCommitEnv() + ).trim(); + runFileHistoryGit(gitDir, workspace, ["update-ref", branchRef, parentHash]); + } + runFileHistoryGit(gitDir, workspace, ["read-tree", "--reset", branchRef]); + + for (const [relativePath, content] of Object.entries(files)) { + const filePath = path.join(workspace, relativePath); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, content, "utf8"); + } + runFileHistoryGit(gitDir, workspace, ["add", "-f", "-A", "--", ...Object.keys(files)]); + const treeHash = runFileHistoryGit(gitDir, workspace, ["write-tree"]).trim(); + const commitHash = runFileHistoryGit( + gitDir, + workspace, + ["commit-tree", treeHash, "-p", parentHash, "-m", "checkpoint"], + "", + fileHistoryCommitEnv() + ).trim(); + runFileHistoryGit(gitDir, workspace, ["update-ref", branchRef, commitHash, parentHash]); + return commitHash; +} + +function runFileHistoryGit( + gitDir: string, + workspace: string, + args: string[], + input = "", + env: NodeJS.ProcessEnv = process.env +): string { + return execFileSync("git", [`--git-dir=${gitDir}`, `--work-tree=${workspace}`, ...args], { + encoding: "utf8", + input, + env, + stdio: ["pipe", "pipe", "pipe"], + }); +} + +function fileHistoryCommitEnv(): NodeJS.ProcessEnv { + return { + ...process.env, + GIT_AUTHOR_NAME: "DeepCode Test", + GIT_AUTHOR_EMAIL: "deepcode-test@example.com", + GIT_COMMITTER_NAME: "DeepCode Test", + GIT_COMMITTER_EMAIL: "deepcode-test@example.com", + }; +} + function createSessionManager(projectRoot: string, machineId: string): SessionManager { return new SessionManager({ projectRoot, diff --git a/src/tests/slashCommands.test.ts b/src/tests/slashCommands.test.ts index 34b48d0..30d77ee 100644 --- a/src/tests/slashCommands.test.ts +++ b/src/tests/slashCommands.test.ts @@ -19,7 +19,18 @@ test("buildSlashCommands prefixes skills before built-ins", () => { assert.equal(items[0].kind, "skill"); assert.equal(items[0].name, "skill-writer"); const builtinNames = items.filter((i) => i.kind !== "skill").map((i) => i.name); - assert.deepEqual(builtinNames, ["skills", "model", "new", "init", "resume", "continue", "mcp", "raw", "exit"]); + assert.deepEqual(builtinNames, [ + "skills", + "model", + "new", + "init", + "resume", + "continue", + "undo", + "mcp", + "raw", + "exit", + ]); }); test("filterSlashCommands matches partial prefixes", () => { @@ -66,6 +77,13 @@ test("findExactSlashCommand returns built-in /continue", () => { assert.equal(item?.kind, "continue"); }); +test("findExactSlashCommand returns built-in /undo", () => { + const items = buildSlashCommands(skills); + const item = findExactSlashCommand(items, "/undo"); + assert.ok(item); + assert.equal(item?.kind, "undo"); +}); + test("findExactSlashCommand returns built-in /skills", () => { const items = buildSlashCommands(skills); const item = findExactSlashCommand(items, "/skills"); diff --git a/src/tools/edit-handler.ts b/src/tools/edit-handler.ts index 29108e5..454a673 100644 --- a/src/tools/edit-handler.ts +++ b/src/tools/edit-handler.ts @@ -321,7 +321,9 @@ export async function handleEditTool( const updated = applyReplacement(raw, replacementOldString, replacementNewString, matches, replaceAll); const diffPreview = buildDiffPreview(filePath, raw, updated); + context.onBeforeFileMutation?.(filePath); writeTextFile(filePath, updated, metadata.encoding, metadata.lineEndings); + context.onAfterFileMutation?.(filePath); const freshMetadata = readTextFileWithMetadata(filePath); recordFileState( context.sessionId, diff --git a/src/tools/executor.ts b/src/tools/executor.ts index 093e9f3..73e31f5 100644 --- a/src/tools/executor.ts +++ b/src/tools/executor.ts @@ -40,6 +40,8 @@ export type ToolExecutionContext = { onProcessExit?: (processId: string | number) => void; onProcessStdout?: (processId: string | number, chunk: string) => void; onProcessTimeoutControl?: (processId: string | number, control: ProcessTimeoutControl | null) => void; + onBeforeFileMutation?: (filePath: string) => void; + onAfterFileMutation?: (filePath: string) => void; bashTimeoutMs?: number; bashMinTimeoutMs?: number; }; @@ -49,6 +51,8 @@ export type ToolExecutionHooks = { onProcessExit?: (processId: string | number) => void; onProcessStdout?: (processId: string | number, chunk: string) => void; onProcessTimeoutControl?: (processId: string | number, control: ProcessTimeoutControl | null) => void; + onBeforeFileMutation?: (filePath: string) => void; + onAfterFileMutation?: (filePath: string) => void; shouldStop?: () => boolean; }; @@ -217,6 +221,8 @@ export class ToolExecutor { onProcessExit: hooks?.onProcessExit, onProcessStdout: hooks?.onProcessStdout, onProcessTimeoutControl: hooks?.onProcessTimeoutControl, + onBeforeFileMutation: hooks?.onBeforeFileMutation, + onAfterFileMutation: hooks?.onAfterFileMutation, }); } catch (error) { const message = error instanceof Error ? error.message : String(error); diff --git a/src/tools/write-handler.ts b/src/tools/write-handler.ts index 153c1c6..a4c81bf 100644 --- a/src/tools/write-handler.ts +++ b/src/tools/write-handler.ts @@ -97,7 +97,9 @@ export async function handleWriteTool( const encoding = existingMetadata?.encoding ?? "utf8"; const lineEndings = existingMetadata?.lineEndings ?? (input.content.includes("\r\n") ? "CRLF" : "LF"); const diffPreview = buildDiffPreview(filePath, existingMetadata?.content ?? null, normalizedContent); + context.onBeforeFileMutation?.(filePath); const bytes = writeTextFile(filePath, normalizedContent, encoding, lineEndings); + context.onAfterFileMutation?.(filePath); const freshMetadata = readTextFileWithMetadata(filePath); recordFileState( diff --git a/src/ui/App.tsx b/src/ui/App.tsx index c729dc0..70f9755 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -13,6 +13,7 @@ import { type SessionMessage, type SessionStatus, type SkillInfo, + type UndoTarget, type UserPromptContent, } from "../session"; import { @@ -22,9 +23,10 @@ import { type ResolvedDeepcodingSettings, resolveSettingsSources, } from "../settings"; -import { PromptInput, type PromptSubmission } from "./PromptInput"; +import { PromptInput, type PromptDraft, type PromptSubmission } from "./PromptInput"; import { MessageView, RawModeExitPrompt } from "./compoments"; import { SessionList } from "./SessionList"; +import { UndoSelector, type UndoRestoreMode } from "./UndoSelector"; import { buildLoadingText } from "./loadingText"; import { findExpandedThinkingId } from "./thinkingState"; import { WelcomeScreen } from "./WelcomeScreen"; @@ -43,7 +45,7 @@ import { renderMessageToStdout } from "./compoments/MessageView/utils"; const DEFAULT_MODEL = "deepseek-v4-pro"; const DEFAULT_BASE_URL = "https://api.deepseek.com"; -type View = "chat" | "session-list" | "mcp-status"; +type View = "chat" | "session-list" | "undo" | "mcp-status"; type AppProps = { projectRoot: string; @@ -67,6 +69,8 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. const [skills, setSkills] = useState([]); const [messages, setMessages] = useState([]); const [sessions, setSessions] = useState([]); + const [undoTargets, setUndoTargets] = useState([]); + const [promptDraft, setPromptDraft] = useState(null); const [statusLine, setStatusLine] = useState(""); const [errorLine, setErrorLine] = useState(null); const [streamProgress, setStreamProgress] = useState(null); @@ -223,6 +227,17 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setView("session-list"); return; } + if (submission.command === "undo") { + const activeSessionId = sessionManager.getActiveSessionId(); + if (!activeSessionId) { + setErrorLine("No active session to undo."); + return; + } + setShowWelcome(false); + setUndoTargets(sessionManager.listUndoTargets(activeSessionId)); + setView("undo"); + return; + } if (submission.command === "mcp") { setShowWelcome(false); setMcpStatuses(sessionManager.getMcpStatus()); @@ -337,6 +352,20 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. [handlePrompt] ); + const reloadActiveSessionView = useCallback( + (sessionId: string): void => { + process.stdout.write("\u001B[2J\u001B[3J\u001B[H"); + setMessages([]); + setShowWelcome(false); + setWelcomeNonce((n) => n + 1); + setTimeout(() => { + setMessages(loadVisibleMessages(sessionManager, sessionId)); + setShowWelcome(true); + }, 0); + }, + [sessionManager] + ); + useEffect(() => { if (initialPromptSubmittedRef.current || !initialPrompt || !initialPrompt.trim()) { return; @@ -376,6 +405,45 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. [sessionManager, refreshSkills] ); + const handleUndoRestore = useCallback( + async (target: UndoTarget, restoreMode: UndoRestoreMode): Promise => { + const sessionId = sessionManager.getActiveSessionId(); + if (!sessionId) { + setErrorLine("No active session to undo."); + setView("chat"); + setShowWelcome(true); + return; + } + + const errors: string[] = []; + if (restoreMode === "code-and-conversation") { + try { + sessionManager.restoreSessionCode(sessionId, target.message.id); + } catch (error) { + errors.push(`Code restore failed: ${error instanceof Error ? error.message : String(error)}`); + } + } + + let conversationRestored = false; + try { + sessionManager.restoreSessionConversation(sessionId, target.message.id); + conversationRestored = true; + } catch (error) { + errors.push(`Conversation restore failed: ${error instanceof Error ? error.message : String(error)}`); + } + + refreshSessionsList(); + await refreshSkills(sessionId); + setView("chat"); + setErrorLine(errors.length > 0 ? errors.join(" ") : null); + if (conversationRestored) { + setPromptDraft(buildPromptDraftFromSessionMessage(target.message, Date.now())); + } + reloadActiveSessionView(sessionId); + }, + [reloadActiveSessionView, refreshSessionsList, refreshSkills, sessionManager] + ); + const handleRawModeChange = useCallback( (nextMode: string) => { const activeSessionId = sessionManager.getActiveSessionId(); @@ -584,6 +652,15 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. onSelect={(id) => void handleSelectSession(id)} onCancel={() => setView("chat")} /> + ) : view === "undo" ? ( + void handleUndoRestore(target, restoreMode)} + onCancel={() => { + setView("chat"); + setShowWelcome(true); + }} + /> ) : view === "mcp-status" ? ( setView("chat")} /> ) : shouldShowQuestionPrompt && pendingQuestion && !busy ? ( @@ -602,6 +679,7 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. busy={busy} loadingText={loadingText} runningProcesses={runningProcesses} + promptDraft={promptDraft} onSubmit={handleSubmit} onModelConfigChange={handleModelConfigChange} onRawModeChange={handleRawModeChange} @@ -646,6 +724,30 @@ function buildSyntheticUserMessage(content: string, imageCount: number): Session }; } +export function buildPromptDraftFromSessionMessage(message: SessionMessage, nonce: number): PromptDraft { + return { + nonce, + text: typeof message.content === "string" ? message.content : "", + imageUrls: extractImageUrlsFromContentParams(message.contentParams), + }; +} + +function extractImageUrlsFromContentParams(contentParams: unknown): string[] { + const params = Array.isArray(contentParams) ? contentParams : contentParams ? [contentParams] : []; + const imageUrls: string[] = []; + for (const param of params) { + if (!param || typeof param !== "object") { + continue; + } + const record = param as { type?: unknown; image_url?: { url?: unknown } }; + const url = record.image_url?.url; + if (record.type === "image_url" && typeof url === "string" && url) { + imageUrls.push(url); + } + } + return imageUrls; +} + function isCurrentSessionEmpty(sessionManager: SessionManager): boolean { const activeSessionId = sessionManager.getActiveSessionId(); return !activeSessionId || !sessionManager.getSession(activeSessionId); diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index b35f72e..ffb614d 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -57,7 +57,13 @@ export type PromptSubmission = { text: string; imageUrls: string[]; selectedSkills?: SkillInfo[]; - command?: "new" | "resume" | "continue" | "mcp" | "exit"; + command?: "new" | "resume" | "continue" | "undo" | "mcp" | "exit"; +}; + +export type PromptDraft = { + nonce: number; + text: string; + imageUrls: string[]; }; type Props = { @@ -71,6 +77,7 @@ type Props = { disabled?: boolean; placeholder?: string; runningProcesses?: SessionEntry["processes"]; + promptDraft?: PromptDraft | null; onSubmit: (submission: PromptSubmission) => void; onModelConfigChange: (selection: ModelConfigSelection) => string | Promise; onRawModeChange?: (mode: string) => void; @@ -124,6 +131,7 @@ export const PromptInput = React.memo(function PromptInput({ disabled, placeholder, runningProcesses, + promptDraft, onSubmit, onModelConfigChange, onInterrupt, @@ -154,6 +162,7 @@ export const PromptInput = React.memo(function PromptInput({ const undoRedoRef = React.useRef(createPromptUndoRedoState()); const wasBusyRef = React.useRef(busy); const hadFileMentionTokenRef = React.useRef(false); + const appliedDraftNonceRef = React.useRef(null); const fileMentionToken = getCurrentFileMentionToken(buffer); const hasFileMentionToken = fileMentionToken !== null; @@ -266,6 +275,22 @@ export const PromptInput = React.memo(function PromptInput({ return () => clearTimeout(timer); }, [statusMessage]); + useEffect(() => { + if (!promptDraft || appliedDraftNonceRef.current === promptDraft.nonce) { + return; + } + appliedDraftNonceRef.current = promptDraft.nonce; + setBuffer({ text: promptDraft.text, cursor: promptDraft.text.length }); + setImageUrls(promptDraft.imageUrls); + setSelectedSkills([]); + setShowSkillsDropdown(false); + setOpenRawModelDropdown(false); + setModelDropdownStep(null); + setHistoryCursor(-1); + setDraftBeforeHistory(null); + clearPromptUndoRedoState(undoRedoRef.current); + }, [promptDraft]); + useEffect(() => { setHistoryCursor(-1); setDraftBeforeHistory(null); @@ -766,6 +791,15 @@ export const PromptInput = React.memo(function PromptInput({ setShowSkillsDropdown(false); return; } + if (item.kind === "undo") { + onSubmit({ text: "/undo", imageUrls: [], command: "undo" }); + setBuffer(EMPTY_BUFFER); + clearUndoRedoStacks(); + setImageUrls([]); + setSelectedSkills([]); + setShowSkillsDropdown(false); + return; + } if (item.kind === "mcp") { onSubmit({ text: "/mcp", imageUrls: [], command: "mcp" }); setBuffer(EMPTY_BUFFER); diff --git a/src/ui/UndoSelector.tsx b/src/ui/UndoSelector.tsx new file mode 100644 index 0000000..fad3e17 --- /dev/null +++ b/src/ui/UndoSelector.tsx @@ -0,0 +1,195 @@ +import React, { useMemo, useState } from "react"; +import { Box, Text, useInput, useWindowSize } from "ink"; +import type { UndoTarget } from "../session"; + +export type UndoRestoreMode = "code-and-conversation" | "conversation"; + +type Props = { + targets: UndoTarget[]; + onSelect: (target: UndoTarget, mode: UndoRestoreMode) => void; + onCancel: () => void; +}; + +type Phase = "message" | "mode"; + +const MAX_VISIBLE_TARGETS = 7; + +export function UndoSelector({ targets, onSelect, onCancel }: Props): React.ReactElement { + const [phase, setPhase] = useState("message"); + const [targetIndex, setTargetIndex] = useState(Math.max(0, targets.length - 1)); + const [modeIndex, setModeIndex] = useState(0); + const { columns, rows } = useWindowSize(); + + const safeTargetIndex = useMemo(() => { + if (targets.length === 0) { + return 0; + } + return Math.max(0, Math.min(targetIndex, targets.length - 1)); + }, [targetIndex, targets.length]); + + const selectedTarget = targets[safeTargetIndex] ?? null; + const maxVisible = Math.max(1, Math.min(MAX_VISIBLE_TARGETS, rows - 8)); + const scrollOffset = Math.max(0, Math.min(safeTargetIndex - Math.floor(maxVisible / 2), targets.length - maxVisible)); + const visibleTargets = targets.slice(scrollOffset, scrollOffset + maxVisible); + + useInput((input, key) => { + if (key.escape || (key.ctrl && (input === "c" || input === "C"))) { + if (phase === "mode") { + setPhase("message"); + return; + } + onCancel(); + return; + } + + if (targets.length === 0) { + return; + } + + if (phase === "message") { + if (key.upArrow) { + setTargetIndex((index) => Math.max(0, index - 1)); + return; + } + if (key.downArrow) { + setTargetIndex((index) => Math.min(targets.length - 1, index + 1)); + return; + } + if (key.home) { + setTargetIndex(0); + return; + } + if (key.end) { + setTargetIndex(targets.length - 1); + return; + } + if (key.return) { + setModeIndex(selectedTarget?.canRestoreCode ? 0 : 1); + setPhase("mode"); + } + return; + } + + if (key.upArrow || key.downArrow) { + setModeIndex((index) => (index === 0 ? 1 : 0)); + return; + } + if (key.return && selectedTarget) { + onSelect(selectedTarget, modeIndex === 0 ? "code-and-conversation" : "conversation"); + } + }); + + if (targets.length === 0) { + return ( + + Nothing to undo yet. + Press Esc to go back. + + ); + } + + return ( + + + + + Undo + + restore to the point before a prompt + + {phase === "message" ? ( + + {visibleTargets.map((target, visibleIndex) => { + const actualIndex = scrollOffset + visibleIndex; + const isActive = actualIndex === safeTargetIndex; + return ( + + {isActive ? "> " : " "} + + + {formatUndoMessage(target.message.content)} + + + {formatTimestamp(target.message.createTime)} + {target.canRestoreCode ? " · code checkpoint available" : " · conversation only"} + + + + ); + })} + + ) : ( + + Selected prompt: + {formatUndoMessage(selectedTarget?.message.content ?? "")} + + + {modeIndex === 0 ? "> " : " "}Restore code and conversation + + + {" "} + {selectedTarget?.canRestoreCode + ? "Restore files from the recorded Git checkpoint, then fork the conversation." + : "No code checkpoint is recorded for this prompt."} + + + {modeIndex === 1 ? "> " : " "}Restore conversation + + {" "}Fork the conversation without changing files. + + + )} + + + {phase === "message" + ? "↑/↓ navigate · Enter choose · Esc cancel" + : "↑/↓ choose restore mode · Enter restore · Esc back"} + + + + + ); +} + +function formatUndoMessage(content: unknown): string { + const text = typeof content === "string" && content.trim() ? content.trim() : "(empty message)"; + const singleLine = text.replace(/\r?\n/g, " ").replace(/\s+/g, " "); + return singleLine.length > 90 ? `${singleLine.slice(0, 89)}…` : singleLine; +} + +function formatTimestamp(value: string): string { + const date = new Date(value); + if (Number.isNaN(date.valueOf())) { + return value; + } + return date.toLocaleString(); +} diff --git a/src/ui/index.ts b/src/ui/index.ts index f2e698c..656b582 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -6,6 +6,7 @@ export { writeModelConfigSelection, resolveCurrentSettings, createOpenAIClient, + buildPromptDraftFromSessionMessage, } from "./App"; export { default as AppContainer } from "./AppContainer"; export { AskUserQuestionPrompt } from "./AskUserQuestionPrompt"; @@ -30,6 +31,7 @@ export { useTerminalInput, parseTerminalInput, type PromptSubmission, + type PromptDraft, type InputKey, } from "./PromptInput"; export { disableTerminalExtendedKeys, enableTerminalExtendedKeys, getPromptCursorPlacement } from "./prompt/cursor"; diff --git a/src/ui/slashCommands.ts b/src/ui/slashCommands.ts index 948a7ab..6d9b7cc 100644 --- a/src/ui/slashCommands.ts +++ b/src/ui/slashCommands.ts @@ -8,6 +8,7 @@ export type SlashCommandKind = | "init" | "resume" | "continue" + | "undo" | "mcp" | "raw" | "exit"; @@ -58,6 +59,12 @@ export const BUILTIN_SLASH_COMMANDS: SlashCommandItem[] = [ label: "/continue", description: "Continue the active conversation or pick one to resume", }, + { + kind: "undo", + name: "undo", + label: "/undo", + description: "Restore code and/or conversation to a previous point", + }, { kind: "mcp", name: "mcp", From 883f1fd051a648b67b457288580565b6f7c7aca0 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Wed, 20 May 2026 11:46:52 +0800 Subject: [PATCH 087/129] refactor: extract the file-history checkpoint logic out of SessionManager --- src/common/file-history.ts | 194 ++++++++++++++++++++++++++++++++++++ src/session.ts | 196 +++---------------------------------- 2 files changed, 209 insertions(+), 181 deletions(-) create mode 100644 src/common/file-history.ts diff --git a/src/common/file-history.ts b/src/common/file-history.ts new file mode 100644 index 0000000..5194e6e --- /dev/null +++ b/src/common/file-history.ts @@ -0,0 +1,194 @@ +import * as childProcess from "child_process"; +import * as fs from "fs"; +import * as path from "path"; + +const FILE_HISTORY_AUTHOR_NAME = "DeepCode Checkpoint"; +const FILE_HISTORY_AUTHOR_EMAIL = "deepcode-checkpoint@localhost"; + +export class GitFileHistory { + constructor( + private readonly projectRoot: string, + private readonly gitDir: string + ) {} + + ensureSession(sessionId: string): string | undefined { + const branchRef = this.getSessionBranchRef(sessionId); + if (!branchRef) { + return undefined; + } + + try { + if (!fs.existsSync(this.gitDir)) { + fs.mkdirSync(path.dirname(this.gitDir), { recursive: true }); + this.runGit(["init"], { includeWorkTree: true }); + } + + const current = this.getCurrentCheckpointHash(sessionId); + if (current) { + return current; + } + + const emptyTree = this.runGit(["mktree"], { includeWorkTree: false, input: "" }).trim(); + const commitHash = this.createCommit(emptyTree, null, "Initial checkpoint"); + this.runGit(["update-ref", branchRef, commitHash], { includeWorkTree: false }); + return commitHash; + } catch { + return undefined; + } + } + + getCurrentCheckpointHash(sessionId: string): string | undefined { + const branchRef = this.getSessionBranchRef(sessionId); + if (!branchRef || !fs.existsSync(this.gitDir)) { + return undefined; + } + + try { + const hash = this.runGit(["rev-parse", "--verify", `${branchRef}^{commit}`], { + includeWorkTree: false, + }).trim(); + return isCommitHash(hash) ? hash : undefined; + } catch { + return undefined; + } + } + + recordCheckpoint(sessionId: string, filePaths: string[], message: string): string | undefined { + const branchRef = this.getSessionBranchRef(sessionId); + if (!branchRef) { + return undefined; + } + + const relativePaths = filePaths + .map((filePath) => this.toProjectRelativeGitPath(filePath)) + .filter((filePath): filePath is string => Boolean(filePath)); + if (relativePaths.length === 0) { + return this.getCurrentCheckpointHash(sessionId); + } + + try { + const parentHash = this.ensureSession(sessionId); + if (!parentHash) { + return undefined; + } + this.runGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); + this.runGit(["add", "-f", "-A", "--", ...relativePaths], { includeWorkTree: true }); + const treeHash = this.runGit(["write-tree"], { includeWorkTree: false }).trim(); + const parentTreeHash = this.runGit(["rev-parse", `${parentHash}^{tree}`], { + includeWorkTree: false, + }).trim(); + if (treeHash === parentTreeHash) { + return parentHash; + } + + const commitHash = this.createCommit(treeHash, parentHash, message); + this.runGit(["update-ref", branchRef, commitHash, parentHash], { includeWorkTree: false }); + return commitHash; + } catch { + return undefined; + } + } + + canRestore(sessionId: string, checkpointHash: string): boolean { + if (!isCommitHash(checkpointHash)) { + return false; + } + if (!this.getSessionBranchRef(sessionId)) { + return false; + } + if (!fs.existsSync(this.gitDir)) { + return false; + } + + try { + this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); + return true; + } catch { + return false; + } + } + + restore(sessionId: string, checkpointHash: string): void { + if (!isCommitHash(checkpointHash)) { + throw new Error("Invalid checkpoint hash."); + } + const branchRef = this.getSessionBranchRef(sessionId); + if (!branchRef || !fs.existsSync(this.gitDir)) { + throw new Error("File history Git repository was not found for this project."); + } + this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); + + try { + this.runGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); + } catch { + // If the session branch is missing, fall back to the target tree only. + // The target checkpoint has already been validated above. + } + this.runGit(["read-tree", "--reset", "-u", checkpointHash], { includeWorkTree: true }); + this.runGit(["update-ref", branchRef, checkpointHash], { includeWorkTree: false }); + } + + private getSessionBranchRef(sessionId: string): string | null { + if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) { + return null; + } + return `refs/heads/${sessionId}`; + } + + private createCommit(treeHash: string, parentHash: string | null, message: string): string { + const args = ["commit-tree", treeHash]; + if (parentHash) { + args.push("-p", parentHash); + } + args.push("-m", message); + return this.runGit(args, { + includeWorkTree: false, + env: getFileHistoryGitEnv(), + }).trim(); + } + + private toProjectRelativeGitPath(filePath: string): string | null { + const absolutePath = path.resolve(filePath); + const relativePath = path.relative(this.projectRoot, absolutePath); + if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) { + return null; + } + return relativePath.split(path.sep).join("/"); + } + + private runGit( + args: string[], + options: { includeWorkTree: boolean; input?: string; env?: NodeJS.ProcessEnv } + ): string { + const gitArgs = [`--git-dir=${this.gitDir}`]; + if (options.includeWorkTree) { + gitArgs.push(`--work-tree=${this.projectRoot}`); + } + gitArgs.push(...args); + const result = childProcess.spawnSync("git", gitArgs, { + encoding: "utf8", + input: options.input, + env: options.env, + stdio: ["pipe", "pipe", "pipe"], + }); + if (result.status !== 0) { + const detail = (result.stderr || result.stdout || "").trim(); + throw new Error(detail || `git ${args.join(" ")} failed`); + } + return result.stdout ?? ""; + } +} + +function getFileHistoryGitEnv(): NodeJS.ProcessEnv { + return { + ...process.env, + GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || FILE_HISTORY_AUTHOR_NAME, + GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || FILE_HISTORY_AUTHOR_EMAIL, + GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || FILE_HISTORY_AUTHOR_NAME, + GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || FILE_HISTORY_AUTHOR_EMAIL, + }; +} + +function isCommitHash(value: string): boolean { + return /^[0-9a-f]{40}$/i.test(value); +} diff --git a/src/session.ts b/src/session.ts index 6b2ceee..88e85b6 100644 --- a/src/session.ts +++ b/src/session.ts @@ -2,7 +2,6 @@ import * as fs from "fs"; import * as path from "path"; import * as os from "os"; import * as crypto from "crypto"; -import * as childProcess from "child_process"; import { fileURLToPath } from "url"; import matter from "gray-matter"; import ejs from "ejs"; @@ -29,14 +28,13 @@ import type { McpServerConfig } from "./settings"; import { logApiError } from "./common/error-logger"; import { logOpenAIChatCompletionDebug, normalizeDebugError } from "./common/debug-logger"; import { killProcessTree } from "./common/process-tree"; +import { GitFileHistory } from "./common/file-history"; const MAX_SESSION_ENTRIES = 50; const DEFAULT_NEW_PROMPT_API_URL = "https://deepcode.vegamo.cn/api/plugin/new"; const NEW_PROMPT_REPORT_TIMEOUT_MS = 3000; const DEFAULT_COMPACT_PROMPT_TOKEN_THRESHOLD = 128 * 1024; const DEEPSEEK_V4_COMPACT_PROMPT_TOKEN_THRESHOLD = 512 * 1024; -const FILE_HISTORY_AUTHOR_NAME = "DeepCode Checkpoint"; -const FILE_HISTORY_AUTHOR_EMAIL = "deepcode-checkpoint@localhost"; type ChatCompletionDebugOptions = { enabled?: boolean; @@ -1585,113 +1583,40 @@ ${skillMd} return { projectCode, projectDir, sessionsIndexPath }; } + private getFileHistory(): GitFileHistory { + return new GitFileHistory(this.projectRoot, this.getFileHistoryGitDir()); + } + private getFileHistoryGitDir(): string { const { projectDir } = this.getProjectStorage(); return path.join(projectDir, "file-history", ".git"); } - private getSessionBranchRef(sessionId: string): string | null { - if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) { - return null; - } - return `refs/heads/${sessionId}`; - } - private ensureFileHistorySession(sessionId: string): string | undefined { - const branchRef = this.getSessionBranchRef(sessionId); - if (!branchRef) { - return undefined; - } - - try { - const gitDir = this.getFileHistoryGitDir(); - if (!fs.existsSync(gitDir)) { - fs.mkdirSync(path.dirname(gitDir), { recursive: true }); - this.runFileHistoryGit(["init"], { includeWorkTree: true }); - } - - const current = this.getCurrentCheckpointHash(sessionId); - if (current) { - return current; - } - - const emptyTree = this.runFileHistoryGit(["mktree"], { includeWorkTree: false, input: "" }).trim(); - const commitHash = this.createFileHistoryCommit(emptyTree, null, "Initial checkpoint"); - this.runFileHistoryGit(["update-ref", branchRef, commitHash], { includeWorkTree: false }); - return commitHash; - } catch { - return undefined; - } + return this.getFileHistory().ensureSession(sessionId); } private getCurrentCheckpointHash(sessionId: string): string | undefined { - const gitDir = this.getFileHistoryGitDir(); - const branchRef = this.getSessionBranchRef(sessionId); - if (!branchRef || !fs.existsSync(gitDir)) { - return undefined; - } - - try { - const hash = this.runFileHistoryGit(["rev-parse", "--verify", `${branchRef}^{commit}`], { - includeWorkTree: false, - }).trim(); - return this.isCommitHash(hash) ? hash : undefined; - } catch { - return undefined; - } + return this.getFileHistory().getCurrentCheckpointHash(sessionId); } private prepareFileMutationCheckpoint(sessionId: string, filePath: string): void { - const previousHash = this.ensureFileHistorySession(sessionId); + const fileHistory = this.getFileHistory(); + const previousHash = fileHistory.ensureSession(sessionId); if (!previousHash) { return; } this.updateLatestUserCheckpointHash(sessionId, undefined, previousHash); - const nextHash = this.recordFileHistoryCheckpoint(sessionId, [filePath], "Pre-mutation checkpoint"); + const nextHash = fileHistory.recordCheckpoint(sessionId, [filePath], "Pre-mutation checkpoint"); if (nextHash && nextHash !== previousHash) { this.updateLatestUserCheckpointHash(sessionId, previousHash, nextHash); } } private recordFileMutationCheckpoint(sessionId: string, filePath: string): void { - this.ensureFileHistorySession(sessionId); - this.recordFileHistoryCheckpoint(sessionId, [filePath], "File mutation checkpoint"); - } - - private recordFileHistoryCheckpoint(sessionId: string, filePaths: string[], message: string): string | undefined { - const branchRef = this.getSessionBranchRef(sessionId); - if (!branchRef) { - return undefined; - } - - const relativePaths = filePaths - .map((filePath) => this.toProjectRelativeGitPath(filePath)) - .filter((filePath): filePath is string => Boolean(filePath)); - if (relativePaths.length === 0) { - return this.getCurrentCheckpointHash(sessionId); - } - - try { - const parentHash = this.ensureFileHistorySession(sessionId); - if (!parentHash) { - return undefined; - } - this.runFileHistoryGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); - this.runFileHistoryGit(["add", "-f", "-A", "--", ...relativePaths], { includeWorkTree: true }); - const treeHash = this.runFileHistoryGit(["write-tree"], { includeWorkTree: false }).trim(); - const parentTreeHash = this.runFileHistoryGit(["rev-parse", `${parentHash}^{tree}`], { - includeWorkTree: false, - }).trim(); - if (treeHash === parentTreeHash) { - return parentHash; - } - - const commitHash = this.createFileHistoryCommit(treeHash, parentHash, message); - this.runFileHistoryGit(["update-ref", branchRef, commitHash, parentHash], { includeWorkTree: false }); - return commitHash; - } catch { - return undefined; - } + const fileHistory = this.getFileHistory(); + fileHistory.ensureSession(sessionId); + fileHistory.recordCheckpoint(sessionId, [filePath], "File mutation checkpoint"); } private updateLatestUserCheckpointHash(sessionId: string, previousHash: string | undefined, nextHash: string): void { @@ -1714,103 +1639,12 @@ ${skillMd} } } - private createFileHistoryCommit(treeHash: string, parentHash: string | null, message: string): string { - const args = ["commit-tree", treeHash]; - if (parentHash) { - args.push("-p", parentHash); - } - args.push("-m", message); - return this.runFileHistoryGit(args, { - includeWorkTree: false, - env: this.getFileHistoryGitEnv(), - }).trim(); - } - - private getFileHistoryGitEnv(): NodeJS.ProcessEnv { - return { - ...process.env, - GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || FILE_HISTORY_AUTHOR_NAME, - GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || FILE_HISTORY_AUTHOR_EMAIL, - GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || FILE_HISTORY_AUTHOR_NAME, - GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || FILE_HISTORY_AUTHOR_EMAIL, - }; - } - - private toProjectRelativeGitPath(filePath: string): string | null { - const absolutePath = path.resolve(filePath); - const relativePath = path.relative(this.projectRoot, absolutePath); - if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) { - return null; - } - return relativePath.split(path.sep).join("/"); - } - private canRestoreCheckpointHash(sessionId: string, checkpointHash: string): boolean { - if (!this.isCommitHash(checkpointHash)) { - return false; - } - if (!this.getSessionBranchRef(sessionId)) { - return false; - } - const gitDir = this.getFileHistoryGitDir(); - if (!fs.existsSync(gitDir)) { - return false; - } - - try { - this.runFileHistoryGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); - return true; - } catch { - return false; - } + return this.getFileHistory().canRestore(sessionId, checkpointHash); } private restoreCheckpointHash(sessionId: string, checkpointHash: string): void { - if (!this.isCommitHash(checkpointHash)) { - throw new Error("Invalid checkpoint hash."); - } - const gitDir = this.getFileHistoryGitDir(); - const branchRef = this.getSessionBranchRef(sessionId); - if (!branchRef || !fs.existsSync(gitDir)) { - throw new Error("File history Git repository was not found for this project."); - } - this.runFileHistoryGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); - - try { - this.runFileHistoryGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); - } catch { - // If the session branch is missing, fall back to the target tree only. - // The target checkpoint has already been validated above. - } - this.runFileHistoryGit(["read-tree", "--reset", "-u", checkpointHash], { includeWorkTree: true }); - this.runFileHistoryGit(["update-ref", branchRef, checkpointHash], { includeWorkTree: false }); - } - - private runFileHistoryGit( - args: string[], - options: { includeWorkTree: boolean; input?: string; env?: NodeJS.ProcessEnv } - ): string { - const gitDir = this.getFileHistoryGitDir(); - const gitArgs = [`--git-dir=${gitDir}`]; - if (options.includeWorkTree) { - gitArgs.push(`--work-tree=${this.projectRoot}`); - } - gitArgs.push(...args); - const result = childProcess.spawnSync("git", gitArgs, { - encoding: "utf8", - input: options.input, - env: options.env, - stdio: ["pipe", "pipe", "pipe"], - }); - if (result.status !== 0) { - const detail = (result.stderr || result.stdout || "").trim(); - throw new Error(detail || `git ${args.join(" ")} failed`); - } - return result.stdout ?? ""; - } - - private isCommitHash(value: string): boolean { - return /^[0-9a-f]{40}$/i.test(value); + this.getFileHistory().restore(sessionId, checkpointHash); } private isUndoTargetMessage(message: SessionMessage): boolean { From 057e3538b286ca5f67a4968674014baf0dbdc808 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Wed, 20 May 2026 12:03:31 +0800 Subject: [PATCH 088/129] fix: Bash timeout session test now uses a temporary HOME --- src/tests/session.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index c02c0fa..3658e1c 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1919,6 +1919,9 @@ test("SessionManager treats OpenAI APIUserAbortError as interrupted", async () = test("SessionManager adjusts the active Bash timeout control and session metadata", async () => { const workspace = createTempDir("deepcode-bash-timeout-session-"); + const home = createTempDir("deepcode-bash-timeout-home-"); + setHomeDir(home); + const manager = createSessionManager(workspace, ""); const sessionId = await manager.createSession({ text: "hello" }); From f37ee2b71c1320820bd0e9b970a45fea4815556f Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 14:00:28 +0800 Subject: [PATCH 089/129] =?UTF-8?q?feat(ui):=20=E6=B7=BB=E5=8A=A0=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E6=8F=90=E5=8F=8A=E8=8F=9C=E5=8D=95=E7=BB=84=E4=BB=B6?= =?UTF-8?q?=E5=B9=B6=E4=BC=98=E5=8C=96PromptInput=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 FileMentionMenu 组件用于文件提及功能显示与交互 - 在 components/index.ts 中导出 FileMentionMenu 组件 - PromptInput 集成 FileMentionMenu 替换原 DropdownMenu 实现 - 重构 PromptInput 相关状态管理及事件处理,移除冗余索引状态 - 提取 resetPromptInput 函数简化重置输入框逻辑 - 优化键盘事件处理逻辑,简化文件提及菜单快捷键支持 - 使用 FileMentionMenu 替换内联菜单渲染,提高代码复用性与可维护性 --- src/ui/PromptInput.tsx | 129 +++++--------------- src/ui/components/FileMentionMenu/index.tsx | 117 ++++++++++++++++++ src/ui/components/index.ts | 1 + 3 files changed, 147 insertions(+), 100 deletions(-) create mode 100644 src/ui/components/FileMentionMenu/index.tsx diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index a79fe30..44e1754 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -50,8 +50,7 @@ import type { InputKey } from "./prompt"; import { useHiddenTerminalCursor, useTerminalExtendedKeys, useTerminalFocusReporting } from "./prompt"; import SlashCommandMenu from "./SlashCommandMenu"; import type { ModelConfigSelection } from "../settings"; -import DropdownMenu from "./DropdownMenu"; -import { ModelsDropdown, RawModelDropdown, SkillsDropdown } from "./components"; +import { FileMentionMenu, ModelsDropdown, RawModelDropdown, SkillsDropdown } from "./components"; export type PromptSubmission = { text: string; @@ -127,7 +126,6 @@ export const PromptInput = React.memo(function PromptInput({ const [openRawModelDropdown, setOpenRawModelDropdown] = useState(false); const [showModelDropdown, setShowModelDropdown] = useState(false); const [fileMentionItems, setFileMentionItems] = useState(() => scanFileMentionItems(projectRoot)); - const [fileMentionIndex, setFileMentionIndex] = useState(0); const [dismissedFileMentionKey, setDismissedFileMentionKey] = useState(null); const [historyCursor, setHistoryCursor] = useState(-1); const [draftBeforeHistory, setDraftBeforeHistory] = useState(null); @@ -213,16 +211,6 @@ export const PromptInput = React.memo(function PromptInput({ } }, [fileMentionKey]); - useEffect(() => { - if (!showFileMentionMenu) { - setFileMentionIndex(0); - return; - } - if (fileMentionIndex >= fileMentionMatches.length) { - setFileMentionIndex(Math.max(0, fileMentionMatches.length - 1)); - } - }, [fileMentionMatches.length, fileMentionIndex, showFileMentionMenu]); - useEffect(() => { if (!statusMessage) { return; @@ -252,8 +240,7 @@ export const PromptInput = React.memo(function PromptInput({ } if (key.escape) { - if (showFileMentionMenu && fileMentionKey) { - setDismissedFileMentionKey(fileMentionKey); + if (showFileMentionMenu) { return; } if (busy) { @@ -345,32 +332,9 @@ export const PromptInput = React.memo(function PromptInput({ const isPlainReturn = returnAction === "submit"; if (showFileMentionMenu) { - if (key.upArrow) { - if (fileMentionMatches.length > 0) { - setFileMentionIndex((idx) => (idx - 1 + fileMentionMatches.length) % fileMentionMatches.length); - } + if (key.upArrow || key.downArrow || key.tab || returnAction === "submit") { return; } - if (key.downArrow) { - if (fileMentionMatches.length > 0) { - setFileMentionIndex((idx) => (idx + 1) % fileMentionMatches.length); - } - return; - } - if (key.tab || returnAction === "submit") { - const selected = fileMentionMatches[fileMentionIndex]; - if (selected && fileMentionToken) { - insertFileMentionSelection(selected); - return; - } - if (key.tab) { - setDismissedFileMentionKey(fileMentionKey); - return; - } - if (fileMentionKey) { - setDismissedFileMentionKey(fileMentionKey); - } - } } if (showMenu) { @@ -613,6 +577,14 @@ export const PromptInput = React.memo(function PromptInput({ setDismissedFileMentionKey(null); } + function resetPromptInput(): void { + setBuffer(EMPTY_BUFFER); + clearUndoRedoStacks(); + setImageUrls([]); + setSelectedSkills([]); + setShowSkillsDropdown(false); + } + function handleSlashSelection(item: SlashCommandItem): void { if (busy && item.kind !== "exit") { setStatusMessage("wait for the current response or press esc to interrupt"); @@ -643,47 +615,27 @@ export const PromptInput = React.memo(function PromptInput({ } if (item.kind === "new") { onSubmit({ text: "", imageUrls: [], command: "new" }); - setBuffer(EMPTY_BUFFER); - clearUndoRedoStacks(); - setImageUrls([]); - setSelectedSkills([]); - setShowSkillsDropdown(false); + resetPromptInput(); return; } if (item.kind === "init") { onSubmit(buildInitPromptSubmission(selectedSkills)); - setBuffer(EMPTY_BUFFER); - clearUndoRedoStacks(); - setImageUrls([]); - setSelectedSkills([]); - setShowSkillsDropdown(false); + resetPromptInput(); return; } if (item.kind === "resume") { onSubmit({ text: "", imageUrls: [], command: "resume" }); - setBuffer(EMPTY_BUFFER); - clearUndoRedoStacks(); - setImageUrls([]); - setSelectedSkills([]); - setShowSkillsDropdown(false); + resetPromptInput(); return; } if (item.kind === "continue") { onSubmit({ text: "/continue", imageUrls: [], command: "continue" }); - setBuffer(EMPTY_BUFFER); - clearUndoRedoStacks(); - setImageUrls([]); - setSelectedSkills([]); - setShowSkillsDropdown(false); + resetPromptInput(); return; } if (item.kind === "mcp") { onSubmit({ text: "/mcp", imageUrls: [], command: "mcp" }); - setBuffer(EMPTY_BUFFER); - clearUndoRedoStacks(); - setImageUrls([]); - setSelectedSkills([]); - setShowSkillsDropdown(false); + resetPromptInput(); return; } if (item.kind === "exit") { @@ -718,11 +670,7 @@ export const PromptInput = React.memo(function PromptInput({ imageUrls, selectedSkills, }); - setBuffer(EMPTY_BUFFER); - clearUndoRedoStacks(); - setImageUrls([]); - setSelectedSkills([]); - setShowSkillsDropdown(false); + resetPromptInput(); } function addSelectedSkill(skill: SkillInfo): void { @@ -798,37 +746,18 @@ export const PromptInput = React.memo(function PromptInput({ onModelConfigChange={onModelConfigChange} onStatusMessage={setStatusMessage} /> - {showFileMentionMenu ? ( - ({ - key: item.path, - label: item.path, - description: item.type === "directory" ? "directory" : "file", - }))} - activeIndex={fileMentionIndex} - activeColor="#229ac3" - maxVisible={8} - renderItem={(item, isActive) => ( - - {isActive ? "> " : " "} - - - {item.label} - - - {item.description ? ( - - {item.description} - - ) : null} - - )} - /> - ) : null} + { + if (fileMentionKey) { + setDismissedFileMentionKey(fileMentionKey); + } + }} + onSelect={insertFileMentionSelection} + /> {!showFooterText && ( diff --git a/src/ui/components/FileMentionMenu/index.tsx b/src/ui/components/FileMentionMenu/index.tsx new file mode 100644 index 0000000..ce9a8ee --- /dev/null +++ b/src/ui/components/FileMentionMenu/index.tsx @@ -0,0 +1,117 @@ +import React, { useEffect, useState } from "react"; +import { Box, Text } from "ink"; +import { useInput } from "ink"; +import DropdownMenu from "../../DropdownMenu"; +import type { FileMentionItem, FileMentionToken } from "../../fileMentions"; + +type Props = { + open: boolean; + width: number; + token: FileMentionToken | null; + items: FileMentionItem[]; + onClose: () => void; + onSelect: (item: FileMentionItem) => void; +}; + +const FileMentionMenu: React.FC = ({ open, width, token, items, onClose, onSelect }) => { + const [activeIndex, setActiveIndex] = useState(0); + + // Reset index when opened + useEffect(() => { + if (open) { + setActiveIndex(0); + } + }, [open]); + + // Validate activeIndex bounds + useEffect(() => { + if (!open) { + return; + } + if (items.length === 0) { + setActiveIndex(0); + return; + } + if (activeIndex >= items.length) { + setActiveIndex(Math.max(0, items.length - 1)); + } + }, [activeIndex, items.length, open]); + + useInput( + (input, key) => { + if (!open) { + return; + } + + if (key.escape) { + onClose(); + return; + } + + if (key.upArrow) { + if (items.length > 0) { + setActiveIndex((idx) => (idx - 1 + items.length) % items.length); + } + return; + } + + if (key.downArrow) { + if (items.length > 0) { + setActiveIndex((idx) => (idx + 1) % items.length); + } + return; + } + + if (key.tab || (key.return && !key.shift && !key.meta)) { + const selected = items[activeIndex]; + if (selected) { + onSelect(selected); + return; + } + if (key.tab) { + onClose(); + } + return; + } + }, + { isActive: open } + ); + + if (!open) { + return null; + } + + return ( + ({ + key: item.path, + label: item.path, + description: item.type === "directory" ? "directory" : "file", + }))} + activeIndex={activeIndex} + activeColor="#229ac3" + maxVisible={8} + renderItem={(item, isActive) => ( + + {isActive ? "> " : " "} + + + {item.label} + + + {item.description ? ( + + {item.description} + + ) : null} + + )} + /> + ); +}; + +export default FileMentionMenu; diff --git a/src/ui/components/index.ts b/src/ui/components/index.ts index 1d929f3..635f733 100644 --- a/src/ui/components/index.ts +++ b/src/ui/components/index.ts @@ -3,3 +3,4 @@ export { MessageView } from "./MessageView"; export { RawModeExitPrompt } from "./RawModeExitPrompt"; export { default as SkillsDropdown } from "./SkillsDropdown"; export { default as ModelsDropdown } from "./ModelsDropdown"; +export { default as FileMentionMenu } from "./FileMentionMenu"; From f611c948fd117c105a7610ca0b8700e181c95140 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Wed, 20 May 2026 14:15:30 +0800 Subject: [PATCH 090/129] fix: update git command options to handle line endings consistently --- src/common/file-history.ts | 2 +- src/tests/session.test.ts | 16 ++++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/common/file-history.ts b/src/common/file-history.ts index 5194e6e..d5966d9 100644 --- a/src/common/file-history.ts +++ b/src/common/file-history.ts @@ -160,7 +160,7 @@ export class GitFileHistory { args: string[], options: { includeWorkTree: boolean; input?: string; env?: NodeJS.ProcessEnv } ): string { - const gitArgs = [`--git-dir=${this.gitDir}`]; + const gitArgs = ["-c", "core.autocrlf=false", "-c", "core.eol=lf", `--git-dir=${this.gitDir}`]; if (options.includeWorkTree) { gitArgs.push(`--work-tree=${this.projectRoot}`); } diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 3658e1c..d5191fa 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -2018,12 +2018,16 @@ function runFileHistoryGit( input = "", env: NodeJS.ProcessEnv = process.env ): string { - return execFileSync("git", [`--git-dir=${gitDir}`, `--work-tree=${workspace}`, ...args], { - encoding: "utf8", - input, - env, - stdio: ["pipe", "pipe", "pipe"], - }); + return execFileSync( + "git", + ["-c", "core.autocrlf=false", "-c", "core.eol=lf", `--git-dir=${gitDir}`, `--work-tree=${workspace}`, ...args], + { + encoding: "utf8", + input, + env, + stdio: ["pipe", "pipe", "pipe"], + } + ); } function fileHistoryCommitEnv(): NodeJS.ProcessEnv { From db6f0c6991095b194f224988e1a72d769f860483 Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 14:24:59 +0800 Subject: [PATCH 091/129] =?UTF-8?q?feat(SessionList):=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E8=BF=87=E6=BB=A4=E5=8A=9F=E8=83=BD=E5=8F=8A?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E6=A0=BC=E5=BC=8F=E5=8C=96=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增filterSessions函数支持根据关键词过滤会话,包括摘要、状态、失败原因和助手回复 - 支持搜索查询框,动态过滤并显示匹配的会话列表 - 实现格式化会话状态显示,如"completed"显示为"done" - 搜索过程中支持编辑和清除查询内容,按Esc键清除搜索或退出 - 会话列表根据搜索结果自动调整高亮和滚动 - 增强交互提示,根据搜索状态显示不同的快捷键说明 - 针对新增功能添加了大量单元测试覆盖各种匹配和边界情况 - 导出filterSessions和formatSessionStatus以供外部使用 --- src/tests/sessionList.test.ts | 108 +++++++++++++++- src/ui/SessionList.tsx | 227 ++++++++++++++++++++++++++-------- src/ui/index.ts | 2 +- 3 files changed, 280 insertions(+), 57 deletions(-) diff --git a/src/tests/sessionList.test.ts b/src/tests/sessionList.test.ts index e3bf51c..3dfda33 100644 --- a/src/tests/sessionList.test.ts +++ b/src/tests/sessionList.test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { formatSessionTitle } from "../ui"; +import { formatSessionTitle, filterSessions, formatSessionStatus } from "../ui"; +import type { SessionEntry } from "../session"; test("formatSessionTitle replaces newlines with spaces", () => { assert.equal(formatSessionTitle("first line\nsecond line\r\nthird"), "first line second line third"); @@ -9,3 +10,108 @@ test("formatSessionTitle replaces newlines with spaces", () => { test("formatSessionTitle truncates after normalizing whitespace", () => { assert.equal(formatSessionTitle("one\n two three", 10), "one two th…"); }); + +test("formatSessionStatus maps status values to display labels", () => { + assert.equal(formatSessionStatus("completed"), "done"); + assert.equal(formatSessionStatus("processing"), "running"); + assert.equal(formatSessionStatus("pending"), "pending"); + assert.equal(formatSessionStatus("waiting_for_user"), "waiting"); + assert.equal(formatSessionStatus("failed"), "failed"); + assert.equal(formatSessionStatus("interrupted"), "stopped"); + assert.equal(formatSessionStatus("unknown_status" as any), "unknown_status"); +}); + +test("filterSessions returns all sessions when query is empty", () => { + const sessions = buildSessions([{ summary: "Fix login bug" }, { summary: "Add dark mode" }]); + assert.equal(filterSessions(sessions, "").length, 2); + assert.equal(filterSessions(sessions, " ").length, 2); +}); + +test("filterSessions matches by summary (case-insensitive)", () => { + const sessions = buildSessions([ + { summary: "Fix login bug" }, + { summary: "Add dark mode" }, + { summary: "Refactor auth module" }, + ]); + + assert.equal(filterSessions(sessions, "login").length, 1); + assert.equal(filterSessions(sessions, "LOGIN").length, 1); + assert.equal(filterSessions(sessions, "Login").length, 1); +}); + +test("filterSessions matches by status (case-insensitive)", () => { + const sessions = buildSessions([ + { summary: "Task 1", status: "completed" }, + { summary: "Task 2", status: "failed" }, + { summary: "Task 3", status: "completed" }, + ]); + + assert.equal(filterSessions(sessions, "failed").length, 1); + assert.equal(filterSessions(sessions, "completed").length, 2); +}); + +test("filterSessions matches by failReason", () => { + const sessions = buildSessions([ + { summary: "Task 1", status: "failed", failReason: "API key not found" }, + { summary: "Task 2", status: "completed" }, + ]); + + assert.equal(filterSessions(sessions, "API key").length, 1); + assert.equal(filterSessions(sessions, "not found").length, 1); +}); + +test("filterSessions matches by assistantReply", () => { + const sessions = buildSessions([ + { summary: "Task 1", assistantReply: "The bug was fixed by updating the config." }, + { summary: "Task 2", assistantReply: "Dark mode has been added successfully." }, + ]); + + assert.equal(filterSessions(sessions, "dark mode").length, 1); + assert.equal(filterSessions(sessions, "config").length, 1); +}); + +test("filterSessions returns empty array when no match", () => { + const sessions = buildSessions([{ summary: "Fix login bug" }, { summary: "Add dark mode" }]); + + assert.equal(filterSessions(sessions, "nonexistent").length, 0); +}); + +test("filterSessions matches across multiple fields on same session", () => { + const sessions = buildSessions([ + { summary: "Fix login bug", status: "failed", failReason: "Timeout error" }, + { summary: "Add dark mode", status: "completed" }, + ]); + + // Should match the first session via status + assert.equal(filterSessions(sessions, "failed").length, 1); + // Should match the first session via failReason + assert.equal(filterSessions(sessions, "timeout").length, 1); + // Partial summary match + assert.equal(filterSessions(sessions, "login").length, 1); +}); + +test("filterSessions handles sessions with null fields", () => { + const sessions = buildSessions([{ summary: null }, { summary: "Valid summary" }]); + + assert.equal(filterSessions(sessions, "valid").length, 1); + assert.equal(filterSessions(sessions, "summary").length, 1); +}); + +function buildSessions(overrides: Array>): SessionEntry[] { + return overrides.map((override, i) => ({ + id: `session-${i}`, + summary: override.summary ?? null, + assistantReply: override.assistantReply ?? null, + assistantThinking: null, + assistantRefusal: null, + toolCalls: null, + status: override.status ?? "completed", + failReason: override.failReason ?? null, + usage: null, + usagePerModel: null, + activeTokens: 0, + createTime: new Date().toISOString(), + updateTime: new Date().toISOString(), + processes: null, + })); +} diff --git a/src/ui/SessionList.tsx b/src/ui/SessionList.tsx index fdbd1fe..ab3bf75 100644 --- a/src/ui/SessionList.tsx +++ b/src/ui/SessionList.tsx @@ -1,6 +1,6 @@ -import React, { useState, useMemo } from "react"; +import React, { useState, useMemo, useCallback } from "react"; import { Box, Text, useInput, useWindowSize } from "ink"; -import type { SessionEntry } from "../session"; +import type { SessionEntry, SessionStatus } from "../session"; type Props = { sessions: SessionEntry[]; @@ -8,25 +8,57 @@ type Props = { onCancel: () => void; }; +/** + * Filter sessions by a search query. + * Matches against summary, status, and failReason fields (case-insensitive). + * Returns all sessions when query is empty. + */ +export function filterSessions(sessions: SessionEntry[], query: string): SessionEntry[] { + if (!query.trim()) { + return sessions; + } + + const lowerQuery = query.toLowerCase().trim(); + return sessions.filter((session) => { + if (session.summary && session.summary.toLowerCase().includes(lowerQuery)) { + return true; + } + if (session.status.toLowerCase().includes(lowerQuery)) { + return true; + } + if (session.failReason && session.failReason.toLowerCase().includes(lowerQuery)) { + return true; + } + if (session.assistantReply && session.assistantReply.toLowerCase().includes(lowerQuery)) { + return true; + } + return false; + }); +} + export function SessionList({ sessions, onSelect, onCancel }: Props): React.ReactElement { const [index, setIndex] = useState(0); + const [searchQuery, setSearchQuery] = useState(""); const { columns, rows } = useWindowSize(); + // Filter sessions by search query + const filteredSessions = useMemo(() => filterSessions(sessions, searchQuery), [sessions, searchQuery]); + + // Reset index when filtered list changes (e.g., query changes) + const safeIndex = useMemo(() => { + if (filteredSessions.length === 0) return 0; + return Math.max(0, Math.min(index, filteredSessions.length - 1)); + }, [index, filteredSessions.length]); + // Dynamically calculate the number of visible sessions based on terminal height const maxVisibleSessions = useMemo(() => { - // Subtract space used by borders, header, footer, scroll indicator, etc. - // Outer container height=rows-1, outer border 2 + header 1 + inner border 2 + footer 1 + scroll indicator 1 = 8 - const reservedLines = 8; + // Subtract space used by borders, header (2 lines with search bar), footer, scroll indicator, etc. + // Outer container height=rows-1, outer border 2 + header 2 + search bar 1 + inner border 2 + footer 1 + scroll indicator 1 = 9 + const reservedLines = searchQuery ? 12 : 9; const linesPerSession = 3; // height=2 + marginBottom=1 const availableLines = Math.max(0, Math.min(rows, 30) - reservedLines); return Math.max(1, Math.floor(availableLines / linesPerSession)); - }, [rows]); - - // Ensure index stays within valid range - const safeIndex = useMemo(() => { - if (sessions.length === 0) return 0; - return Math.max(0, Math.min(index, sessions.length - 1)); - }, [index, sessions.length]); + }, [rows, searchQuery]); // Calculate scroll offset to keep the selected item visible const scrollOffset = useMemo(() => { @@ -36,23 +68,63 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac // Get the currently visible session list const visibleSessions = useMemo(() => { - return sessions.slice(scrollOffset, scrollOffset + maxVisibleSessions); - }, [sessions, scrollOffset, maxVisibleSessions]); + return filteredSessions.slice(scrollOffset, scrollOffset + maxVisibleSessions); + }, [filteredSessions, scrollOffset, maxVisibleSessions]); + + // Handle backspace for search query + const handleBackspace = useCallback(() => { + setSearchQuery((prev) => prev.slice(0, -1)); + setIndex(0); + }, []); useInput((input, key) => { - if (key.escape || (key.ctrl && (input === "c" || input === "C"))) { + // ESC: clear search first, then cancel + if (key.escape) { + if (searchQuery) { + setSearchQuery(""); + setIndex(0); + return; + } onCancel(); return; } - if (sessions.length === 0) { + + // Ctrl+C also cancels + if (key.ctrl && (input === "c" || input === "C")) { + onCancel(); return; } + + // Backspace / Delete: remove last search character + if (key.backspace || key.delete) { + if (searchQuery) { + handleBackspace(); + return; + } + // If no search query, navigation keys below handle the rest + } + + // Printable character: append to search query + if (input && input.length > 0 && !key.meta && !key.ctrl && !key.tab) { + // Ignore if it's a named key that happens to have input (safety check) + if (key.upArrow || key.downArrow || key.leftArrow || key.rightArrow) { + return; + } + setSearchQuery((prev) => prev + input); + setIndex(0); + return; + } + + if (filteredSessions.length === 0) { + return; + } + if (key.upArrow) { setIndex((i) => Math.max(0, i - 1)); return; } if (key.downArrow) { - setIndex((i) => Math.min(sessions.length - 1, i + 1)); + setIndex((i) => Math.min(filteredSessions.length - 1, i + 1)); return; } if (key.pageUp) { @@ -60,7 +132,7 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac return; } if (key.pageDown) { - setIndex((i) => Math.min(sessions.length - 1, i + maxVisibleSessions)); + setIndex((i) => Math.min(filteredSessions.length - 1, i + maxVisibleSessions)); return; } if (key.home) { @@ -68,17 +140,19 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac return; } if (key.end) { - setIndex(sessions.length - 1); + setIndex(filteredSessions.length - 1); return; } if (key.return) { - const session = sessions[safeIndex]; + const session = filteredSessions[safeIndex]; if (session) { onSelect(session.id); } } }); + const hasActiveSearch = searchQuery.trim().length > 0; + if (sessions.length === 0) { return ( @@ -99,15 +173,24 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac > {/* Header row */} - - - Resume a session - - - {" "} - ({sessions.length} total) - + + + + Resume a session + + + {" "} + ({sessions.length} total + {hasActiveSearch ? `, ${filteredSessions.length} matched` : ""}) + + + {/* Search bar */} + + {searchQuery ? `Search: ${searchQuery}` : "Type to search\u2026"} + {searchQuery ? | : null} + + {/* Session list */} - {visibleSessions.map((session, i) => { - const actualIndex = scrollOffset + i; - return ( - - - {actualIndex === safeIndex ? "> " : " "} - - - - - {formatSessionTitle(session.summary || "Untitled")} - - ({session.status}) + {filteredSessions.length === 0 ? ( + + No sessions match "{searchQuery}". + + ) : ( + visibleSessions.map((session, i) => { + const actualIndex = scrollOffset + i; + return ( + + + {actualIndex === safeIndex ? "> " : " "} - - {formatTimestamp(session.updateTime)} + + + + {formatSessionTitle(session.summary || "Untitled")} + + ({formatSessionStatus(session.status)}) + + + {formatTimestamp(session.updateTime)} + - - ); - })} - {scrollOffset > 0 || scrollOffset + maxVisibleSessions < sessions.length ? ( + ); + }) + )} + {scrollOffset > 0 || scrollOffset + maxVisibleSessions < filteredSessions.length ? ( - {scrollOffset > 0 ? … {scrollOffset} newer sessions above. : null} - {scrollOffset + maxVisibleSessions < sessions.length ? ( - … {sessions.length - scrollOffset - maxVisibleSessions} older sessions below. + {scrollOffset > 0 ? … {scrollOffset} sessions above. : null} + {scrollOffset + maxVisibleSessions < filteredSessions.length ? ( + … {filteredSessions.length - scrollOffset - maxVisibleSessions} sessions below. ) : null} ) : null} {/* Footer */} - - ↑/↓ navigate · PgUp/PgDn page · Enter select · Esc cancel + + {hasActiveSearch ? ( + + Esc clear search · + ↑/↓ navigate · Enter select · Esc again to cancel + + ) : ( + + Type to search · ↑/↓ navigate · PgUp/PgDn page · Enter select · Esc cancel + + )} @@ -179,6 +277,25 @@ export function formatSessionTitle(value: string, max = 70): string { return truncate(value.replace(/\r?\n/g, " ").replace(/\s+/g, " ").trim(), max); } +export function formatSessionStatus(status: SessionStatus): string { + switch (status) { + case "completed": + return "done"; + case "processing": + return "running"; + case "pending": + return "pending"; + case "waiting_for_user": + return "waiting"; + case "failed": + return "failed"; + case "interrupted": + return "stopped"; + default: + return status; + } +} + function truncate(value: string, max: number): string { if (value.length <= max) { return value; diff --git a/src/ui/index.ts b/src/ui/index.ts index efb4edd..f639c65 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -37,7 +37,7 @@ export { } from "./PromptInput"; export { getThinkingOptionIndex, MODEL_COMMAND_MODELS, MODEL_COMMAND_THINKING_OPTIONS }; export { disableTerminalExtendedKeys, enableTerminalExtendedKeys, getPromptCursorPlacement } from "./prompt/cursor"; -export { SessionList, formatSessionTitle } from "./SessionList"; +export { SessionList, formatSessionTitle, filterSessions, formatSessionStatus } from "./SessionList"; export { ThemedGradient } from "./ThemedGradient"; export { UpdatePrompt, type UpdatePromptChoice } from "./UpdatePrompt"; export { WelcomeScreen, formatHomeRelativePath, buildWelcomeTips } from "./WelcomeScreen"; From 208a9886196c404dd00c052a4bcc45e4a1ed4a0c Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 14:38:00 +0800 Subject: [PATCH 092/129] =?UTF-8?q?fix(ui):=20=E4=BF=AE=E5=A4=8D=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=9F=A5=E8=AF=A2=E4=B8=AD=E5=9B=9E=E8=BD=A6=E9=94=AE?= =?UTF-8?q?=E7=9A=84=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在处理搜索输入时忽略回车键,避免错误触发搜索操作 - 增加对回车键的判断,提升输入处理的准确性 - 防止命名键在输入查询时误触发逻辑分支 --- src/ui/SessionList.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/SessionList.tsx b/src/ui/SessionList.tsx index ab3bf75..5f186bd 100644 --- a/src/ui/SessionList.tsx +++ b/src/ui/SessionList.tsx @@ -105,7 +105,7 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac } // Printable character: append to search query - if (input && input.length > 0 && !key.meta && !key.ctrl && !key.tab) { + if (input && input.length > 0 && !key.meta && !key.ctrl && !key.tab && !key.return) { // Ignore if it's a named key that happens to have input (safety check) if (key.upArrow || key.downArrow || key.leftArrow || key.rightArrow) { return; From 585fe5ff442b0dcbfeb6a68a959c68badb386fcd Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 14:48:05 +0800 Subject: [PATCH 093/129] merge(branch): 'main' into refactor/extract-dropdown-components --- src/ui/PromptInput.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 24aa076..7008cba 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -238,7 +238,6 @@ export const PromptInput = React.memo(function PromptInput({ setSelectedSkills([]); setShowSkillsDropdown(false); setOpenRawModelDropdown(false); - setModelDropdownStep(null); setHistoryCursor(-1); setDraftBeforeHistory(null); clearPromptUndoRedoState(undoRedoRef.current); From 3c15003454ce743a2577fbaa278579c88e675fb6 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Wed, 20 May 2026 14:53:10 +0800 Subject: [PATCH 094/129] refactor: extracted terminal data dispatch into `dispatchTerminalInput()` --- src/tests/promptInputKeys.test.ts | 51 +++++++++++++++++++++++++++ src/ui/PromptInput.tsx | 2 +- src/ui/index.ts | 1 + src/ui/prompt/index.ts | 2 +- src/ui/prompt/useTerminalInput.ts | 58 +++++++++++++++++-------------- 5 files changed, 86 insertions(+), 28 deletions(-) diff --git a/src/tests/promptInputKeys.test.ts b/src/tests/promptInputKeys.test.ts index 54213a1..4f8b4d9 100644 --- a/src/tests/promptInputKeys.test.ts +++ b/src/tests/promptInputKeys.test.ts @@ -20,11 +20,23 @@ import { renderBufferWithCursor, buildInitPromptSubmission, buildPromptDraftFromSessionMessage, + dispatchTerminalInput, disableTerminalExtendedKeys, enableTerminalExtendedKeys, + EMPTY_BUFFER, + insertText, + backspace, } from "../ui"; import type { SessionMessage, SkillInfo } from "../session"; +function collectDispatchedInput(data: string) { + const events: ReturnType[] = []; + dispatchTerminalInput(data, (input, key) => { + events.push({ input, key }); + }); + return events; +} + test("parseTerminalInput treats DEL bytes as backspace", () => { const { input, key } = parseTerminalInput("\u007F"); assert.equal(input, ""); @@ -72,6 +84,45 @@ test("parseTerminalInput keeps DEL payload for meta+backspace", () => { assert.equal(key.backspace, false); }); +test("dispatchTerminalInput splits iOS CJK composition packets", () => { + const events = collectDispatchedInput("가\u007F나"); + assert.equal(events.length, 3); + assert.equal(events[0]?.input, "가"); + assert.equal(events[1]?.input, ""); + assert.equal(events[1]?.key.backspace, true); + assert.equal(events[2]?.input, "나"); +}); + +test("dispatchTerminalInput applies multi-step CJK composition to the prompt buffer", () => { + let state = EMPTY_BUFFER; + dispatchTerminalInput("ㄱ\u007F가\u007F각", (input, key) => { + if (key.backspace) { + state = backspace(state); + return; + } + state = insertText(state, input); + }); + + assert.equal(state.text, "각"); + assert.equal(state.cursor, 1); +}); + +test("dispatchTerminalInput preserves meta+backspace as one event", () => { + const events = collectDispatchedInput("\u001B\u007F"); + assert.equal(events.length, 1); + assert.equal(events[0]?.input, "\u007F"); + assert.equal(events[0]?.key.meta, true); + assert.equal(events[0]?.key.backspace, false); + assert.equal(events[0]?.key.escape, false); +}); + +test("dispatchTerminalInput emits consecutive backspaces from one packet", () => { + const events = collectDispatchedInput("\u007F\u007F"); + assert.equal(events.length, 2); + assert.equal(events[0]?.key.backspace, true); + assert.equal(events[1]?.key.backspace, true); +}); + test("parseTerminalInput keeps BS payload for meta+backspace", () => { const { input, key } = parseTerminalInput("\u001B\b"); assert.equal(input, "\b"); diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 6767560..3cb51f2 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -42,7 +42,7 @@ import { readClipboardImageAsync } from "./clipboard"; import type { SessionEntry, SkillInfo } from "../session"; // Re-exported from prompt modules for backward compatibility -export { useTerminalInput, parseTerminalInput } from "./prompt"; +export { useTerminalInput, parseTerminalInput, dispatchTerminalInput } from "./prompt"; export type { InputKey } from "./prompt"; import { useTerminalInput } from "./prompt"; diff --git a/src/ui/index.ts b/src/ui/index.ts index 7c0ed15..681d77c 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -30,6 +30,7 @@ export { MODEL_COMMAND_THINKING_OPTIONS, useTerminalInput, parseTerminalInput, + dispatchTerminalInput, type PromptSubmission, type PromptDraft, type InputKey, diff --git a/src/ui/prompt/index.ts b/src/ui/prompt/index.ts index a33172c..5907558 100644 --- a/src/ui/prompt/index.ts +++ b/src/ui/prompt/index.ts @@ -1,4 +1,4 @@ -export { useTerminalInput, parseTerminalInput } from "./useTerminalInput"; +export { useTerminalInput, parseTerminalInput, dispatchTerminalInput } from "./useTerminalInput"; export type { InputKey } from "./useTerminalInput"; export { diff --git a/src/ui/prompt/useTerminalInput.ts b/src/ui/prompt/useTerminalInput.ts index 8fe0d60..9ce6976 100644 --- a/src/ui/prompt/useTerminalInput.ts +++ b/src/ui/prompt/useTerminalInput.ts @@ -169,6 +169,37 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: return { input, key }; } +export function dispatchTerminalInput( + data: Buffer | string, + inputHandler: (input: string, key: InputKey) => void +): void { + const raw = String(data); + + // Fix CJK composition bug on iOS terminals (Moshi, Blink, etc.). + // iOS keyboards can send composed characters as a single packet like: + // "가\x7f나" (character + backspace + replacement character) + // Do not split escape-prefixed sequences such as Alt+Backspace. + if (!raw.startsWith("\u001B") && raw.includes("\x7f") && raw.length > 1) { + const parts = raw.split("\x7f"); + if (parts[0]) { + const { input, key } = parseTerminalInput(parts[0]); + inputHandler(input, key); + } + for (let i = 1; i < parts.length; i++) { + const bs = parseTerminalInput("\x7f"); + inputHandler(bs.input, bs.key); + if (parts[i]) { + const { input, key } = parseTerminalInput(parts[i]); + inputHandler(input, key); + } + } + return; + } + + const { input, key } = parseTerminalInput(data); + inputHandler(input, key); +} + export function useTerminalInput( inputHandler: (input: string, key: InputKey) => void, options: { isActive?: boolean } = {} @@ -193,32 +224,7 @@ export function useTerminalInput( return; } const handleData = (data: Buffer | string) => { - const raw = String(data); - - // Fix CJK composition bug on iOS terminals (Moshi, Blink, etc.). - // iOS keyboards send composed characters as a single packet like: - // "가\x7f나" (character + backspace + new character) - // Without splitting, parseTerminalInput treats the whole packet as - // one input and drops the composition backspaces, corrupting the text. - if (raw.includes("\x7f") && raw.length > 1) { - const parts = raw.split("\x7f"); - if (parts[0]) { - const { input, key } = parseTerminalInput(parts[0]); - handlerRef.current(input, key); - } - for (let i = 1; i < parts.length; i++) { - const bs = parseTerminalInput("\x7f"); - handlerRef.current(bs.input, bs.key); - if (parts[i]) { - const { input, key } = parseTerminalInput(parts[i]); - handlerRef.current(input, key); - } - } - return; - } - - const { input, key } = parseTerminalInput(data); - handlerRef.current(input, key); + dispatchTerminalInput(data, handlerRef.current); }; stdin?.on("data", handleData); From abde38cc76be4cd1836d04713d2f51cca294d11b Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Wed, 20 May 2026 15:40:35 +0800 Subject: [PATCH 095/129] feat: refresh cached MCP tool definitions after server crash --- src/mcp/mcp-manager.ts | 1 + src/tests/session.test.ts | 64 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/src/mcp/mcp-manager.ts b/src/mcp/mcp-manager.ts index 217e3fc..fe8066b 100644 --- a/src/mcp/mcp-manager.ts +++ b/src/mcp/mcp-manager.ts @@ -236,6 +236,7 @@ export class McpManager { this.tools = this.tools.filter((t) => t.serverName !== name); this.prompts = this.prompts.filter((p) => p.serverName !== name); this.resources = this.resources.filter((r) => r.serverName !== name); + this.onToolsListChanged?.(); this.setStatus({ name, status: "failed", diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 27b504e..9f3c7fb 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -482,6 +482,60 @@ rl.on("line", (line) => { assert.deepEqual(manager.getMcpStatus(), []); }); +test("SessionManager refreshes cached MCP tool definitions after server crash", async () => { + const workspace = createTempDir("deepcode-mcp-crash-cache-workspace-"); + const serverPath = path.join(workspace, "mcp-server-crash.cjs"); + fs.writeFileSync( + serverPath, + ` +const readline = require("readline"); +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +function send(message) { + process.stdout.write(JSON.stringify(message) + "\\n"); +} +rl.on("line", (line) => { + const request = JSON.parse(line); + if (!("id" in request)) { + return; + } + if (request.method === "initialize") { + send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} } } }); + return; + } + if (request.method === "tools/list") { + send({ jsonrpc: "2.0", id: request.id, result: { tools: [ + { name: "echo", inputSchema: { type: "object", properties: {} } } + ] } }); + return; + } + if (request.method === "prompts/list") { + send({ jsonrpc: "2.0", id: request.id, result: { prompts: [] } }); + return; + } + if (request.method === "resources/list") { + send({ jsonrpc: "2.0", id: request.id, result: { resources: [] } }); + setTimeout(() => process.exit(9), 10); + return; + } + send({ jsonrpc: "2.0", id: request.id, result: { content: [] } }); +}); +`, + "utf8" + ); + + const manager = createSessionManager(workspace, "machine-id-mcp-crash-cache"); + await manager.initMcpServers({ crashy: { command: process.execPath, args: [serverPath] } }); + + assert.equal(manager.getMcpStatus()[0]?.status, "ready"); + assert.equal((manager as any).mcpToolDefinitions.length, 1); + + await waitForMcpStatus(manager, "failed"); + + assert.equal((manager as any).mcpToolDefinitions.length, 0); + + manager.dispose(); +}); + test("SessionManager reports configured MCP servers as starting before initialization", () => { const workspace = createTempDir("deepcode-mcp-configured-workspace-"); const manager = new SessionManager({ @@ -2276,6 +2330,16 @@ async function waitForNotifyRecords( assert.fail(`expected ${expectedCount} notify records in ${outputPath}`); } +async function waitForMcpStatus(manager: SessionManager, expectedStatus: string): Promise { + for (let attempt = 0; attempt < 100; attempt += 1) { + if (manager.getMcpStatus()[0]?.status === expectedStatus) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } + assert.fail(`expected MCP status ${expectedStatus}`); +} + function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } From b757ea191993207f2fe7761bf58730e111eec01a Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 16:51:07 +0800 Subject: [PATCH 096/129] =?UTF-8?q?refactor(ui):=20=E7=A7=BB=E5=8A=A8?= =?UTF-8?q?=E5=B9=B6=E5=A4=8D=E7=94=A8=20isSkillSelected=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 isSkillSelected 函数从 PromptInput.tsx 移动到 SlashCommandMenu.tsx - 在 PromptInput.tsx 中从 SlashCommandMenu 导入 isSkillSelected - 简化代码结构,避免函数重复定义 - 统一技能选择判断逻辑以提高代码复用性 --- src/ui/PromptInput.tsx | 6 +----- src/ui/SlashCommandMenu.tsx | 5 ++++- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 5e2c2b5..074cab6 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -48,7 +48,7 @@ export type { InputKey } from "./prompt"; import { useTerminalInput } from "./prompt"; import type { InputKey } from "./prompt"; import { useHiddenTerminalCursor, useTerminalExtendedKeys, useTerminalFocusReporting } from "./prompt"; -import SlashCommandMenu from "./SlashCommandMenu"; +import SlashCommandMenu, { isSkillSelected } from "./SlashCommandMenu"; import type { ModelConfigSelection } from "../settings"; import { FileMentionMenu, ModelsDropdown, RawModelDropdown, SkillsDropdown } from "./components"; @@ -818,10 +818,6 @@ export function formatSelectedSkillsStatus(skills: SkillInfo[]): string { return `⚡ ${names.join(", ")}`; } -export function isSkillSelected(skills: SkillInfo[], skill: SkillInfo): boolean { - return skills.some((item) => item.name === skill.name); -} - export function addUniqueSkill(skills: SkillInfo[], skill: SkillInfo): SkillInfo[] { if (isSkillSelected(skills, skill)) { return skills; diff --git a/src/ui/SlashCommandMenu.tsx b/src/ui/SlashCommandMenu.tsx index 02ff308..df599b5 100644 --- a/src/ui/SlashCommandMenu.tsx +++ b/src/ui/SlashCommandMenu.tsx @@ -3,6 +3,7 @@ import type { SlashCommandItem } from "./slashCommands"; import { ARGS_SEPARATOR } from "./constants"; import React from "react"; import { Box, Text } from "ink"; +import type { SkillInfo } from "../session"; type SlashCommandMenuProps = { items: SlashCommandItem[]; @@ -10,7 +11,9 @@ type SlashCommandMenuProps = { width: number; maxVisible?: number; }; - +export function isSkillSelected(skills: SkillInfo[], skill: SkillInfo): boolean { + return skills.some((item) => item.name === skill.name); +} const SlashCommandMenu = React.memo(function SlashCommandMenu({ items, activeIndex, From e0bde604fb220b63b8b43b17a72cf3b5ea0934fd Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 17:00:45 +0800 Subject: [PATCH 097/129] =?UTF-8?q?refactor(ui):=20=E7=A7=BB=E5=8A=A8?= =?UTF-8?q?=E5=B9=B6=E5=A4=8D=E7=94=A8=20isSkillSelected=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 isSkillSelected 函数从 PromptInput.tsx 移动到 SlashCommandMenu.tsx - 在 PromptInput.tsx 中从 SlashCommandMenu 导入 isSkillSelected - 简化代码结构,避免函数重复定义 - 统一技能选择判断逻辑以提高代码复用性 --- src/ui/components/SkillsDropdown/index.tsx | 2 +- src/ui/index.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/ui/components/SkillsDropdown/index.tsx b/src/ui/components/SkillsDropdown/index.tsx index 545e2ab..b320d24 100644 --- a/src/ui/components/SkillsDropdown/index.tsx +++ b/src/ui/components/SkillsDropdown/index.tsx @@ -1,8 +1,8 @@ import DropdownMenu from "../../DropdownMenu"; import React, { useEffect, useState } from "react"; -import { isSkillSelected } from "../../PromptInput"; import type { SkillInfo } from "../../../session"; import { useInput } from "ink"; +import { isSkillSelected } from "../../SlashCommandMenu"; const SkillsDropdown: React.FC<{ open: boolean; diff --git a/src/ui/index.ts b/src/ui/index.ts index d634ed6..26e7eaa 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -23,7 +23,6 @@ export { IMAGE_ATTACHMENT_CLEAR_HINT, formatImageAttachmentStatus, formatSelectedSkillsStatus, - isSkillSelected, addUniqueSkill, toggleSkillSelection, removeCurrentSlashToken, From b2544b831252c5d58f15cbfa6b5c7c04e1a1aa8f Mon Sep 17 00:00:00 2001 From: lellansin Date: Wed, 20 May 2026 17:36:41 +0800 Subject: [PATCH 098/129] perf: reuse OpenAI client and add undici keep-alive Agent with connection warmup Extract OpenAI client creation logic into src/common/openai-client.ts: - Custom undici Agent with 60s keepAlive timeout (default is 4s) - Module-level client instance cache (reuse across calls) - Fire-and-forget connection warmup on first creation (3s timeout) - getMachineId() helper The App.tsx now simply imports and re-exports createOpenAIClient from the new common module, keeping UI concerns separate from HTTP/client lifecycle management. --- package-lock.json | 10 +++ package.json | 1 + src/common/openai-client.ts | 117 ++++++++++++++++++++++++++++++++++++ src/ui/App.tsx | 73 +++------------------- src/ui/index.ts | 2 +- 5 files changed, 138 insertions(+), 65 deletions(-) create mode 100644 src/common/openai-client.ts diff --git a/package-lock.json b/package-lock.json index 17a77ca..cdb85de 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,7 @@ "ink-gradient": "^4.0.0", "openai": "^6.35.0", "react": "^19.2.5", + "undici": "^7.25.0", "zod": "^4.4.3" }, "bin": { @@ -4096,6 +4097,15 @@ "typescript": ">=4.8.4 <6.1.0" } }, + "node_modules/undici": { + "version": "7.25.0", + "resolved": "https://registry.npmmirror.com/undici/-/undici-7.25.0.tgz", + "integrity": "sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/undici-types": { "version": "7.19.2", "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.19.2.tgz", diff --git a/package.json b/package.json index b72fd96..bf8d167 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "ink-gradient": "^4.0.0", "openai": "^6.35.0", "react": "^19.2.5", + "undici": "^7.25.0", "zod": "^4.4.3" }, "devDependencies": { diff --git a/src/common/openai-client.ts b/src/common/openai-client.ts new file mode 100644 index 0000000..7f9634c --- /dev/null +++ b/src/common/openai-client.ts @@ -0,0 +1,117 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import OpenAI from "openai"; +import { Agent, fetch as undiciFetch } from "undici"; +import { resolveCurrentSettings } from "../ui/App"; + +// Custom undici Agent with a 60-second keepAlive timeout. The default +// global fetch (undici) only keeps connections alive for 4 seconds, which +// is too short for a CLI where the user may spend 10–30 seconds reading +// output between prompts. By passing a dedicated Agent to undiciFetch we +// keep connections reusable for a full minute after the last request. +const keepAliveAgent = new Agent({ keepAliveTimeout: 60_000 }); + +// Module-level cache for the OpenAI client instance. The client itself is +// a stateless fetch wrapper, so it is safe to share across calls as long as +// the apiKey + baseURL stay the same. Model, thinking-mode and other +// settings are always read fresh from the project / user config files. +let cachedOpenAI: OpenAI | null = null; +let cachedOpenAIKey = ""; + +export function createOpenAIClient(projectRoot: string = process.cwd()): { + client: OpenAI | null; + model: string; + baseURL: string; + thinkingEnabled: boolean; + reasoningEffort: "high" | "max"; + debugLogEnabled: boolean; + notify?: string; + webSearchTool?: string; + env: Record; + machineId?: string; +} { + const settings = resolveCurrentSettings(projectRoot); + if (!settings.apiKey) { + return { + client: null, + model: settings.model, + baseURL: settings.baseURL, + thinkingEnabled: settings.thinkingEnabled, + reasoningEffort: settings.reasoningEffort, + debugLogEnabled: settings.debugLogEnabled, + notify: settings.notify, + webSearchTool: settings.webSearchTool, + env: settings.env, + machineId: getMachineId(), + }; + } + + const cacheKey = `${settings.apiKey}::${settings.baseURL}`; + if (cachedOpenAI && cachedOpenAIKey === cacheKey) { + return { + client: cachedOpenAI, + model: settings.model, + baseURL: settings.baseURL, + thinkingEnabled: settings.thinkingEnabled, + reasoningEffort: settings.reasoningEffort, + debugLogEnabled: settings.debugLogEnabled, + notify: settings.notify, + webSearchTool: settings.webSearchTool, + env: settings.env, + machineId: getMachineId(), + }; + } + + cachedOpenAI = new OpenAI({ + apiKey: settings.apiKey, + baseURL: settings.baseURL || undefined, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + fetch: (url: any, init: any) => undiciFetch(url, { ...init, dispatcher: keepAliveAgent }), + }); + cachedOpenAIKey = cacheKey; + + // Fire-and-forget warmup: pre-establish TCP+TLS connection to the API + // server while the user is composing their first prompt. Bounded by a + // short timeout so a slow / unreachable API never blocks process exit. + void (async () => { + const ac = new AbortController(); + const timer = setTimeout(() => ac.abort(), 3000); + try { + await cachedOpenAI.models.list({ signal: ac.signal }).catch(() => {}); + } finally { + clearTimeout(timer); + } + })(); + + return { + client: cachedOpenAI, + model: settings.model, + baseURL: settings.baseURL, + thinkingEnabled: settings.thinkingEnabled, + reasoningEffort: settings.reasoningEffort, + debugLogEnabled: settings.debugLogEnabled, + notify: settings.notify, + webSearchTool: settings.webSearchTool, + env: settings.env, + machineId: getMachineId(), + }; +} + +function getMachineId(): string | undefined { + try { + const idPath = path.join(os.homedir(), ".deepcode", "machine-id"); + if (fs.existsSync(idPath)) { + const raw = fs.readFileSync(idPath, "utf8").trim(); + if (raw) { + return raw; + } + } + const generated = `${os.hostname()}-${Math.random().toString(36).slice(2)}-${Date.now()}`; + fs.mkdirSync(path.dirname(idPath), { recursive: true }); + fs.writeFileSync(idPath, generated, "utf8"); + return generated; + } catch { + return undefined; + } +} diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 75d6689..5419a2a 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -4,7 +4,7 @@ import chalk from "chalk"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; -import OpenAI from "openai"; +import { createOpenAIClient } from "../common/openai-client"; import { type LlmStreamProgress, type MessageMeta, @@ -166,6 +166,13 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. void refreshSkills(); }, [refreshSessionsList, refreshSkills]); + // Eagerly create the OpenAI client on mount so the TCP+TLS connection + // warmup (fire-and-forget inside createOpenAIClient) starts before the + // user sends their first prompt. + useEffect(() => { + createOpenAIClient(projectRoot); + }, [projectRoot]); + useLayoutEffect(() => { const settings = resolveCurrentSettings(projectRoot); void sessionManager.initMcpServers(settings.mcpServers); @@ -838,69 +845,7 @@ export function resolveCurrentSettings(projectRoot: string = process.cwd()): Res ); } -export function createOpenAIClient(projectRoot: string = process.cwd()): { - client: OpenAI | null; - model: string; - baseURL: string; - thinkingEnabled: boolean; - reasoningEffort: "high" | "max"; - debugLogEnabled: boolean; - notify?: string; - webSearchTool?: string; - env: Record; - machineId?: string; -} { - const settings = resolveCurrentSettings(projectRoot); - if (!settings.apiKey) { - return { - client: null, - model: settings.model, - baseURL: settings.baseURL, - thinkingEnabled: settings.thinkingEnabled, - reasoningEffort: settings.reasoningEffort, - debugLogEnabled: settings.debugLogEnabled, - notify: settings.notify, - webSearchTool: settings.webSearchTool, - env: settings.env, - machineId: getMachineId(), - }; - } - - const client = new OpenAI({ - apiKey: settings.apiKey, - baseURL: settings.baseURL || undefined, - }); - return { - client, - model: settings.model, - baseURL: settings.baseURL, - thinkingEnabled: settings.thinkingEnabled, - reasoningEffort: settings.reasoningEffort, - debugLogEnabled: settings.debugLogEnabled, - notify: settings.notify, - webSearchTool: settings.webSearchTool, - env: settings.env, - machineId: getMachineId(), - }; -} - -function getMachineId(): string | undefined { - try { - const idPath = path.join(os.homedir(), ".deepcode", "machine-id"); - if (fs.existsSync(idPath)) { - const raw = fs.readFileSync(idPath, "utf8").trim(); - if (raw) { - return raw; - } - } - const generated = `${os.hostname()}-${Math.random().toString(36).slice(2)}-${Date.now()}`; - fs.mkdirSync(path.dirname(idPath), { recursive: true }); - fs.writeFileSync(idPath, generated, "utf8"); - return generated; - } catch { - return undefined; - } -} +export { createOpenAIClient } from "../common/openai-client"; function getUserSettingsPath(): string { return path.join(os.homedir(), ".deepcode", "settings.json"); diff --git a/src/ui/index.ts b/src/ui/index.ts index 26e7eaa..d899d4b 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -11,9 +11,9 @@ export { writeProjectSettings, writeModelConfigSelection, resolveCurrentSettings, - createOpenAIClient, buildPromptDraftFromSessionMessage, } from "./App"; +export { createOpenAIClient } from "../common/openai-client"; export { default as AppContainer } from "./AppContainer"; export { AskUserQuestionPrompt } from "./AskUserQuestionPrompt"; export { MessageView } from "./components"; From 7578c324639fccdccee32870b193111aaeff3183 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Wed, 20 May 2026 18:12:54 +0800 Subject: [PATCH 099/129] feat: add built-in tool alias mapping --- src/tests/tool-executor.test.ts | 41 +++++++++++++++++++++++++++++++++ src/tools/executor.ts | 10 +++++++- 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 src/tests/tool-executor.test.ts diff --git a/src/tests/tool-executor.test.ts b/src/tests/tool-executor.test.ts new file mode 100644 index 0000000..f7def2f --- /dev/null +++ b/src/tests/tool-executor.test.ts @@ -0,0 +1,41 @@ +import { afterEach, test } from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { ToolExecutor } from "../tools/executor"; + +const tempDirs: string[] = []; + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) { + fs.rmSync(dir, { recursive: true, force: true }); + } + } +}); + +test("ToolExecutor accepts title-case built-in tool aliases", async () => { + const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-tool-executor-")); + tempDirs.push(workspace); + const filePath = path.join(workspace, "sample.txt"); + fs.writeFileSync(filePath, "alpha\nbeta\n", "utf8"); + + const executor = new ToolExecutor(workspace); + const executions = await executor.executeToolCalls("alias-session", [ + { + id: "call-read", + type: "function", + function: { + name: "Read", + arguments: JSON.stringify({ file_path: filePath }) + } + } + ]); + + assert.equal(executions.length, 1); + assert.equal(executions[0]?.result.ok, true); + assert.equal(executions[0]?.result.name, "read"); + assert.match(executions[0]?.result.output ?? "", /alpha/); +}); diff --git a/src/tools/executor.ts b/src/tools/executor.ts index 73e31f5..edfca6f 100644 --- a/src/tools/executor.ts +++ b/src/tools/executor.ts @@ -89,6 +89,13 @@ export type ToolHandler = ( context: ToolExecutionContext ) => Promise; +const BUILT_IN_TOOL_NAME_ALIASES = new Map([ + ["Bash", "bash"], + ["Read", "read"], + ["Write", "write"], + ["Edit", "edit"] +]); + export type ToolCallExecution = { toolCallId: string; content: string; @@ -187,7 +194,8 @@ export class ToolExecutor { hooks?: ToolExecutionHooks ): Promise { const toolName = toolCall.function.name; - const handler = this.toolHandlers.get(toolName); + const handlerName = BUILT_IN_TOOL_NAME_ALIASES.get(toolName) ?? toolName; + const handler = this.toolHandlers.get(handlerName); if (!handler) { // Try MCP tools if (this.mcpManager?.isMcpTool(toolName)) { From e424e187cfb1ecaa07f2673138464e303fa7e699 Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 21:30:49 +0800 Subject: [PATCH 100/129] =?UTF-8?q?refactor(ui):=20=E4=BD=BF=E7=94=A8=20re?= =?UTF-8?q?setPromptInput=20=E7=AE=80=E5=8C=96=E6=92=A4=E9=94=80=E5=92=8C?= =?UTF-8?q?=E5=9B=9E=E7=BB=95=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 替换手动状态重置为调用 resetPromptInput 函数 - 简化代码提高可读性和维护性 - 保持撤销(undo)和回绕(rewind)命令处理逻辑一致 - 移除重复的状态重置代码块 --- src/ui/PromptInput.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 074cab6..d2af534 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -659,11 +659,7 @@ export const PromptInput = React.memo(function PromptInput({ } if (item.kind === "undo") { onSubmit({ text: "/undo", imageUrls: [], command: "undo" }); - setBuffer(EMPTY_BUFFER); - clearUndoRedoStacks(); - setImageUrls([]); - setSelectedSkills([]); - setShowSkillsDropdown(false); + resetPromptInput(); return; } if (item.kind === "mcp") { From a858684cf1d246d597552f0f16dc65bdedde422d Mon Sep 17 00:00:00 2001 From: hcyang Date: Wed, 20 May 2026 21:36:50 +0800 Subject: [PATCH 101/129] =?UTF-8?q?fix(executor):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F=E4=B8=8E=E8=AF=AD=E6=B3=95?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在工具类型列表的最后一项添加缺失的逗号 - 修正测试用例中 JSON 对象的格式错误 - 确保工具调用参数语法规范合理 - 修复断言前的代码缩进问题 --- src/tests/tool-executor.test.ts | 6 +++--- src/tools/executor.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tests/tool-executor.test.ts b/src/tests/tool-executor.test.ts index f7def2f..f36def2 100644 --- a/src/tests/tool-executor.test.ts +++ b/src/tests/tool-executor.test.ts @@ -29,9 +29,9 @@ test("ToolExecutor accepts title-case built-in tool aliases", async () => { type: "function", function: { name: "Read", - arguments: JSON.stringify({ file_path: filePath }) - } - } + arguments: JSON.stringify({ file_path: filePath }), + }, + }, ]); assert.equal(executions.length, 1); diff --git a/src/tools/executor.ts b/src/tools/executor.ts index edfca6f..220fc89 100644 --- a/src/tools/executor.ts +++ b/src/tools/executor.ts @@ -93,7 +93,7 @@ const BUILT_IN_TOOL_NAME_ALIASES = new Map([ ["Bash", "bash"], ["Read", "read"], ["Write", "write"], - ["Edit", "edit"] + ["Edit", "edit"], ]); export type ToolCallExecution = { From 3a8041faa173f09fac437318f15cfefb4d9c2f78 Mon Sep 17 00:00:00 2001 From: Kayro Date: Wed, 20 May 2026 21:30:27 +0800 Subject: [PATCH 102/129] feat(ui): add bracketed paste detection with large-paste marker collapsing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Detect bracketed paste (ESC[200~ / ESC[201~) and dispatch as atomic paste event - Large pastes (>10 lines or >1000 chars) are stored and replaced with a compact marker [paste #N] - Ctrl+O toggles expand/collapse, backspace/delete atomically remove the entire marker - Markers are highlighted with chalk.yellow and expanded back on submit - Follows existing terminal hook patterns (useBracketedPaste alongside useTerminalExtendedKeys) - Array-based chunk buffering to avoid O(n²) string concatenation on multi-chunk pastes - Lazy text cleaning deferred to expand/submit time Known limitation: expand/collapse briefly clears Ink content above the prompt (React render pipeline constraint). Reference: PR #45 (closed), inspired by pi project's paste marker approach. --- src/ui/PromptInput.tsx | 234 ++++++++++++++++++++++++++++-- src/ui/prompt/cursor.ts | 21 +++ src/ui/prompt/index.ts | 1 + src/ui/prompt/useTerminalInput.ts | 110 ++++++++++++++ src/ui/promptBuffer.ts | 114 +++++++++++++++ 5 files changed, 465 insertions(+), 15 deletions(-) diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 074cab6..ad73d83 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -4,11 +4,18 @@ import chalk from "chalk"; import { ARGS_SEPARATOR } from "./constants"; import { EMPTY_BUFFER, + PASTE_MARKER_REGEX, backspace, + cleanPasteContent, deleteForward, + deletePasteMarkerBackward, + deletePasteMarkerForward, deleteWordBefore, deleteWordAfter, + expandPasteMarkers, + findPasteMarkerContaining, getCurrentSlashToken, + hasActivePasteMarkers, insertText, isEmpty, killLine, @@ -47,7 +54,12 @@ export type { InputKey } from "./prompt"; import { useTerminalInput } from "./prompt"; import type { InputKey } from "./prompt"; -import { useHiddenTerminalCursor, useTerminalExtendedKeys, useTerminalFocusReporting } from "./prompt"; +import { + useHiddenTerminalCursor, + useTerminalExtendedKeys, + useBracketedPaste, + useTerminalFocusReporting, +} from "./prompt"; import SlashCommandMenu, { isSkillSelected } from "./SlashCommandMenu"; import type { ModelConfigSelection } from "../settings"; import { FileMentionMenu, ModelsDropdown, RawModelDropdown, SkillsDropdown } from "./components"; @@ -143,6 +155,12 @@ export const PromptInput = React.memo(function PromptInput({ const wasBusyRef = React.useRef(busy); const hadFileMentionTokenRef = React.useRef(false); const appliedDraftNonceRef = React.useRef(null); + const pastesRef = React.useRef>(new Map()); + const pasteCounterRef = React.useRef(0); + // Track expanded paste regions for toggle (Ctrl+O expand / collapse). + const expandedRegionsRef = React.useRef>( + new Map() + ); const fileMentionToken = getCurrentFileMentionToken(buffer); const hasFileMentionToken = fileMentionToken !== null; @@ -170,16 +188,25 @@ export const PromptInput = React.memo(function PromptInput({ const showMenu = slashMenu.length > 0; const promptHistoryKey = React.useMemo(() => promptHistory.join("\0"), [promptHistory]); const hasRunningProcess = runningProcesses && runningProcesses.size > 0; - const processHint = hasRunningProcess ? " · ctrl+o view output" : ""; + const hasCollapsedMarkers = hasActivePasteMarkers(buffer.text); + const hasExpandedRegions = expandedRegionsRef.current.size > 0; + const processOrPasteHint = hasRunningProcess + ? " · ctrl+o view output" + : hasCollapsedMarkers + ? " · ctrl+o expand" + : hasExpandedRegions + ? " · ctrl+o collapse" + : ""; const footerText = statusMessage ? statusMessage : busy ? loadingText && loadingText.trim() - ? `${loadingText}${processHint}` - : `esc to interrupt · ctrl+c to cancel input${processHint}` - : `enter send · shift+enter newline · @ files · ctrl+v image · / commands · ctrl+d exit${processHint}`; + ? `${loadingText}${processOrPasteHint}` + : `esc to interrupt · ctrl+c to cancel input${processOrPasteHint}` + : `enter send · shift+enter newline · @ files · ctrl+v image · / commands · ctrl+d exit${processOrPasteHint}`; useTerminalFocusReporting(stdout, !disabled); useTerminalExtendedKeys(stdout, !disabled); + useBracketedPaste(stdout, !disabled); useHiddenTerminalCursor(stdout, !disabled); const refreshFileMentionItems = React.useCallback(() => { @@ -241,6 +268,8 @@ export const PromptInput = React.memo(function PromptInput({ setHistoryCursor(-1); setDraftBeforeHistory(null); clearPromptUndoRedoState(undoRedoRef.current); + pastesRef.current.clear(); + expandedRegionsRef.current.clear(); }, [promptDraft]); useEffect(() => { @@ -278,7 +307,7 @@ export const PromptInput = React.memo(function PromptInput({ if (runningProcesses && runningProcesses.size > 0 && onToggleProcessStdout) { onToggleProcessStdout(); } else { - setStatusMessage("No running process to inspect"); + expandPasteMarkerAtCursor(); } return; } @@ -306,6 +335,8 @@ export const PromptInput = React.memo(function PromptInput({ } else if (!isEmpty(buffer)) { setBuffer(EMPTY_BUFFER); clearUndoRedoStacks(); + pastesRef.current.clear(); + expandedRegionsRef.current.clear(); } else { setStatusMessage("press ctrl+d to exit"); } @@ -324,6 +355,11 @@ export const PromptInput = React.memo(function PromptInput({ exitHistoryBrowsing(); } + if (key.paste) { + handlePaste(input); + return; + } + if (key.ctrl && (input === "v" || input === "V")) { setStatusMessage("Reading clipboard..."); readClipboardImageAsync() @@ -395,12 +431,12 @@ export const PromptInput = React.memo(function PromptInput({ } if (key.delete) { - updateBuffer((s) => deleteForward(s)); + updateBuffer((s) => deletePasteMarkerForward(s) ?? deleteForward(s)); return; } if (key.backspace) { - updateBuffer((s) => backspace(s)); + updateBuffer((s) => deletePasteMarkerBackward(s) ?? backspace(s)); return; } @@ -490,6 +526,8 @@ export const PromptInput = React.memo(function PromptInput({ } if (key.ctrl && (input === "u" || input === "U")) { updateBuffer(() => EMPTY_BUFFER); + pastesRef.current.clear(); + expandedRegionsRef.current.clear(); return; } if (key.ctrl && (input === "w" || input === "W")) { @@ -567,6 +605,81 @@ export const PromptInput = React.memo(function PromptInput({ }); } + function handlePaste(pastedText: string): void { + const totalChars = pastedText.length; + + if (totalChars <= 1000) { + const newlineCount = (pastedText.match(/\n/g) ?? []).length; + if (newlineCount <= 9) { + const clean = pastedText + .replace(/\r\n|\r/g, "\n") + .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "") + .replace(/\t/g, " "); + updateBuffer((s) => insertText(s, clean)); + return; + } + } + + // Large paste: store raw text, insert marker with line/char count. + const lineCount = (pastedText.match(/\n/g) ?? []).length + 1; + pasteCounterRef.current += 1; + const pasteId = pasteCounterRef.current; + pastesRef.current.set(pasteId, pastedText); + + const marker = + lineCount > 10 ? `[paste #${pasteId} +${lineCount} lines]` : `[paste #${pasteId} ${totalChars} chars]`; + + updateBuffer((s) => insertText(s, marker)); + } + + function expandPasteMarkerAtCursor(): void { + // First, try to collapse an already-expanded region at the cursor. + for (const [id, region] of expandedRegionsRef.current) { + if (buffer.cursor >= region.start && buffer.cursor <= region.end) { + // Collapse back to marker. + expandedRegionsRef.current.delete(id); + pastesRef.current.set(id, region.content); + setTimeout(() => { + updateBuffer((s) => { + const text = s.text.slice(0, region.start) + region.marker + s.text.slice(region.end); + return { text, cursor: region.start + region.marker.length }; + }); + }, 0); + return; + } + } + + // No expanded region at cursor — try to expand a paste marker. + const marker = findPasteMarkerContaining(buffer); + if (!marker) { + setStatusMessage("No paste marker at cursor"); + return; + } + const content = pastesRef.current.get(marker.id); + if (!content) { + setStatusMessage("Paste content not found"); + return; + } + + const pasteId = marker.id; + const originalMarker = buffer.text.slice(marker.start, marker.end); + pastesRef.current.delete(pasteId); + + setTimeout(() => { + updateBuffer((s) => { + const text = s.text.slice(0, marker.start) + cleanPasteContent(content) + s.text.slice(marker.end); + const newEnd = marker.start + content.length; + expandedRegionsRef.current.set(pasteId, { + start: marker.start, + end: newEnd, + content, + marker: originalMarker, + }); + return { text, cursor: marker.start }; + }); + }, 0); + } + function navigateHistory(direction: -1 | 1): void { if (promptHistory.length === 0) { return; @@ -607,6 +720,9 @@ export const PromptInput = React.memo(function PromptInput({ setImageUrls([]); setSelectedSkills([]); setShowSkillsDropdown(false); + pastesRef.current.clear(); + expandedRegionsRef.current.clear(); + pasteCounterRef.current = 0; } function handleSlashSelection(item: SlashCommandItem): void { @@ -664,6 +780,8 @@ export const PromptInput = React.memo(function PromptInput({ setImageUrls([]); setSelectedSkills([]); setShowSkillsDropdown(false); + pastesRef.current.clear(); + expandedRegionsRef.current.clear(); return; } if (item.kind === "mcp") { @@ -699,7 +817,7 @@ export const PromptInput = React.memo(function PromptInput({ } onSubmit({ - text: buffer.text, + text: expandPasteMarkers(buffer.text, pastesRef.current), imageUrls, selectedSkills, }); @@ -871,9 +989,6 @@ export function getPromptReturnKeyAction(key: Pick= end) return ""; + + const segText = text.slice(start, end); + const cursorRel = cursor - start; // relative cursor position inside this segment + + // Cursor not in this segment – just return the text. + if (cursorRel < 0 || cursorRel > segText.length) { + return highlighted ? chalk.yellow(segText) : segText; } - if (typeof at === "undefined") { - return before + renderCursorCell(" "); + // Cursor is exactly at `end` (which equals `segText.length`). + if (cursorRel === segText.length) { + return highlighted ? chalk.yellow(segText) + renderCursorCell(" ") : segText + renderCursorCell(" "); } + + // Cursor is somewhere inside the segment. + const at = segText[cursorRel]; + if (at === "\n") { + // Render newline as a space in the cursor cell, then output the actual newline. + const before = segText.slice(0, cursorRel); + const after = segText.slice(cursorRel + 1); return before + renderCursorCell(" ") + "\n" + after; } + + const before = segText.slice(0, cursorRel); + const after = segText.slice(cursorRel + 1); + if (highlighted) { + return chalk.yellow(before) + renderCursorCell(at) + chalk.yellow(after); + } return before + renderCursorCell(at) + after; } diff --git a/src/ui/prompt/cursor.ts b/src/ui/prompt/cursor.ts index 2668470..aefea34 100644 --- a/src/ui/prompt/cursor.ts +++ b/src/ui/prompt/cursor.ts @@ -40,6 +40,14 @@ function disableTerminalFocusReporting(): string { return "\u001B[?1004l"; } +function enableBracketedPaste(): string { + return "\u001B[?2004h"; +} + +function disableBracketedPaste(): string { + return "\u001B[?2004l"; +} + export function enableTerminalExtendedKeys(): string { return "\u001B[>4;1m"; } @@ -260,3 +268,16 @@ export function useTerminalExtendedKeys(stdout: NodeJS.WriteStream | undefined, }; }, [isActive, stdout]); } + +export function useBracketedPaste(stdout: NodeJS.WriteStream | undefined, isActive: boolean): void { + useLayoutEffect(() => { + if (!isActive || !stdout?.isTTY) { + return; + } + + stdout.write(enableBracketedPaste()); + return () => { + stdout.write(disableBracketedPaste()); + }; + }, [isActive, stdout]); +} diff --git a/src/ui/prompt/index.ts b/src/ui/prompt/index.ts index 5907558..6435f62 100644 --- a/src/ui/prompt/index.ts +++ b/src/ui/prompt/index.ts @@ -4,6 +4,7 @@ export type { InputKey } from "./useTerminalInput"; export { useHiddenTerminalCursor, useTerminalExtendedKeys, + useBracketedPaste, usePromptTerminalCursor, useTerminalFocusReporting, getPromptCursorPlacement, diff --git a/src/ui/prompt/useTerminalInput.ts b/src/ui/prompt/useTerminalInput.ts index 9ce6976..e3d6349 100644 --- a/src/ui/prompt/useTerminalInput.ts +++ b/src/ui/prompt/useTerminalInput.ts @@ -20,6 +20,8 @@ export type InputKey = { meta: boolean; focusIn: boolean; focusOut: boolean; + /** True when the input came from a bracketed paste (ESC[200~ ... ESC[201~). */ + paste: boolean; }; const BACKSPACE_BYTES = new Set(["\u007F", "\b"]); @@ -35,6 +37,13 @@ const META_RIGHT_SEQUENCES = new Set(["\u001B[1;3C", "\u001B[3C", "\u001Bf"]); const TERMINAL_FOCUS_IN = "\u001B[I"; const TERMINAL_FOCUS_OUT = "\u001B[O"; +// Bracketed paste mode markers (xterm-style). +// When the terminal supports bracketed paste, pasted text is wrapped with: +// ESC[200~ ...pasted content... ESC[201~ +const PASTE_START = "\u001B[200~"; +const PASTE_END = "\u001B[201~"; +const PASTE_END_LENGTH = 6; // length of PASTE_END + // Ctrl+- (minus) sequences in modifyOtherKeys mode. // \u001B[45;5u — standard format: keycode=45 ('-'), modifier=5 (Ctrl) // \u001B[27;5;45~ — extended format for function-like reporting @@ -73,6 +82,7 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: meta: false, focusIn: false, focusOut: false, + paste: false, }; return { input, key }; } @@ -100,6 +110,7 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: meta: false, focusIn: false, focusOut: false, + paste: false, }; return { input, key }; } @@ -123,6 +134,7 @@ export function parseTerminalInput(data: Buffer | string): { input: string; key: meta: META_LEFT_SEQUENCES.has(raw) || META_RIGHT_SEQUENCES.has(raw) || META_RETURN_SEQUENCES.has(raw), focusIn: raw === TERMINAL_FOCUS_IN, focusOut: raw === TERMINAL_FOCUS_OUT, + paste: false, }; if (input <= "\u001A" && !key.return) { @@ -200,6 +212,29 @@ export function dispatchTerminalInput( inputHandler(input, key); } +/** An InputKey with all fields false (including paste). Used when dispatching paste events. */ +const EMPTY_KEY: InputKey = { + upArrow: false, + downArrow: false, + leftArrow: false, + rightArrow: false, + home: false, + end: false, + pageDown: false, + pageUp: false, + return: false, + escape: false, + ctrl: false, + shift: false, + tab: false, + backspace: false, + delete: false, + meta: false, + focusIn: false, + focusOut: false, + paste: false, +}; + export function useTerminalInput( inputHandler: (input: string, key: InputKey) => void, options: { isActive?: boolean } = {} @@ -209,8 +244,15 @@ export function useTerminalInput( const handlerRef = useRef(inputHandler); handlerRef.current = inputHandler; + // Mutable paste-bracketing state shared across data events. + // Uses an array of chunks instead of string concatenation to avoid + // O(n²) copying when the terminal splits a large paste across many events. + const pasteRef = useRef({ active: false, chunks: [] as string[] }); + useEffect(() => { if (!isActive) { + pasteRef.current.active = false; + pasteRef.current.chunks = []; return; } setRawMode(true); @@ -223,7 +265,75 @@ export function useTerminalInput( if (!isActive) { return; } + const handleData = (data: Buffer | string) => { + const raw = String(data); + + // ----- Bracketed paste handling ----- + // Most terminals send the start/end markers in the same chunk as + // the content. We handle both inline and multi-chunk scenarios. + + if (raw.includes(PASTE_START)) { + pasteRef.current.active = true; + pasteRef.current.chunks = []; + + // Extract content after the start marker. + const startIdx = raw.indexOf(PASTE_START); + const afterStart = raw.slice(startIdx + PASTE_START.length); + + // Check if the end marker is also in this same chunk. + const endIdx = afterStart.indexOf(PASTE_END); + if (endIdx !== -1) { + // Both markers in one chunk — process immediately. + const pasteContent = afterStart.slice(0, endIdx); + pasteRef.current.active = false; + const remaining = afterStart.slice(endIdx + PASTE_END_LENGTH); + + if (pasteContent.length > 0) { + handlerRef.current(pasteContent, { ...EMPTY_KEY, paste: true }); + } + if (remaining.length > 0) { + dispatchTerminalInput(remaining, handlerRef.current); + } + return; + } + + // Only start marker — buffer as first chunk. + if (afterStart) { + pasteRef.current.chunks.push(afterStart); + } + return; + } + + if (pasteRef.current.active) { + pasteRef.current.chunks.push(raw); + // Only join+search when this chunk might contain the end marker. + if (raw.includes("201~")) { + const combined = pasteRef.current.chunks.join(""); + const endIdx = combined.indexOf(PASTE_END); + if (endIdx !== -1) { + const pasteContent = combined.slice(0, endIdx); + pasteRef.current.active = false; + const remaining = combined.slice(endIdx + PASTE_END_LENGTH); + pasteRef.current.chunks = []; + + // Dispatch the pasted text as a single event. + if (pasteContent.length > 0) { + handlerRef.current(pasteContent, { ...EMPTY_KEY, paste: true }); + } + + // Handle any remaining input after the paste end marker. + if (remaining.length > 0) { + dispatchTerminalInput(remaining, handlerRef.current); + } + return; + } + return; + } + return; + } + + // ----- Normal (non-paste) input ----- dispatchTerminalInput(data, handlerRef.current); }; diff --git a/src/ui/promptBuffer.ts b/src/ui/promptBuffer.ts index 3e3c182..97d15a5 100644 --- a/src/ui/promptBuffer.ts +++ b/src/ui/promptBuffer.ts @@ -171,6 +171,120 @@ export function getCurrentSlashToken(state: PromptBufferState): string | null { return line; } +/** + * Regex matching paste markers like `[paste #1 +123 lines]` or `[paste #2 1234 chars]`. + * When the user pastes a large block of text (>10 lines or >1000 chars), a compact + * marker is inserted instead of the full content. The actual content is stored in a + * Map and expanded back before submission. + */ +export const PASTE_MARKER_REGEX = /\[paste #(\d+)( (\+?\d+ lines|\d+ chars))?\]/g; + +/** + * Find the paste marker that ends exactly at `state.cursor`, if any. + * Returns the marker's start and end positions, or `null`. + */ +export function findPasteMarkerBefore(state: PromptBufferState): { start: number; end: number } | null { + // Walk backwards through all markers and return the one that ends at the cursor. + let match: RegExpExecArray | null; + PASTE_MARKER_REGEX.lastIndex = 0; + while ((match = PASTE_MARKER_REGEX.exec(state.text)) !== null) { + if (match.index + match[0].length === state.cursor) { + return { start: match.index, end: match.index + match[0].length }; + } + } + return null; +} + +/** + * Find the paste marker that starts exactly at `state.cursor`, if any. + * Returns the marker's start and end positions, or `null`. + */ +export function findPasteMarkerAt(state: PromptBufferState): { start: number; end: number } | null { + let match: RegExpExecArray | null; + PASTE_MARKER_REGEX.lastIndex = 0; + while ((match = PASTE_MARKER_REGEX.exec(state.text)) !== null) { + if (match.index === state.cursor) { + return { start: match.index, end: match.index + match[0].length }; + } + } + return null; +} + +/** + * If the cursor is immediately after a paste marker, delete the entire marker + * (atomic backspace). Returns the new state, or `state` unchanged if no marker. + */ +export function deletePasteMarkerBackward(state: PromptBufferState): PromptBufferState | null { + const marker = findPasteMarkerBefore(state); + if (!marker) return null; + const text = state.text.slice(0, marker.start) + state.text.slice(marker.end); + return { text, cursor: marker.start }; +} + +/** + * If the cursor is at the start of a paste marker, delete the entire marker + * (atomic forward delete). Returns the new state, or `state` unchanged if no marker. + */ +export function deletePasteMarkerForward(state: PromptBufferState): PromptBufferState | null { + const marker = findPasteMarkerAt(state); + if (!marker) return null; + const text = state.text.slice(0, marker.start) + state.text.slice(marker.end); + return { text, cursor: marker.start }; +} + +/** + * Sanitize stored paste content (filter control chars, expand tabs). + * Called lazily on expand/submit, not during paste to keep paste instant. + */ +export function cleanPasteContent(text: string): string { + return text + .replace(/\r\n|\r/g, "\n") + .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "") + .replace(/\t/g, " "); +} + +/** + * Expand paste markers in the text back to their original (cleaned) content. + * @param text - Text potentially containing paste markers. + * @param pastes - Map of paste ID → original content. + */ +export function expandPasteMarkers(text: string, pastes: Map): string { + if (pastes.size === 0) return text; + let result = text; + for (const [pasteId, pasteContent] of pastes) { + const markerRegex = new RegExp(`\\[paste #${pasteId}( (\\+?\\d+ lines|\\d+ chars))?\\]`, "g"); + result = result.replace(markerRegex, () => cleanPasteContent(pasteContent)); + } + return result; +} + +/** + * Find the paste marker that contains `state.cursor`, if any. + * Returns the marker's start, end, and numeric paste ID, or `null`. + */ +export function findPasteMarkerContaining(state: PromptBufferState): { start: number; end: number; id: number } | null { + let match: RegExpExecArray | null; + PASTE_MARKER_REGEX.lastIndex = 0; + while ((match = PASTE_MARKER_REGEX.exec(state.text)) !== null) { + if (match.index <= state.cursor && match.index + match[0].length >= state.cursor) { + return { + start: match.index, + end: match.index + match[0].length, + id: Number.parseInt(match[1]!, 10), + }; + } + } + return null; +} + +/** + * Check whether the given text contains any paste markers. + */ +export function hasActivePasteMarkers(text: string): boolean { + PASTE_MARKER_REGEX.lastIndex = 0; + return PASTE_MARKER_REGEX.test(text); +} + function locate(state: PromptBufferState): { line: number; column: number; From bb95daff1995dabf191e7888909423e5018e71a3 Mon Sep 17 00:00:00 2001 From: Kayro Date: Wed, 20 May 2026 22:30:59 +0800 Subject: [PATCH 103/129] fix: validate paste markers by ID to prevent false positives - hasActivePasteMarkers now checks validIds map, not just regex match - deletePasteMarkerBackward/Forward only atomically delete real paste markers - renderBufferWithCursor and renderFocusedText only highlight markers with valid IDs - PASTE_MARKER_REGEX requires line/char suffix (no bare [paste #N]) - Fix empty buffer cursor rendering in renderFocusedText regression - All render/test call sites updated to pass pastesRef.current --- src/ui/PromptInput.tsx | 42 +++++++++++++++++++++++++----------------- src/ui/promptBuffer.ts | 35 ++++++++++++++++++++++++++++------- 2 files changed, 53 insertions(+), 24 deletions(-) diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index ad73d83..0eaa169 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -188,7 +188,7 @@ export const PromptInput = React.memo(function PromptInput({ const showMenu = slashMenu.length > 0; const promptHistoryKey = React.useMemo(() => promptHistory.join("\0"), [promptHistory]); const hasRunningProcess = runningProcesses && runningProcesses.size > 0; - const hasCollapsedMarkers = hasActivePasteMarkers(buffer.text); + const hasCollapsedMarkers = hasActivePasteMarkers(buffer.text, pastesRef.current); const hasExpandedRegions = expandedRegionsRef.current.size > 0; const processOrPasteHint = hasRunningProcess ? " · ctrl+o view output" @@ -431,12 +431,12 @@ export const PromptInput = React.memo(function PromptInput({ } if (key.delete) { - updateBuffer((s) => deletePasteMarkerForward(s) ?? deleteForward(s)); + updateBuffer((s) => deletePasteMarkerForward(s, pastesRef.current) ?? deleteForward(s)); return; } if (key.backspace) { - updateBuffer((s) => deletePasteMarkerBackward(s) ?? backspace(s)); + updateBuffer((s) => deletePasteMarkerBackward(s, pastesRef.current) ?? backspace(s)); return; } @@ -872,7 +872,7 @@ export const PromptInput = React.memo(function PromptInput({ borderDimColor > - {renderBufferWithCursor(buffer, !disabled && hasTerminalFocus, placeholder)} + {renderBufferWithCursor(buffer, !disabled && hasTerminalFocus, placeholder, pastesRef.current)} {inlineHint ? {inlineHint} : null} +): string { const text = state.text || ""; const cursor = Math.max(0, Math.min(state.cursor, text.length)); + const validIds = validPastes ?? new Map(); if (text.length === 0 && placeholder) { if (!isFocused) { @@ -997,18 +1003,18 @@ export function renderBufferWithCursor(state: PromptBufferState, isFocused: bool return renderCursorCell(" ") + chalk.dim(` ${placeholder}`); } + if (text.length === 0) { + return isFocused ? renderCursorCell(" ") : ""; + } + if (!isFocused) { - return highlightPasteMarkersInText(text); + return highlightPasteMarkersInText(text, validIds); } - // Focused: scan through the text, highlight paste markers, and insert - // the cursor cell at the correct position. This approach handles the - // case where the cursor sits at the start of (or inside) a paste marker. - return renderFocusedText(text, cursor); + return renderFocusedText(text, cursor, validIds); } -/** Highlight paste markers in a plain string (no cursor). */ -function highlightPasteMarkersInText(s: string): string { +function highlightPasteMarkersInText(s: string, validIds: Map): string { if (!s.includes("[paste #")) return s; PASTE_MARKER_REGEX.lastIndex = 0; let result = ""; @@ -1016,7 +1022,8 @@ function highlightPasteMarkersInText(s: string): string { let match: RegExpExecArray | null; while ((match = PASTE_MARKER_REGEX.exec(s)) !== null) { result += s.slice(pos, match.index); - result += chalk.yellow(match[0]); + const id = Number.parseInt(match[1]!, 10); + result += validIds.has(id) ? chalk.yellow(match[0]) : match[0]; pos = match.index + match[0].length; } result += s.slice(pos); @@ -1029,7 +1036,7 @@ function highlightPasteMarkersInText(s: string): string { * anywhere (including inside or at the boundary of a paste marker) and the * marker will still be highlighted correctly. */ -function renderFocusedText(text: string, cursor: number): string { +function renderFocusedText(text: string, cursor: number, validIds: Map): string { let result = ""; let pos = 0; PASTE_MARKER_REGEX.lastIndex = 0; @@ -1038,14 +1045,15 @@ function renderFocusedText(text: string, cursor: number): string { while ((match = PASTE_MARKER_REGEX.exec(text)) !== null) { const markerStart = match.index; const markerEnd = match.index + match[0].length; + const id = Number.parseInt(match[1]!, 10); + const isReal = validIds.has(id); // 1. Non-marker segment before this marker. result += renderTextSegmentWithCursor(text, pos, markerStart, cursor, false); pos = markerStart; - // 2. Marker segment — highlighted with chalk.yellow. - // The cursor may fall inside it. - result += renderTextSegmentWithCursor(text, pos, markerEnd, cursor, true); + // 2. Marker segment — highlighted only if it corresponds to a real paste. + result += renderTextSegmentWithCursor(text, pos, markerEnd, cursor, isReal); pos = markerEnd; } diff --git a/src/ui/promptBuffer.ts b/src/ui/promptBuffer.ts index 97d15a5..3e0a710b 100644 --- a/src/ui/promptBuffer.ts +++ b/src/ui/promptBuffer.ts @@ -177,7 +177,7 @@ export function getCurrentSlashToken(state: PromptBufferState): string | null { * marker is inserted instead of the full content. The actual content is stored in a * Map and expanded back before submission. */ -export const PASTE_MARKER_REGEX = /\[paste #(\d+)( (\+?\d+ lines|\d+ chars))?\]/g; +export const PASTE_MARKER_REGEX = /\[paste #(\d+) (\+?\d+ lines|\d+ chars)\]/g; /** * Find the paste marker that ends exactly at `state.cursor`, if any. @@ -214,9 +214,16 @@ export function findPasteMarkerAt(state: PromptBufferState): { start: number; en * If the cursor is immediately after a paste marker, delete the entire marker * (atomic backspace). Returns the new state, or `state` unchanged if no marker. */ -export function deletePasteMarkerBackward(state: PromptBufferState): PromptBufferState | null { +export function deletePasteMarkerBackward( + state: PromptBufferState, + validIds: Map +): PromptBufferState | null { const marker = findPasteMarkerBefore(state); if (!marker) return null; + // Only delete if this is a real paste marker (ID in validIds). + PASTE_MARKER_REGEX.lastIndex = 0; + const m = PASTE_MARKER_REGEX.exec(state.text.slice(marker.start, marker.end)); + if (!m || !validIds.has(Number.parseInt(m[1]!, 10))) return null; const text = state.text.slice(0, marker.start) + state.text.slice(marker.end); return { text, cursor: marker.start }; } @@ -225,9 +232,16 @@ export function deletePasteMarkerBackward(state: PromptBufferState): PromptBuffe * If the cursor is at the start of a paste marker, delete the entire marker * (atomic forward delete). Returns the new state, or `state` unchanged if no marker. */ -export function deletePasteMarkerForward(state: PromptBufferState): PromptBufferState | null { +export function deletePasteMarkerForward( + state: PromptBufferState, + validIds: Map +): PromptBufferState | null { const marker = findPasteMarkerAt(state); if (!marker) return null; + // Only delete if this is a real paste marker (ID in validIds). + PASTE_MARKER_REGEX.lastIndex = 0; + const m = PASTE_MARKER_REGEX.exec(state.text.slice(marker.start, marker.end)); + if (!m || !validIds.has(Number.parseInt(m[1]!, 10))) return null; const text = state.text.slice(0, marker.start) + state.text.slice(marker.end); return { text, cursor: marker.start }; } @@ -252,7 +266,7 @@ export function expandPasteMarkers(text: string, pastes: Map): s if (pastes.size === 0) return text; let result = text; for (const [pasteId, pasteContent] of pastes) { - const markerRegex = new RegExp(`\\[paste #${pasteId}( (\\+?\\d+ lines|\\d+ chars))?\\]`, "g"); + const markerRegex = new RegExp(`\\[paste #${pasteId} (\\+?\\d+ lines|\\d+ chars)\\]`, "g"); result = result.replace(markerRegex, () => cleanPasteContent(pasteContent)); } return result; @@ -278,11 +292,18 @@ export function findPasteMarkerContaining(state: PromptBufferState): { start: nu } /** - * Check whether the given text contains any paste markers. + * Check whether the text contains real paste markers (IDs present in validIds). */ -export function hasActivePasteMarkers(text: string): boolean { +export function hasActivePasteMarkers(text: string, validIds: Map): boolean { + if (!text.includes("[paste #")) return false; PASTE_MARKER_REGEX.lastIndex = 0; - return PASTE_MARKER_REGEX.test(text); + let match: RegExpExecArray | null; + while ((match = PASTE_MARKER_REGEX.exec(text)) !== null) { + if (validIds.has(Number.parseInt(match[1]!, 10))) { + return true; + } + } + return false; } function locate(state: PromptBufferState): { From 27fcfd02e0c8cf564f39fa8d3fc4c9a878dbe501 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Thu, 21 May 2026 10:36:19 +0800 Subject: [PATCH 104/129] feat: add normalizeLlmToolCalls() to replace missing/empty tool call IDs --- src/session.ts | 34 ++++++++++++++++++++-- src/tests/session.test.ts | 60 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 3 deletions(-) diff --git a/src/session.ts b/src/session.ts index b4a3c71..54340e7 100644 --- a/src/session.ts +++ b/src/session.ts @@ -570,9 +570,10 @@ export class SessionManager { const toolCalls = Array.from(toolCallsByIndex.entries()) .sort(([left], [right]) => left - right) .map(([, toolCall]) => toolCall); + const normalizedToolCalls = this.normalizeLlmToolCalls(toolCalls); const message: Record = { content }; - if (toolCalls.length > 0) { - message.tool_calls = toolCalls; + if (normalizedToolCalls) { + message.tool_calls = normalizedToolCalls; } if (reasoningContent.length > 0) { message.reasoning_content = reasoningContent; @@ -1180,7 +1181,7 @@ ${skillMd} const rawContent = message?.content; const content = typeof rawContent === "string" ? rawContent : ""; const rawToolCalls = (message as { tool_calls?: unknown[] } | undefined)?.tool_calls ?? null; - toolCalls = Array.isArray(rawToolCalls) && rawToolCalls.length > 0 ? rawToolCalls : null; + toolCalls = this.normalizeLlmToolCalls(rawToolCalls); const rawThinking = (message as { reasoning_content?: unknown } | undefined)?.reasoning_content; const thinking = typeof rawThinking === "string" ? rawThinking : null; const refusal = (message as { refusal?: string } | undefined)?.refusal ?? null; @@ -1899,6 +1900,33 @@ ${skillMd} }; } + private generateToolCallId(): string { + return crypto.randomBytes(16).toString("hex"); + } + + private normalizeLlmToolCalls(rawToolCalls: unknown[] | null | undefined): unknown[] | null { + if (!Array.isArray(rawToolCalls) || rawToolCalls.length === 0) { + return null; + } + + return rawToolCalls.map((toolCall) => { + if (!toolCall || typeof toolCall !== "object" || Array.isArray(toolCall)) { + return toolCall; + } + + const record = toolCall as Record; + const id = typeof record.id === "string" ? record.id.trim() : ""; + if (id) { + return toolCall; + } + + return { + ...record, + id: this.generateToolCallId(), + }; + }); + } + private buildToolMessage( sessionId: string, toolCallId: string, diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 9f3c7fb..fd83199 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1565,6 +1565,66 @@ test("Write tool params prefer file_path even when content appears first", () => assert.equal(toolMessage.meta?.paramsMd, filePath); }); +test("LLM tool calls without ids receive generated 32 character ids", async () => { + const workspace = createTempDir("deepcode-tool-call-id-workspace-"); + const home = createTempDir("deepcode-tool-call-id-home-"); + setHomeDir(home); + + const filePath = path.join(workspace, "note.txt"); + fs.writeFileSync(filePath, "hello\n", "utf8"); + const plan = "## Task List\n\n- [ ] Inspect current behavior"; + const manager = createMockedClientSessionManager(workspace, [ + { + choices: [ + { + message: { + content: "", + tool_calls: [ + { + id: "", + type: "function", + function: { + name: "UpdatePlan", + arguments: JSON.stringify({ plan, explanation: "Initial plan" }), + }, + }, + { + type: "function", + function: { + name: "read", + arguments: JSON.stringify({ file_path: filePath }), + }, + }, + ], + }, + }, + ], + }, + createChatResponse("done", { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }), + ]); + + const sessionId = await manager.createSession({ text: "inspect note" }); + const assistantMessage = manager + .listSessionMessages(sessionId) + .find((message) => message.role === "assistant" && (message.messageParams as any)?.tool_calls); + const toolCalls = (assistantMessage?.messageParams as { tool_calls?: Array<{ id?: unknown }> } | null)?.tool_calls; + + assert.equal(toolCalls?.length, 2); + assert.match(String(toolCalls?.[0]?.id), /^[0-9a-f]{32}$/); + assert.match(String(toolCalls?.[1]?.id), /^[0-9a-f]{32}$/); + assert.notEqual(toolCalls?.[0]?.id, toolCalls?.[1]?.id); + + const toolMessages = manager.listSessionMessages(sessionId).filter((message) => message.role === "tool"); + assert.deepEqual( + toolMessages.map((message) => (message.messageParams as { tool_call_id?: unknown } | null)?.tool_call_id), + toolCalls?.map((toolCall) => toolCall.id) + ); + + const readToolMessage = toolMessages.find((message) => JSON.parse(message.content ?? "{}").name === "read"); + assert.equal((readToolMessage?.meta?.function as { name?: string } | undefined)?.name, "read"); + assert.equal(readToolMessage?.meta?.paramsMd, "note.txt"); +}); + test("buildOpenAIMessages repairs mixed missing duplicate and orphan tool messages", () => { const manager = createSessionManager(process.cwd(), "machine-id-mixed-tool-badcase"); const assistantMessage = (manager as any).buildAssistantMessage( From 5b51f4066c09764eb1de631109166a8d69013a94 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Thu, 21 May 2026 10:40:31 +0800 Subject: [PATCH 105/129] 0.1.24 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 17a77ca..0250531 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.23", + "version": "0.1.24", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@vegamo/deepcode-cli", - "version": "0.1.23", + "version": "0.1.24", "license": "MIT", "dependencies": { "chalk": "^5.6.2", diff --git a/package.json b/package.json index b72fd96..c8809ea 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.23", + "version": "0.1.24", "description": "Deep Code CLI - Vibe coding for the deepseek-v4 model in your terminal", "license": "MIT", "type": "module", From ec9a219554858262687180b40f5726a133e3bf73 Mon Sep 17 00:00:00 2001 From: hcyang Date: Thu, 21 May 2026 14:41:24 +0800 Subject: [PATCH 106/129] =?UTF-8?q?docs(cli):=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E5=B9=B6=E6=89=A9=E5=B1=95=E5=91=BD=E4=BB=A4=E8=8F=9C=E5=8D=95?= =?UTF-8?q?=E8=AF=B4=E6=98=8E=E5=92=8C=E5=B8=AE=E5=8A=A9=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 /skills、/model、/undo、/mcp 和 /raw 命令说明 - README.md 和 README-en.md 中同步添加对应命令描述 - 详细列出各命令功能,方便用户快速查阅 - 修改 CLI 界面帮助输出,包含所有新增命令提示 - 优化菜单结构,提升用户操作体验 --- README-en.md | 8 ++++++++ README-zh_CN.md | 45 ++++++++++++++++++++++++++------------------- README.md | 45 ++++++++++++++++++++++++++------------------- src/cli.tsx | 5 +++++ 4 files changed, 65 insertions(+), 38 deletions(-) diff --git a/README-en.md b/README-en.md index 55d0cf6..d9719fd 100644 --- a/README-en.md +++ b/README-en.md @@ -66,11 +66,13 @@ Deep Code CLI supports agent skills that allow you to extend the assistant's cap | `/` | Open the skills / commands menu | | `/new` | Start a fresh conversation | | `/resume` | Choose a previous conversation to continue | +| `/continue` | Continue the active conversation or pick one to resume | | `/model` | Switch model, thinking mode, and reasoning effort | | `/raw` | Toggle display mode (Normal / Lite / Raw scrollback) | | `/init` | Initialize an AGENTS.md file (LLM project instructions) | | `/skills` | List available skills | | `/mcp` | View MCP server status and available tools | +| `/undo` | Restore code and/or conversation to a previous point | | `/exit` | Quit (also `Ctrl+D` twice) | | Key | Action | @@ -126,6 +128,12 @@ Deep Code supports MCP (Model Context Protocol) to connect external services suc For detailed setup instructions, see: [docs/mcp.md](docs/mcp.md) +### How to configure Deep Code to send notifications after a task completes? + +When the AI assistant completes a task, Deep Code can automatically execute a notification script to send the task results to the specified channel (e.g., Slack, system notifications, etc.). + +For detailed configuration instructions, see: [docs/notify_en.md](docs/notify_en.md) + ## Contributing Contributions are welcome! Here's how to get started: diff --git a/README-zh_CN.md b/README-zh_CN.md index 8a427de..7b74a50 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -60,25 +60,27 @@ Deep Code CLI 支持 agent skills,允许您扩展助手的能力: ## 斜杠命令与按键功能 -| 斜杠命令 | 操作 | -|-----------------|---------------------------------------------| -| `/` | 打开 skills / 命令菜单 | -| `/new` | 开始新对话 | -| `/resume` | 选择历史对话继续 | -| `/model` | 切换模型、思考模式和推理强度 | -| `/raw` | 切换显示模式(Normal / Lite / Raw 滚动回溯)| -| `/init` | 初始化 AGENTS.md 文件 | -| `/skills` | 列出可用 skills | -| `/mcp` | 查看 MCP 服务器状态和可用工具 | -| `/exit` | 退出(也可用连续 `Ctrl+D`) | - -| 按键 | 操作 | -|-----------------|---------------------------------------------| -| `Enter` | 发送消息 | -| `Shift+Enter` | 插入换行(也可用 `Ctrl+J`) | -| `Ctrl+V` | 从剪贴板粘贴图片 | -| `Esc` | 中断当前模型回复 | -| 连续 `Ctrl+D` | 退出 | +| 斜杠命令 | 操作 | +|-------------|----------------------------------| +| `/` | 打开 skills / 命令菜单 | +| `/new` | 开始新对话 | +| `/resume` | 选择历史对话继续 | +| `/continue` | 继续当前对话,或选择历史对话恢复 | +| `/model` | 切换模型、思考模式和推理强度 | +| `/raw` | 切换显示模式(Normal / Lite / Raw 滚动回溯) | +| `/init` | 初始化 AGENTS.md 文件 | +| `/skills` | 列出可用 skills | +| `/mcp` | 查看 MCP 服务器状态和可用工具 | +| `/undo` | 将代码和/或对话恢复到之前的状态 | +| `/exit` | 退出(也可用连续 `Ctrl+D`) | + +| 按键 | 操作 | +|---------------|--------------------| +| `Enter` | 发送消息 | +| `Shift+Enter` | 插入换行(也可用 `Ctrl+J`) | +| `Ctrl+V` | 从剪贴板粘贴图片 | +| `Esc` | 中断当前模型回复 | +| 连续 `Ctrl+D` | 退出 | ## 支持的模型 @@ -111,6 +113,11 @@ Deep Code 支持 MCP(Model Context Protocol),可以连接 GitHub、浏览 详细配置指南:[docs/mcp.md](docs/mcp.md) +### 如何配置 Deep Code 任务完成后发送通知? + +当 AI 助手完成一轮任务后,Deep Code 可以自动执行一个通知脚本,将任务结果发送到你指定的渠道(如 Slack、系统通知等)。 + +详细配置指南:[docs/notify.md](docs/notify.md) ### 是否支持 Coding Plan? diff --git a/README.md b/README.md index 8a427de..7b74a50 100644 --- a/README.md +++ b/README.md @@ -60,25 +60,27 @@ Deep Code CLI 支持 agent skills,允许您扩展助手的能力: ## 斜杠命令与按键功能 -| 斜杠命令 | 操作 | -|-----------------|---------------------------------------------| -| `/` | 打开 skills / 命令菜单 | -| `/new` | 开始新对话 | -| `/resume` | 选择历史对话继续 | -| `/model` | 切换模型、思考模式和推理强度 | -| `/raw` | 切换显示模式(Normal / Lite / Raw 滚动回溯)| -| `/init` | 初始化 AGENTS.md 文件 | -| `/skills` | 列出可用 skills | -| `/mcp` | 查看 MCP 服务器状态和可用工具 | -| `/exit` | 退出(也可用连续 `Ctrl+D`) | - -| 按键 | 操作 | -|-----------------|---------------------------------------------| -| `Enter` | 发送消息 | -| `Shift+Enter` | 插入换行(也可用 `Ctrl+J`) | -| `Ctrl+V` | 从剪贴板粘贴图片 | -| `Esc` | 中断当前模型回复 | -| 连续 `Ctrl+D` | 退出 | +| 斜杠命令 | 操作 | +|-------------|----------------------------------| +| `/` | 打开 skills / 命令菜单 | +| `/new` | 开始新对话 | +| `/resume` | 选择历史对话继续 | +| `/continue` | 继续当前对话,或选择历史对话恢复 | +| `/model` | 切换模型、思考模式和推理强度 | +| `/raw` | 切换显示模式(Normal / Lite / Raw 滚动回溯) | +| `/init` | 初始化 AGENTS.md 文件 | +| `/skills` | 列出可用 skills | +| `/mcp` | 查看 MCP 服务器状态和可用工具 | +| `/undo` | 将代码和/或对话恢复到之前的状态 | +| `/exit` | 退出(也可用连续 `Ctrl+D`) | + +| 按键 | 操作 | +|---------------|--------------------| +| `Enter` | 发送消息 | +| `Shift+Enter` | 插入换行(也可用 `Ctrl+J`) | +| `Ctrl+V` | 从剪贴板粘贴图片 | +| `Esc` | 中断当前模型回复 | +| 连续 `Ctrl+D` | 退出 | ## 支持的模型 @@ -111,6 +113,11 @@ Deep Code 支持 MCP(Model Context Protocol),可以连接 GitHub、浏览 详细配置指南:[docs/mcp.md](docs/mcp.md) +### 如何配置 Deep Code 任务完成后发送通知? + +当 AI 助手完成一轮任务后,Deep Code 可以自动执行一个通知脚本,将任务结果发送到你指定的渠道(如 Slack、系统通知等)。 + +详细配置指南:[docs/notify.md](docs/notify.md) ### 是否支持 Coding Plan? diff --git a/src/cli.tsx b/src/cli.tsx index 66ceb7d..c3876ae 100644 --- a/src/cli.tsx +++ b/src/cli.tsx @@ -41,10 +41,15 @@ if (args.includes("--help") || args.includes("-h")) { " ctrl+x Clear pasted images", " esc Interrupt the current model turn", " / Open the skills/commands menu", + " /skills List available skills", + " /model Select model, thinking mode and effort control", " /new Start a fresh conversation", " /init Initialize an AGENTS.md file with instructions for LLM", " /resume Pick a previous conversation to continue", " /continue Continue the active conversation, or resume one if empty", + " /undo Restore code and/or conversation to a previous point", + " /mcp Show MCP server status and available tools", + " /raw Toggle display mode for viewing or collapsing reasoning content", " /exit Quit", " ctrl+d twice Quit", ].join("\n") + "\n" From 040a3245bbca60301c325ce6b993bf236ed8df4c Mon Sep 17 00:00:00 2001 From: hcyang Date: Thu, 21 May 2026 14:43:08 +0800 Subject: [PATCH 107/129] =?UTF-8?q?docs(cli):=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E5=B9=B6=E6=89=A9=E5=B1=95=E5=91=BD=E4=BB=A4=E8=8F=9C=E5=8D=95?= =?UTF-8?q?=E8=AF=B4=E6=98=8E=E5=92=8C=E5=B8=AE=E5=8A=A9=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 /skills、/model、/undo、/mcp 和 /raw 命令说明 - README.md 和 README-en.md 中同步添加对应命令描述 - 详细列出各命令功能,方便用户快速查阅 - 修改 CLI 界面帮助输出,包含所有新增命令提示 - 优化菜单结构,提升用户操作体验 --- README-en.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README-en.md b/README-en.md index d9719fd..18e3f13 100644 --- a/README-en.md +++ b/README-en.md @@ -61,19 +61,19 @@ Deep Code CLI supports agent skills that allow you to extend the assistant's cap ## Slash Commands & Keyboard Shortcuts -| Slash Command | Action | -|------------------|----------------------------------------------------------| -| `/` | Open the skills / commands menu | -| `/new` | Start a fresh conversation | -| `/resume` | Choose a previous conversation to continue | -| `/continue` | Continue the active conversation or pick one to resume | -| `/model` | Switch model, thinking mode, and reasoning effort | -| `/raw` | Toggle display mode (Normal / Lite / Raw scrollback) | -| `/init` | Initialize an AGENTS.md file (LLM project instructions) | -| `/skills` | List available skills | -| `/mcp` | View MCP server status and available tools | -| `/undo` | Restore code and/or conversation to a previous point | -| `/exit` | Quit (also `Ctrl+D` twice) | +| Slash Command | Action | +|------------------|---------------------------------------------------------| +| `/` | Open the skills / commands menu | +| `/new` | Start a fresh conversation | +| `/resume` | Choose a previous conversation to continue | +| `/continue` | Continue the active conversation or pick one to resume | +| `/model` | Switch model, thinking mode, and reasoning effort | +| `/raw` | Toggle display mode (Normal / Lite / Raw scrollback) | +| `/init` | Initialize an AGENTS.md file (LLM project instructions) | +| `/skills` | List available skills | +| `/mcp` | View MCP server status and available tools | +| `/undo` | Restore code and/or conversation to a previous point | +| `/exit` | Quit (also `Ctrl+D` twice) | | Key | Action | |------------------|----------------------------------------------------------| From 56e75050dce95fadf4bfde76feb80d703699a2a1 Mon Sep 17 00:00:00 2001 From: hcyang Date: Thu, 21 May 2026 15:37:55 +0800 Subject: [PATCH 108/129] =?UTF-8?q?docs(readme):=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E5=BE=BD=E7=AB=A0=E5=B1=95=E7=A4=BA=E6=8F=90?= =?UTF-8?q?=E5=8D=87=E4=BF=A1=E6=81=AF=E5=8F=AF=E8=A7=81=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 README.md、README-en.md 和 README-zh_CN.md 中添加了 npm 和 GitHub 相关徽章 - 新增版本号、下载量、贡献者、分支、Star、Issue、PR 和许可信息的动态展示链接 - 增强项目主页的视觉效果和信息传达 - 为中英文 README 文件同步更新相同内容及样式 --- README-en.md | 23 +++++++++++++++++++++++ README-zh_CN.md | 22 ++++++++++++++++++++++ README.md | 22 ++++++++++++++++++++++ 3 files changed, 67 insertions(+) diff --git a/README-en.md b/README-en.md index 18e3f13..be6442b 100644 --- a/README-en.md +++ b/README-en.md @@ -8,6 +8,9 @@

Deep Code CLI

+[![][npm-release-shield]][npm-release-link] [![][npm-downloads-shield]][npm-downloads-link] [![][github-contributors-shield]][github-contributors-link] [![][github-forks-shield]][github-forks-link] [![][github-stars-shield]][github-stars-link] +[![][github-issues-shield]][github-issues-link] [![][github-issues-pr-shield]][github-issues-pr-link] [![][github-license-shield]][github-license-link] + English · [中文](./README.md)
@@ -174,3 +177,23 @@ If you find this tool helpful, please consider supporting us by: - Giving us a Star on GitHub (https://github.com/lessweb/deepcode-cli) - Submitting feedback and suggestions - Sharing with your friends and colleagues + + + + +[npm-release-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli +[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square +[npm-downloads-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli +[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE +[github-contributors-link]: https://github.com/lessweb/deepcode-cli/graphs/contributors +[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-forks-link]: https://github.com/lessweb/deepcode-cli/network/members +[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-stars-link]: https://github.com/lessweb/deepcode-cli/network/stargazers +[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-link]: https://github.com/lessweb/deepcode-cli/issues +[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls +[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/master/LICENSE +[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file diff --git a/README-zh_CN.md b/README-zh_CN.md index 7b74a50..52f0123 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -8,6 +8,9 @@

Deep Code CLI

+[![][npm-release-shield]][npm-release-link] [![][npm-downloads-shield]][npm-downloads-link] [![][github-contributors-shield]][github-contributors-link] [![][github-forks-shield]][github-forks-link] [![][github-stars-shield]][github-stars-link] +[![][github-issues-shield]][github-issues-link] [![][github-issues-pr-shield]][github-issues-pr-link] [![][github-license-shield]][github-license-link] + [English](README-en.md) · 中文
@@ -173,3 +176,22 @@ npm link - 在 GitHub 上给我们一个 Star (https://github.com/lessweb/deepcode-cli) - 向我们提交反馈和建议 - 分享给你的朋友和同事 + + + +[npm-release-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli +[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square +[npm-downloads-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli +[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE +[github-contributors-link]: https://github.com/lessweb/deepcode-cli/graphs/contributors +[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-forks-link]: https://github.com/lessweb/deepcode-cli/network/members +[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-stars-link]: https://github.com/lessweb/deepcode-cli/network/stargazers +[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-link]: https://github.com/lessweb/deepcode-cli/issues +[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls +[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/master/LICENSE +[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file diff --git a/README.md b/README.md index 7b74a50..52f0123 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,9 @@

Deep Code CLI

+[![][npm-release-shield]][npm-release-link] [![][npm-downloads-shield]][npm-downloads-link] [![][github-contributors-shield]][github-contributors-link] [![][github-forks-shield]][github-forks-link] [![][github-stars-shield]][github-stars-link] +[![][github-issues-shield]][github-issues-link] [![][github-issues-pr-shield]][github-issues-pr-link] [![][github-license-shield]][github-license-link] + [English](README-en.md) · 中文
@@ -173,3 +176,22 @@ npm link - 在 GitHub 上给我们一个 Star (https://github.com/lessweb/deepcode-cli) - 向我们提交反馈和建议 - 分享给你的朋友和同事 + + + +[npm-release-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli +[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square +[npm-downloads-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli +[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE +[github-contributors-link]: https://github.com/lessweb/deepcode-cli/graphs/contributors +[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-forks-link]: https://github.com/lessweb/deepcode-cli/network/members +[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-stars-link]: https://github.com/lessweb/deepcode-cli/network/stargazers +[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-link]: https://github.com/lessweb/deepcode-cli/issues +[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls +[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/master/LICENSE +[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file From b010fb16f92dd01444d683566e41c3ef08c72af7 Mon Sep 17 00:00:00 2001 From: hcyang Date: Thu, 21 May 2026 22:46:17 +0800 Subject: [PATCH 109/129] =?UTF-8?q?docs(readme):=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=AE=B8=E5=8F=AF=E8=AF=81=E9=93=BE=E6=8E=A5=E5=88=B0=E4=B8=BB?= =?UTF-8?q?=E5=88=86=E6=94=AF=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 README.md 中许可证链接从 master 更改为 main 分支路径 - 同步更新 README-en.md 中的许可证链接路径 - 同步更新 README-zh_CN.md 中的许可证链接路径 - 保持徽章和其他链接不变,确保一致性和正确性 --- README-en.md | 2 +- README-zh_CN.md | 2 +- README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README-en.md b/README-en.md index be6442b..1e1323d 100644 --- a/README-en.md +++ b/README-en.md @@ -195,5 +195,5 @@ If you find this tool helpful, please consider supporting us by: [github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square [github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls [github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square -[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/master/LICENSE +[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/main/LICENSE [github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file diff --git a/README-zh_CN.md b/README-zh_CN.md index 52f0123..2909271 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -193,5 +193,5 @@ npm link [github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square [github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls [github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square -[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/master/LICENSE +[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/main/LICENSE [github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file diff --git a/README.md b/README.md index 52f0123..2909271 100644 --- a/README.md +++ b/README.md @@ -193,5 +193,5 @@ npm link [github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square [github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls [github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square -[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/master/LICENSE +[github-license-link]: https://github.com/lessweb/deepcode-cli/blob/main/LICENSE [github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file From c4a2463847d1d294624199d4a066b44b2547df37 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Fri, 22 May 2026 08:42:47 +0800 Subject: [PATCH 110/129] feat: update README.md --- README-en.md | 16 ++++++++-------- README-zh_CN.md | 16 ++++++++-------- README.md | 16 ++++++++-------- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/README-en.md b/README-en.md index 1e1323d..4bff6af 100644 --- a/README-en.md +++ b/README-en.md @@ -182,18 +182,18 @@ If you find this tool helpful, please consider supporting us by: [npm-release-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli -[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square +[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square&cacheSeconds=1800 [npm-downloads-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli -[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE +[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE&cacheSeconds=1800 [github-contributors-link]: https://github.com/lessweb/deepcode-cli/graphs/contributors -[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-forks-link]: https://github.com/lessweb/deepcode-cli/network/members -[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-stars-link]: https://github.com/lessweb/deepcode-cli/network/stargazers -[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-issues-link]: https://github.com/lessweb/deepcode-cli/issues -[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls -[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-license-link]: https://github.com/lessweb/deepcode-cli/blob/main/LICENSE -[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file +[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 \ No newline at end of file diff --git a/README-zh_CN.md b/README-zh_CN.md index 2909271..77db497 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -180,18 +180,18 @@ npm link [npm-release-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli -[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square +[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square&cacheSeconds=1800 [npm-downloads-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli -[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE +[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE&cacheSeconds=1800 [github-contributors-link]: https://github.com/lessweb/deepcode-cli/graphs/contributors -[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-forks-link]: https://github.com/lessweb/deepcode-cli/network/members -[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-stars-link]: https://github.com/lessweb/deepcode-cli/network/stargazers -[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-issues-link]: https://github.com/lessweb/deepcode-cli/issues -[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls -[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-license-link]: https://github.com/lessweb/deepcode-cli/blob/main/LICENSE -[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file +[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 \ No newline at end of file diff --git a/README.md b/README.md index 2909271..77db497 100644 --- a/README.md +++ b/README.md @@ -180,18 +180,18 @@ npm link [npm-release-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli -[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square +[npm-release-shield]: https://img.shields.io/npm/v/@vegamo/deepcode-cli?color=4d6BFE&labelColor=black&logo=npm&logoColor=white&style=flat-square&cacheSeconds=1800 [npm-downloads-link]: https://www.npmjs.com/package/@vegamo/deepcode-cli -[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE +[npm-downloads-shield]: https://img.shields.io/npm/dt/@vegamo/deepcode-cli?labelColor=black&style=flat-square&color=4d6BFE&cacheSeconds=1800 [github-contributors-link]: https://github.com/lessweb/deepcode-cli/graphs/contributors -[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-contributors-shield]: https://img.shields.io/github/contributors/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-forks-link]: https://github.com/lessweb/deepcode-cli/network/members -[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-forks-shield]: https://img.shields.io/github/forks/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-stars-link]: https://github.com/lessweb/deepcode-cli/network/stargazers -[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-stars-shield]: https://img.shields.io/github/stars/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-issues-link]: https://github.com/lessweb/deepcode-cli/issues -[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-shield]: https://img.shields.io/github/issues/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-issues-pr-link]: https://github.com/lessweb/deepcode-cli/pulls -[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square +[github-issues-pr-shield]: https://img.shields.io/github/issues-pr/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 [github-license-link]: https://github.com/lessweb/deepcode-cli/blob/main/LICENSE -[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square \ No newline at end of file +[github-license-shield]: https://img.shields.io/github/license/lessweb/deepcode-cli?color=4d6BFE&labelColor=black&style=flat-square&cacheSeconds=1800 \ No newline at end of file From d7d453f55bd11352a38dadb40ebb375cb656e9ba Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Fri, 22 May 2026 09:20:55 +0800 Subject: [PATCH 111/129] chore: remove draft doc --- docs/SKILL_new.md | 246 ---------------------------------------------- 1 file changed, 246 deletions(-) delete mode 100644 docs/SKILL_new.md diff --git a/docs/SKILL_new.md b/docs/SKILL_new.md deleted file mode 100644 index 9fc8bd2..0000000 --- a/docs/SKILL_new.md +++ /dev/null @@ -1,246 +0,0 @@ ---- -name: plan-and-execute -description: Automatically plan and execute requirements. Creates a markdown task list with the UpdatePlan tool, and systematically executes each task while updating progress. Use when working with task planning or when you need to break down and execute complex multi-step requirements. ---- - -# Plan and Execute - -This Skill helps you automatically plan and execute requirements. It creates a structured markdown task list with the UpdatePlan tool and systematically works through each task while keeping progress visible. - -## Quick Start - -When you need to work through a multi-step request: - -1. Analyze the requirements and explore enough project context -2. Clarify unclear or ambiguous requirements with AskUserQuestion -3. Create a markdown task list by calling the UpdatePlan tool -4. Execute tasks one by one, updating the tool plan in real time -5. Revise the remaining plan as new context appears - -## Instructions - -### Step 1: Analyze the requirements - -Identify the requirements from the available context. Explore the project enough to make the plan concrete and accurate. - -If the original requirements are unclear, incomplete, or ambiguous, call the AskUserQuestion tool before creating the task list. Ask only the questions needed to avoid implementing the wrong behavior, and keep each question specific to the decision that affects the plan or acceptance criteria. - -If a required referenced file path is missing, ask for it with AskUserQuestion: - -``` -What is the path to the referenced file? -``` - -Referenced files can be in any text format (.md, .txt, etc.) that contains task requirements or feature descriptions. If no additional file is needed, continue from the available requirements. - -- What are the main requirements? -- What tasks need to be completed? -- Are there dependencies between tasks? -- What is the complexity level? -- Which files, modules, commands, or tests are relevant? -- What ambiguity would change the implementation or acceptance criteria? - -### Step 2: Create the task list - -Create a structured markdown task list and pass it to the UpdatePlan tool as the `plan` string. The tool input must use this shape: - -```json -{ - "plan": "## Task List\n\n- [ ] Task 1 description\n- [ ] Task 2 description\n- [ ] Task 3 description" -} -``` - -Use this markdown format for the `plan` content: - -```markdown -## Task List - -- [ ] Task 1 description -- [ ] Task 2 description -- [ ] Task 3 description -``` - -Break down complex requirements into specific, actionable tasks and call UpdatePlan with the full markdown task list. - -### Step 3: Execute tasks systematically - -For each task in the list: - -1. **Refresh the plan**: Before starting the first task and after completing each task, re-evaluate the latest conversation and project context. Update the remaining tasks when scope, order, blockers, or follow-up work changes. -2. **Mark as in progress**: Call UpdatePlan with the task changed from `[ ]` to `[>]` -3. **Execute the task**: Use appropriate tools to complete the work -4. **Mark as completed**: Call UpdatePlan with the task changed from `[>]` to `[x]` when finished -5. **Move to next task**: Only ONE task should be in progress at a time - -Important rules: -- Always keep the plan aligned with the latest context before executing the next task -- Always call UpdatePlan BEFORE starting work on a task -- Always call UpdatePlan IMMEDIATELY after completing a task -- Always pass the complete current markdown task list, not a partial diff -- Never work on multiple tasks simultaneously -- Remove tasks that are no longer relevant, and add newly discovered tasks before working on them -- If you encounter errors, keep the task as `[>]` and create new tasks to resolve blockers - -### Step 4: Handle task breakdown - -If during execution you discover a task is more complex than expected: - -1. Keep the current task as `[>]` -2. Call UpdatePlan with new sub-tasks below it with indentation: - ```markdown - - [>] Main task - - [ ] Sub-task 1 - - [ ] Sub-task 2 - ``` -3. Complete sub-tasks first, then mark the main task as complete with UpdatePlan - -### Step 5: Final verification - -After all tasks are completed (`[x]`): - -1. Review the original requirements to ensure everything is addressed -2. Run any final checks (tests, builds, linting) -3. Call UpdatePlan with every task marked `[x]` -4. Provide a concise completion summary in the final response - -## Task State Symbols - -- `[ ]` - Pending -- `[>]` - In progress -- `[x]` - Completed -- `[!]` - Blocked - -## Examples - -### Example 1: Simple feature request - -**Example requirements:** -```markdown -# 新功能:添加深色模式切换 - -用户应该能够在浅色和深色主题之间切换。 -切换开关应放在设置页面中。 -``` - -**分析后的 UpdatePlan 调用:** -```markdown -## Task List - -- [ ] 在设置页面创建深色模式切换组件 -- [ ] 添加深色模式状态管理(context/store) -- [ ] 实现深色主题的 CSS-in-JS 样式 -- [ ] 更新现有组件以支持主题切换 -- [ ] 运行测试并验证功能 -``` - -**UpdatePlan call during execution:** -```markdown -## Task List - -- [x] 在设置页面创建深色模式切换组件 -- [>] 添加深色模式状态管理(context/store) -- [ ] 实现深色主题的 CSS-in-JS 样式 -- [ ] 更新现有组件以支持主题切换 -- [ ] 运行测试并验证功能 -``` - -### Example 2: Bug fix with investigation - -**Example requirements:** -```markdown -# Fix bug:登录表单提交时崩溃 - -当用户点击提交时,应用崩溃。 -错误信息:"Cannot read property 'email' of undefined" -``` - -**UpdatePlan call after analysis:** -```markdown -## Task List - -- [ ] 在本地复现缺陷 -- [ ] 调查登录表单组件中的错误 -- [ ] 定位 undefined email 属性的根本原因 -- [ ] 实施修复 -- [ ] 添加验证以防止类似问题 -- [ ] 使用各种输入测试修复 -- [ ] 更新错误处理 -``` - -## When to Use This Skill - -Use this Skill when: - -1. **Complex multi-step tasks** - Request requires 3+ distinct steps -2. **Feature implementation** - Building new functionality from requirements -3. **Bug fixing** - Need to investigate, fix, and verify -4. **Refactoring** - Multiple files or components need changes -5. **Detailed requirements** - Specifications need to be translated into concrete tasks -6. **Need progress tracking** - Want visible progress without editing source files - -## When NOT to Use This Skill - -Skip this Skill when: - -1. **Single simple task** - Just one straightforward action needed -2. **Trivial changes** - Quick fixes that don't need planning -3. **Informational requests** - User just wants explanation, not execution -4. **No execution requested** - User only wants brainstorming or a high-level explanation - -## Best Practices - -1. **Be specific with tasks**: "Add login button to navbar" not "Update UI" -2. **Keep tasks atomic**: Each task should be independently completable -3. **Update immediately**: Don't batch status updates, do them in real-time -4. **One task at a time**: Never mark multiple tasks as `[>]` -5. **Handle blockers**: If stuck, create new tasks to resolve the blocker -6. **Verify completion**: Only mark `[x]` when task is fully done - -## Advanced Usage - -### Handling dependencies - -When tasks have dependencies, order them properly: - -```markdown -- [ ] Create database schema -- [ ] Implement API endpoints (depends on schema) -- [ ] Build frontend forms (depends on API) -``` - -### Using sub-tasks - -For complex tasks, break them down: - -```markdown -- [>] Implement authentication system - - [x] Set up JWT library - - [>] Create login endpoint - - [ ] Create logout endpoint - - [ ] Add token refresh logic -``` - -### Adding notes - -Add implementation notes or findings: - -```markdown -- [x] Investigate performance issue - - Note: Found N+1 query in user loader - - Solution: Added dataloader batching -``` - -## Workflow Summary - -1. Analyze the requirements and relevant project context -2. Call AskUserQuestion if the original requirements are unclear or ambiguous -3. Call UpdatePlan with the structured markdown task list -4. Refresh the remaining plan before the first task -5. For each task: - - Update to `[>]` with UpdatePlan - - Execute the task - - Update to `[x]` with UpdatePlan - - Re-evaluate and revise remaining tasks before moving on -6. Call UpdatePlan with all tasks completed and summarize the result - -This approach keeps planning and progress tracking in the UpdatePlan display, leaving source materials unchanged unless the actual task requires editing them. From 27b9b7feb444cbeb0b10473216e7f6804530234f Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Fri, 22 May 2026 10:22:12 +0800 Subject: [PATCH 112/129] refactor: adjust calling identifyMatchingSkillNames in createSession and replySession --- src/session.ts | 37 +++++++++++++++++++------------------ src/tests/session.test.ts | 10 ++++++++-- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/src/session.ts b/src/session.ts index 54340e7..3144f88 100644 --- a/src/session.ts +++ b/src/session.ts @@ -901,20 +901,6 @@ The candidate skills are as follows:\n\n`; const signal = controller?.signal; this.throwIfAborted(signal); - if (userPrompt.text) { - const skills = await this.listSkills(); - const skillNames = await this.identifyMatchingSkillNames(skills, userPrompt.text, { signal }); - this.throwIfAborted(signal); - const skillSet = new Set(skillNames); - const matchedSkill = skills.filter((skill) => skillSet.has(skill.name)); - if (Array.isArray(userPrompt.skills)) { - userPrompt.skills.push(...matchedSkill); - } else if (matchedSkill.length > 0) { - userPrompt.skills = matchedSkill; - } - } - userPrompt.skills = await this.normalizeSkills(userPrompt.skills); - this.throwIfAborted(signal); const sessionId = crypto.randomUUID(); this.ensureFileHistorySession(sessionId); const now = new Date().toISOString(); @@ -977,6 +963,21 @@ The candidate skills are as follows:\n\n`; const userMessage = this.buildUserMessage(sessionId, userPrompt); this.appendSessionMessage(sessionId, userMessage); + if (userPrompt.text) { + const skills = await this.listSkills(); + const skillNames = await this.identifyMatchingSkillNames(skills, userPrompt.text, { signal }); + this.throwIfAborted(signal); + const skillSet = new Set(skillNames); + const matchedSkill = skills.filter((skill) => skillSet.has(skill.name)); + if (Array.isArray(userPrompt.skills)) { + userPrompt.skills.push(...matchedSkill); + } else if (matchedSkill.length > 0) { + userPrompt.skills = matchedSkill; + } + } + userPrompt.skills = await this.normalizeSkills(userPrompt.skills); + this.throwIfAborted(signal); + if (userPrompt.skills && userPrompt.skills.length > 0) { for (const skill of userPrompt.skills) { if (skill.isLoaded) { @@ -1022,6 +1023,10 @@ ${skillMd} this.reportNewPrompt(); + this.ensureFileHistorySession(sessionId); + const userMessage = this.buildUserMessage(sessionId, userPrompt); + this.appendSessionMessage(sessionId, userMessage); + if (userPrompt.text) { const skills = await this.listSkills(sessionId); const skillNames = await this.identifyMatchingSkillNames(skills, userPrompt.text, { signal, sessionId }); @@ -1037,10 +1042,6 @@ ${skillMd} userPrompt.skills = await this.normalizeSkills(userPrompt.skills, sessionId); this.throwIfAborted(signal); - this.ensureFileHistorySession(sessionId); - const userMessage = this.buildUserMessage(sessionId, userPrompt); - this.appendSessionMessage(sessionId, userMessage); - if (userPrompt.skills && userPrompt.skills.length > 0) { for (const skill of userPrompt.skills) { if (skill.isLoaded) { diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index fd83199..e5bdcb2 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1952,7 +1952,7 @@ test("SessionManager streams chat completions and counts reasoning progress", as assert.equal(progressEvents[2]?.formattedTokens, "3"); }); -test("SessionManager cancels skill matching before a session is created", async () => { +test("SessionManager persists session and user message before skill matching is cancelled", async () => { const workspace = createTempDir("deepcode-skill-abort-workspace-"); const home = createTempDir("deepcode-skill-abort-home-"); setHomeDir(home); @@ -1981,7 +1981,13 @@ test("SessionManager cancels skill matching before a session is created", async await manager.handleUserPrompt({ text: "please use demo" }); - assert.equal(manager.listSessions().length, 0); + // Session and user message are persisted before skill matching triggers an abort. + assert.equal(manager.listSessions().length, 1); + const [session] = manager.listSessions(); + assert.equal(session?.status, "pending"); + const messages = manager.listSessionMessages(session!.id); + const userMessage = messages.find((m) => m.role === "user"); + assert.equal(userMessage?.content, "please use demo"); }); test("SessionManager treats OpenAI APIUserAbortError as interrupted", async () => { From f1774292a0e2e4420117e1984ce40efd94b38799 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Fri, 22 May 2026 11:01:31 +0800 Subject: [PATCH 113/129] feat: implement checkpoints store only explicit Write/Edit file paths --- src/common/file-history.ts | 206 ++++++++++++++++++++++++++++--------- src/tests/session.test.ts | 96 +++++++++-------- 2 files changed, 215 insertions(+), 87 deletions(-) diff --git a/src/common/file-history.ts b/src/common/file-history.ts index d5966d9..2a41d9a 100644 --- a/src/common/file-history.ts +++ b/src/common/file-history.ts @@ -1,13 +1,26 @@ import * as childProcess from "child_process"; +import * as crypto from "crypto"; import * as fs from "fs"; import * as path from "path"; const FILE_HISTORY_AUTHOR_NAME = "DeepCode Checkpoint"; const FILE_HISTORY_AUTHOR_EMAIL = "deepcode-checkpoint@localhost"; +const MANIFEST_PATH = ".deepcode-file-history.json"; + +type FileHistoryEntry = { + path: string; + blob: string; + mode: "100644"; +}; + +type FileHistoryManifest = { + version: 1; + files: Record; +}; export class GitFileHistory { constructor( - private readonly projectRoot: string, + _projectRoot: string, private readonly gitDir: string ) {} @@ -20,7 +33,7 @@ export class GitFileHistory { try { if (!fs.existsSync(this.gitDir)) { fs.mkdirSync(path.dirname(this.gitDir), { recursive: true }); - this.runGit(["init"], { includeWorkTree: true }); + this.runGit(["init"]); } const current = this.getCurrentCheckpointHash(sessionId); @@ -28,9 +41,9 @@ export class GitFileHistory { return current; } - const emptyTree = this.runGit(["mktree"], { includeWorkTree: false, input: "" }).trim(); - const commitHash = this.createCommit(emptyTree, null, "Initial checkpoint"); - this.runGit(["update-ref", branchRef, commitHash], { includeWorkTree: false }); + const treeHash = this.createTree(emptyManifest()); + const commitHash = this.createCommit(treeHash, null, "Initial checkpoint"); + this.runGit(["update-ref", branchRef, commitHash]); return commitHash; } catch { return undefined; @@ -44,9 +57,7 @@ export class GitFileHistory { } try { - const hash = this.runGit(["rev-parse", "--verify", `${branchRef}^{commit}`], { - includeWorkTree: false, - }).trim(); + const hash = this.runGit(["rev-parse", "--verify", `${branchRef}^{commit}`]).trim(); return isCommitHash(hash) ? hash : undefined; } catch { return undefined; @@ -59,10 +70,8 @@ export class GitFileHistory { return undefined; } - const relativePaths = filePaths - .map((filePath) => this.toProjectRelativeGitPath(filePath)) - .filter((filePath): filePath is string => Boolean(filePath)); - if (relativePaths.length === 0) { + const absolutePaths = uniqueAbsolutePaths(filePaths); + if (absolutePaths.length === 0) { return this.getCurrentCheckpointHash(sessionId); } @@ -71,18 +80,30 @@ export class GitFileHistory { if (!parentHash) { return undefined; } - this.runGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); - this.runGit(["add", "-f", "-A", "--", ...relativePaths], { includeWorkTree: true }); - const treeHash = this.runGit(["write-tree"], { includeWorkTree: false }).trim(); - const parentTreeHash = this.runGit(["rev-parse", `${parentHash}^{tree}`], { - includeWorkTree: false, - }).trim(); + + const manifest = this.readManifest(parentHash); + for (const filePath of absolutePaths) { + const key = this.getFileKey(filePath); + if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) { + delete manifest.files[key]; + continue; + } + + manifest.files[key] = { + path: filePath, + blob: this.hashFile(filePath), + mode: "100644", + }; + } + + const treeHash = this.createTree(manifest); + const parentTreeHash = this.runGit(["rev-parse", `${parentHash}^{tree}`]).trim(); if (treeHash === parentTreeHash) { return parentHash; } const commitHash = this.createCommit(treeHash, parentHash, message); - this.runGit(["update-ref", branchRef, commitHash, parentHash], { includeWorkTree: false }); + this.runGit(["update-ref", branchRef, commitHash, parentHash]); return commitHash; } catch { return undefined; @@ -101,7 +122,8 @@ export class GitFileHistory { } try { - this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); + this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`]); + this.readManifest(checkpointHash); return true; } catch { return false; @@ -116,16 +138,24 @@ export class GitFileHistory { if (!branchRef || !fs.existsSync(this.gitDir)) { throw new Error("File history Git repository was not found for this project."); } - this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); + this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`]); - try { - this.runGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); - } catch { - // If the session branch is missing, fall back to the target tree only. - // The target checkpoint has already been validated above. + const currentHash = this.getCurrentCheckpointHash(sessionId); + const currentManifest = currentHash ? this.readManifest(currentHash) : emptyManifest(); + const targetManifest = this.readManifest(checkpointHash); + + for (const [key, entry] of Object.entries(currentManifest.files)) { + if (!targetManifest.files[key]) { + removeTrackedFile(entry.path); + } } - this.runGit(["read-tree", "--reset", "-u", checkpointHash], { includeWorkTree: true }); - this.runGit(["update-ref", branchRef, checkpointHash], { includeWorkTree: false }); + + for (const entry of Object.values(targetManifest.files)) { + fs.mkdirSync(path.dirname(entry.path), { recursive: true }); + fs.writeFileSync(entry.path, this.readBlob(entry.blob)); + } + + this.runGit(["update-ref", branchRef, checkpointHash]); } private getSessionBranchRef(sessionId: string): string | null { @@ -142,41 +172,125 @@ export class GitFileHistory { } args.push("-m", message); return this.runGit(args, { - includeWorkTree: false, env: getFileHistoryGitEnv(), }).trim(); } - private toProjectRelativeGitPath(filePath: string): string | null { - const absolutePath = path.resolve(filePath); - const relativePath = path.relative(this.projectRoot, absolutePath); - if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) { - return null; + private createTree(manifest: FileHistoryManifest): string { + const normalizedManifest = normalizeManifest(manifest); + const manifestBlob = this.hashContent(`${JSON.stringify(normalizedManifest, null, 2)}\n`); + const entries: string[] = [`100644 blob ${manifestBlob}\t${MANIFEST_PATH}\0`]; + + for (const [key, entry] of Object.entries(normalizedManifest.files)) { + entries.push(`${entry.mode} blob ${entry.blob}\t${key}\0`); } - return relativePath.split(path.sep).join("/"); + + return this.runGit(["mktree", "-z"], { input: entries.join("") }).trim(); } - private runGit( - args: string[], - options: { includeWorkTree: boolean; input?: string; env?: NodeJS.ProcessEnv } - ): string { - const gitArgs = ["-c", "core.autocrlf=false", "-c", "core.eol=lf", `--git-dir=${this.gitDir}`]; - if (options.includeWorkTree) { - gitArgs.push(`--work-tree=${this.projectRoot}`); + private readManifest(commitHash: string): FileHistoryManifest { + const buffer = this.runGitBuffer(["cat-file", "blob", `${commitHash}:${MANIFEST_PATH}`]); + const parsed = JSON.parse(buffer.toString("utf8")) as FileHistoryManifest; + if (!parsed || parsed.version !== 1 || !parsed.files || typeof parsed.files !== "object") { + throw new Error("Invalid file history manifest."); + } + return normalizeManifest(parsed); + } + + private readBlob(blobHash: string): Buffer { + if (!isCommitHash(blobHash)) { + throw new Error("Invalid file history blob hash."); + } + return this.runGitBuffer(["cat-file", "blob", blobHash]); + } + + private hashFile(filePath: string): string { + const blobHash = this.runGit(["hash-object", "-w", "--", filePath]).trim(); + if (!isCommitHash(blobHash)) { + throw new Error("Invalid file history blob hash."); } - gitArgs.push(...args); + return blobHash; + } + + private hashContent(content: string): string { + const blobHash = this.runGit(["hash-object", "-w", "--stdin"], { input: content }).trim(); + if (!isCommitHash(blobHash)) { + throw new Error("Invalid file history blob hash."); + } + return blobHash; + } + + private getFileKey(filePath: string): string { + const hash = crypto.createHash("sha256").update(filePath).digest("hex"); + return `files-${hash}`; + } + + private runGit(args: string[], options: { input?: string | Buffer; env?: NodeJS.ProcessEnv } = {}): string { + return this.spawnGit(args, options, "utf8") as string; + } + + private runGitBuffer(args: string[], options: { input?: string | Buffer; env?: NodeJS.ProcessEnv } = {}): Buffer { + return this.spawnGit(args, options, "buffer") as Buffer; + } + + private spawnGit( + args: string[], + options: { input?: string | Buffer; env?: NodeJS.ProcessEnv }, + encoding: BufferEncoding | "buffer" + ): string | Buffer { + const gitArgs = ["-c", "core.autocrlf=false", "-c", "core.eol=lf", `--git-dir=${this.gitDir}`, ...args]; const result = childProcess.spawnSync("git", gitArgs, { - encoding: "utf8", + encoding, input: options.input, env: options.env, stdio: ["pipe", "pipe", "pipe"], }); if (result.status !== 0) { - const detail = (result.stderr || result.stdout || "").trim(); + const stderr = Buffer.isBuffer(result.stderr) ? result.stderr.toString("utf8") : result.stderr; + const stdout = Buffer.isBuffer(result.stdout) ? result.stdout.toString("utf8") : result.stdout; + const detail = (stderr || stdout || "").trim(); throw new Error(detail || `git ${args.join(" ")} failed`); } - return result.stdout ?? ""; + return result.stdout ?? (encoding === "buffer" ? Buffer.alloc(0) : ""); + } +} + +function emptyManifest(): FileHistoryManifest { + return { version: 1, files: {} }; +} + +function normalizeManifest(manifest: FileHistoryManifest): FileHistoryManifest { + const files: Record = {}; + for (const [key, entry] of Object.entries(manifest.files).sort(([left], [right]) => left.localeCompare(right))) { + if (!isValidStoredPath(key) || !entry || entry.mode !== "100644" || !isCommitHash(entry.blob)) { + throw new Error("Invalid file history manifest."); + } + files[key] = { + path: path.resolve(entry.path), + blob: entry.blob, + mode: "100644", + }; + } + return { version: 1, files }; +} + +function uniqueAbsolutePaths(filePaths: string[]): string[] { + return Array.from(new Set(filePaths.map((filePath) => path.resolve(filePath)))); +} + +function isValidStoredPath(value: string): boolean { + return /^files-[0-9a-f]{64}$/.test(value); +} + +function removeTrackedFile(filePath: string): void { + if (!fs.existsSync(filePath)) { + return; + } + const stat = fs.lstatSync(filePath); + if (stat.isDirectory()) { + return; } + fs.unlinkSync(filePath); } function getFileHistoryGitEnv(): NodeJS.ProcessEnv { diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index e5bdcb2..08d61e9 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -4,6 +4,7 @@ import { execFileSync } from "node:child_process"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import { GitFileHistory } from "../common/file-history"; import { SessionManager, type SessionMessage } from "../session"; const originalFetch = globalThis.fetch; @@ -1040,6 +1041,54 @@ test("Write tool advances file-history while preserving the user prompt checkpoi assert.equal(fs.existsSync(filePath), false); }); +test("Write checkpoints restore tool-touched files outside the workspace and leave unrelated files alone", async (t) => { + if (!hasGit()) { + t.skip("git is not available"); + return; + } + + const workspace = createTempDir("deepcode-write-outside-workspace-"); + const outsideDir = createTempDir("deepcode-write-outside-target-"); + const home = createTempDir("deepcode-write-outside-home-"); + setHomeDir(home); + + const outsideFilePath = path.join(outsideDir, "outside.txt"); + const unrelatedWorkspaceFilePath = path.join(workspace, "unrelated.txt"); + const manager = createMockedClientSessionManager(workspace, [ + { + choices: [ + { + message: { + content: "", + tool_calls: [ + { + id: "call-write-outside", + type: "function", + function: { + name: "write", + arguments: JSON.stringify({ file_path: outsideFilePath, content: "outside\n" }), + }, + }, + ], + }, + }, + ], + }, + createChatResponse("done", { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }), + ]); + + const sessionId = await manager.createSession({ text: "create an outside file" }); + const userMessage = manager.listSessionMessages(sessionId).find((message) => message.role === "user"); + assert.ok(userMessage?.checkpointHash); + assert.equal(fs.readFileSync(outsideFilePath, "utf8"), "outside\n"); + + fs.writeFileSync(unrelatedWorkspaceFilePath, "keep\n", "utf8"); + manager.restoreSessionCode(sessionId, userMessage.id); + + assert.equal(fs.existsSync(outsideFilePath), false); + assert.equal(fs.readFileSync(unrelatedWorkspaceFilePath, "utf8"), "keep\n"); +}); + test("missing git executable does not block sessions or Write tool calls", async () => { const workspace = createTempDir("deepcode-no-git-write-workspace-"); const home = createTempDir("deepcode-no-git-write-home-"); @@ -2146,43 +2195,18 @@ function createFileHistoryCommit( ): string { const projectCode = workspace.replace(/[\\/]/g, "-").replace(/:/g, ""); const gitDir = path.join(home, ".deepcode", "projects", projectCode, "file-history", ".git"); - const branchRef = `refs/heads/${sessionId}`; - fs.mkdirSync(path.dirname(gitDir), { recursive: true }); - if (!fs.existsSync(gitDir)) { - runFileHistoryGit(gitDir, workspace, ["init"]); - } - - let parentHash = ""; - try { - parentHash = runFileHistoryGit(gitDir, workspace, ["rev-parse", "--verify", `${branchRef}^{commit}`]).trim(); - } catch { - const emptyTree = runFileHistoryGit(gitDir, workspace, ["mktree"], ""); - parentHash = runFileHistoryGit( - gitDir, - workspace, - ["commit-tree", emptyTree.trim(), "-m", "initial checkpoint"], - "", - fileHistoryCommitEnv() - ).trim(); - runFileHistoryGit(gitDir, workspace, ["update-ref", branchRef, parentHash]); - } - runFileHistoryGit(gitDir, workspace, ["read-tree", "--reset", branchRef]); + const fileHistory = new GitFileHistory(workspace, gitDir); + fileHistory.ensureSession(sessionId); + const filePaths: string[] = []; for (const [relativePath, content] of Object.entries(files)) { const filePath = path.join(workspace, relativePath); fs.mkdirSync(path.dirname(filePath), { recursive: true }); fs.writeFileSync(filePath, content, "utf8"); + filePaths.push(filePath); } - runFileHistoryGit(gitDir, workspace, ["add", "-f", "-A", "--", ...Object.keys(files)]); - const treeHash = runFileHistoryGit(gitDir, workspace, ["write-tree"]).trim(); - const commitHash = runFileHistoryGit( - gitDir, - workspace, - ["commit-tree", treeHash, "-p", parentHash, "-m", "checkpoint"], - "", - fileHistoryCommitEnv() - ).trim(); - runFileHistoryGit(gitDir, workspace, ["update-ref", branchRef, commitHash, parentHash]); + const commitHash = fileHistory.recordCheckpoint(sessionId, filePaths, "checkpoint"); + assert.ok(commitHash); return commitHash; } @@ -2205,16 +2229,6 @@ function runFileHistoryGit( ); } -function fileHistoryCommitEnv(): NodeJS.ProcessEnv { - return { - ...process.env, - GIT_AUTHOR_NAME: "DeepCode Test", - GIT_AUTHOR_EMAIL: "deepcode-test@example.com", - GIT_COMMITTER_NAME: "DeepCode Test", - GIT_COMMITTER_EMAIL: "deepcode-test@example.com", - }; -} - function createSessionManager(projectRoot: string, machineId: string): SessionManager { return new SessionManager({ projectRoot, From 683a51106b1d9faa8d58811da80f5857eb641934 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Fri, 22 May 2026 21:41:14 +0800 Subject: [PATCH 114/129] feat: implement the permission system --- docs/issue_0522.md | 241 +++++++++++++ src/common/permissions.ts | 464 ++++++++++++++++++++++++++ src/prompt.ts | 23 +- src/session.ts | 229 +++++++++++-- src/settings.ts | 97 ++++++ src/tests/permissions.test.ts | 120 +++++++ src/tests/prompt.test.ts | 13 + src/tests/session.test.ts | 192 +++++++++++ src/tests/settings-and-notify.test.ts | 29 ++ src/ui/App.tsx | 74 +++- src/ui/PermissionPrompt.tsx | 229 +++++++++++++ src/ui/PromptInput.tsx | 4 +- templates/tools/bash.md | 28 +- 13 files changed, 1719 insertions(+), 24 deletions(-) create mode 100644 docs/issue_0522.md create mode 100644 src/common/permissions.ts create mode 100644 src/tests/permissions.test.ts create mode 100644 src/ui/PermissionPrompt.tsx diff --git a/docs/issue_0522.md b/docs/issue_0522.md new file mode 100644 index 0000000..2e9fd1a --- /dev/null +++ b/docs/issue_0522.md @@ -0,0 +1,241 @@ +# Deep Code Permission System (设计文档) + +scopes是枚举值,列表如下: + +``` +# PermissionScope +read-in-cwd +read-out-cwd +write-in-cwd +write-out-cwd +delete-in-cwd +delete-out-cwd +query-git-log +mutate-git-log +network +mcp +``` + +settings.json的配置项(例子): + +``` +{ + "permissions": { + "allow": [ + "write-in-cwd" + ], + "deny": [ + "write-out-cwd" + ], + "ask": [ + "read-out-cwd" + ], + "defaultMode": "allowAll|askAll" // 默认是allowAll + } +} +``` + +工具和PermissionScope可能的对应关系: + +- read: read-in-cwd, read-out-cwd +- write: write-in-cwd, write-out-cwd +- edit: write-in-cwd, write-out-cwd +- WebSearch: network +- mcp__*: mcp +- bash: 每一次bash命令需要的scope在sideEffects字段中。如果sideEffects字段为undefined|null,或者sideEffects包含了"unknown"则总是ask +- 其他: 无权限要求,总是允许 + +## bash tool的参数schema新增sideEffects字段 + +目标:让LLM在每一次调用`bash`时显式声明该命令可能需要的权限范围,后端只信任这个结构化字段,不从自然语言`description`中推断权限。 + +需要同步修改两处schema: + +1. `src/prompt.ts`里的`getTools()`内置`bash`工具定义。 +2. `templates/tools/bash.md`里的`bash`工具说明和JSON schema示例。 + +新增字段: + +``` +sideEffects: PermissionScope[] | ["unknown"] +``` + +`bash`可声明的scope只包含文件系统、Git历史和网络权限,不包含`mcp`: + +``` +read-in-cwd +read-out-cwd +write-in-cwd +write-out-cwd +delete-in-cwd +delete-out-cwd +query-git-log +mutate-git-log +network +unknown +``` + +建议schema如下: + +```json +{ + "type": "object", + "properties": { + "command": { + "description": "The command to execute", + "type": "string" + }, + "description": { + "description": "Clear, concise description of what this command does in active voice.", + "type": "string" + }, + "sideEffects": { + "description": "Permission scopes required by this bash command. Use [] only for commands that do not read, write, delete, or access the network. Use [\"unknown\"] when the effects cannot be classified safely.", + "type": "array", + "items": { + "type": "string", + "enum": [ + "read-in-cwd", + "read-out-cwd", + "write-in-cwd", + "write-out-cwd", + "delete-in-cwd", + "delete-out-cwd", + "query-git-log", + "mutate-git-log", + "network", + "unknown" + ] + }, + "uniqueItems": true + } + }, + "required": [ + "command", + "sideEffects" + ], + "additionalProperties": false +} +``` + +字段语义: + +- `sideEffects: []`表示命令不需要权限,例如`date`、`node --version`这类只读取进程环境或输出版本信息的命令。 +- `sideEffects`必须按最小必要权限填写;例如`rg foo src`是`["read-in-cwd"]`,`npm install`通常是`["write-in-cwd", "network"]`。 +- 如果命令访问项目目录之外的路径,需要使用`*-out-cwd`;例如`cat /etc/hosts`是`["read-out-cwd"]`。 +- 删除类操作使用`delete-*`;如果同一条命令还会写入其他文件,再同时声明对应的`write-*`。 +- 查询Git历史使用`query-git-log`;例如`git log`、`git show HEAD`、`git blame`、`git diff HEAD~1..HEAD`这类读取提交历史、提交对象或历史diff的命令。 +- 修改Git历史或引用使用`mutate-git-log`;例如`git commit`、`git reset`、`git rebase`、`git merge`、`git cherry-pick`、`git tag`这类会创建提交、移动引用或改写提交图的命令。 +- Git命令如果同时读写工作区文件,也需要同时声明文件系统scope;例如`git checkout -- src/foo.ts`需要`["write-in-cwd"]`,`git reset --hard HEAD~1`需要`["write-in-cwd", "mutate-git-log"]`。 +- `unknown`只能单独出现为`["unknown"]`,不能和其他scope混用。 + +示例: + +```json +{ "command": "date", "description": "Show current date", "sideEffects": [] } +{ "command": "rg \"TODO\" src", "description": "Search TODO markers in source files", "sideEffects": ["read-in-cwd"] } +{ "command": "npm install", "description": "Install package dependencies", "sideEffects": ["write-in-cwd", "network"] } +{ "command": "rm -rf dist", "description": "Delete build output directory", "sideEffects": ["delete-in-cwd"] } +{ "command": "curl -s https://example.com", "description": "Fetch example.com response", "sideEffects": ["network"] } +{ "command": "git show --stat HEAD", "description": "Show file statistics for HEAD", "sideEffects": ["query-git-log"] } +{ "command": "git blame src/prompt.ts", "description": "Show line authorship for prompt source", "sideEffects": ["read-in-cwd", "query-git-log"] } +{ "command": "git reset --hard HEAD~1", "description": "Reset branch and worktree to previous commit", "sideEffects": ["write-in-cwd", "mutate-git-log"] } +``` + +## 核心数据结构设计 + +``` +export type UserPromptContent = { + text?: string; + imageUrls?: string[]; + skills?: SkillInfo[]; ++ permissions?: [{toolCallId: "...", permission: "allow|deny"}]; ++ alwaysAllows?: [""]; +}; + +export type SessionEntry = { + id: string; + ... + toolCalls: unknown[] | null; // 例如:[{"id":"...","function":{"name":"bash","arguments":"{\"command\": \"...\", \"description\": \"...\"}"}}] + status: SessionStatus; ++ askPermissions?: [{toolCallId: "...", scopes: [""], name: "...", command: "...", description?: "..."}]; +}; + +export type SessionStatus = "... | "completed" | "interrupted" | "ask_permission"; // 新增 ask_permission 状态 + +export type SessionMessage = { + ... + meta?: MessageMeta; + ... +}; + +export type MessageMeta = { + ... ++ permissions?: [{toolCallId: "...", permission: "allow|deny|ask"}]; ++ userPrompt?: UserPromptContent; //对于role为user的消息,持久化userPrompt可方便后续排查问题 +}; +``` + +## 前端流程 + +如果当前会话状态不是ask_permission,则保持现状。会话状态是ask_permission时: + +对SessionEntry.askPermissions中每一个toolCallId的每一个scope,显示权限弹窗(示例): + +``` + + + + + + Do you want to proceed? + ❯ 1. Yes + 2. Yes, and always allow + 3. No +``` + +注意对于read/write/edit的``,格式可以是"工具名称+相对或绝对文件路径",例如:`read ~/dev/main.c` + +如果在权限弹窗过程中,用户按Esc,则走现有的interrupt流程(会话状态也应该变成"interrupted")。 + +提醒注意一种情况:例如askPermissions里面有好几个item的scopes是`["write-in-cwd"]`,如果用户已经在第一个权限弹窗选了"always allow write in CWD `~/dev/qrcode_test/`",则后面的几个scopes是`["write-in-cwd"]`的item就不用显示权限弹窗了。 + +如果用户完成了所有权限弹窗的选择,则判断: + +1. 如果用户提交的结果中包含deny,则需要用户输入user prompt,按回车手动提交replySession()。 + - 如果用户没有输入user prompt就退出了,或者切换到了其他会话。则重新开始这个会话时,由于会话状态还是ask_permission,则会重新显示权限弹窗,要求用户选择。 +2. 如果用户提交的结果中不包含deny,则以`/continue`作为UserPromptContent.text内容,前端自动提交replySession()。 + + +## 后端流程 + +后端主要是对replySession()和activateSession()进行升级: + +1. 支持传入UserPromptContent.permissions和alwaysAllows +2. 如果UserPromptContent.alwaysAllows非空,将其中的scopes追加写入项目级别的settings.json配置文件(`permissions.allow`字段),避免重复写入已存在的项。 +3. 检查当前会话消息列表末尾是否存在连续的role为assistant的有tool_calls的消息,也就是"待执行消息"。如果没有,则走现有流程。 +4. 对于每一条待执行消息,先检查UserPromptContent.permissions中对应的toolCallId的用户授权是allow还是deny + - 如果是allow,则正常执行这个toolCall + - 如果是deny,则直接返回失败结果,报错信息提示LLM用户禁用相关权限。例如: + ``` + { + "ok": false, + "name": "edit", + "error": "用户已禁用了在项目目录之外修改文件的权限,请不要尝试用任何方式修改目录之外的文件" + } + ``` +5. 如果对于某条待执行消息,在UserPromptContent.permissions没有出现对应的toolCallId的用户授权,则检查它的 SessionMessage.meta.permissions[].permission 是allow还是deny还是ask + - 如果是allow,则正常执行这个toolCall + - 如果是deny,则直接返回失败结果,报错信息提示LLM用户禁用相关权限 + - 如果是ask,则直接返回失败结果,报错信息提示LLM用户未授权执行。例如: + ``` + { + "ok": false, + "name": "edit", + "error": "用户暂未授权执行,如果有必要,可重新尝试执行" + } + ``` + - 如果不存在,则正常执行这个toolCall(兼容老版本会话数据) +6. 当LLM返回了新的待执行消息时,不要立即执行,而是: + 1. 根据配置的permissions和defaultMode,计算出SessionMessage.meta.permissions字段 + 2. 如果存在一个待执行消息的SessionMessage.meta.permissions[].permission是ask,则把SessionEntry.status设置为"ask_permission",并设置好SessionEntry.askPermissions,然后退出activateSession,这样就回到了上面的前端流程。 diff --git a/src/common/permissions.ts b/src/common/permissions.ts new file mode 100644 index 0000000..e9aae01 --- /dev/null +++ b/src/common/permissions.ts @@ -0,0 +1,464 @@ +import * as fs from "fs"; +import * as path from "path"; +import type { DeepcodingSettings, PermissionScope, PermissionSettings } from "../settings"; +import { isAbsoluteFilePath, normalizeFilePath } from "./state"; + +export type BashPermissionScope = Exclude | "unknown"; + +export type PermissionDecision = "allow" | "deny" | "ask"; + +export type UserToolPermission = { + toolCallId: string; + permission: "allow" | "deny"; +}; + +export type MessageToolPermission = { + toolCallId: string; + permission: PermissionDecision; +}; + +export type AskPermissionScope = PermissionScope | "unknown"; + +export type AskPermissionRequest = { + toolCallId: string; + scopes: AskPermissionScope[]; + name: string; + command: string; + description?: string; +}; + +export type PermissionToolCall = { + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; +}; + +export type PermissionToolExecution = { + toolCallId: string; + content: string; + result: { + ok: boolean; + name: string; + output?: string; + error?: string; + metadata?: Record; + awaitUserResponse?: boolean; + followUpMessages?: Array<{ role: "system"; content: string; contentParams?: unknown | null }>; + }; +}; + +export type PermissionPlan = { + permissions: MessageToolPermission[]; + askPermissions: AskPermissionRequest[]; +}; + +export type ComputeToolCallPermissionsOptions = { + sessionId: string; + projectRoot: string; + toolCalls: unknown[]; + settings?: Required; + resolveSnippetPath?: (sessionId: string, snippetId: string) => string | null | undefined; +}; + +export function parseToolCallForPermissions(toolCall: unknown): PermissionToolCall | null { + if (!toolCall || typeof toolCall !== "object") { + return null; + } + const record = toolCall as { + id?: unknown; + type?: unknown; + function?: { name?: unknown; arguments?: unknown }; + }; + if (typeof record.id !== "string" || !record.function || typeof record.function !== "object") { + return null; + } + if (typeof record.function.name !== "string") { + return null; + } + return { + id: record.id, + type: "function", + function: { + name: record.function.name, + arguments: typeof record.function.arguments === "string" ? record.function.arguments : "", + }, + }; +} + +export function buildPermissionToolExecution( + toolCall: PermissionToolCall, + options: { + permissionOverrides?: UserToolPermission[]; + messagePermissions?: MessageToolPermission[]; + } +): PermissionToolExecution | null { + const permission = resolveToolCallPermission(toolCall.id, options); + if (permission === "allow") { + return null; + } + if (permission === "deny") { + return buildSyntheticToolExecution( + toolCall, + "User denied the required permission for this tool call. Do not try to bypass this decision." + ); + } + return buildSyntheticToolExecution( + toolCall, + "The user has not authorized this tool call yet. Retry only if the permission is still necessary." + ); +} + +export function resolveToolCallPermission( + toolCallId: string, + options: { + permissionOverrides?: UserToolPermission[]; + messagePermissions?: MessageToolPermission[]; + } +): PermissionDecision { + const override = options.permissionOverrides?.find((item) => item.toolCallId === toolCallId); + if (override?.permission === "allow" || override?.permission === "deny") { + return override.permission; + } + const messagePermission = options.messagePermissions?.find((item) => item.toolCallId === toolCallId); + if ( + messagePermission?.permission === "allow" || + messagePermission?.permission === "deny" || + messagePermission?.permission === "ask" + ) { + return messagePermission.permission; + } + return "allow"; +} + +export function buildSyntheticToolExecution(toolCall: PermissionToolCall, error: string): PermissionToolExecution { + const result = { + ok: false, + name: toolCall.function.name, + error, + }; + return { + toolCallId: toolCall.id, + content: JSON.stringify(result, null, 2), + result, + }; +} + +export function computeToolCallPermissions(options: ComputeToolCallPermissionsOptions): PermissionPlan { + const permissions: MessageToolPermission[] = []; + const askPermissions: AskPermissionRequest[] = []; + + for (const rawToolCall of options.toolCalls) { + const toolCall = parseToolCallForPermissions(rawToolCall); + if (!toolCall) { + continue; + } + const request = describeToolPermissionRequest({ + sessionId: options.sessionId, + projectRoot: options.projectRoot, + toolCall, + resolveSnippetPath: options.resolveSnippetPath, + }); + const permission = evaluatePermissionScopes(request.scopes, options.settings); + permissions.push({ toolCallId: toolCall.id, permission }); + if (permission === "ask") { + askPermissions.push({ + toolCallId: toolCall.id, + scopes: request.scopes, + name: request.name, + command: request.command, + description: request.description, + }); + } + } + + return { permissions, askPermissions }; +} + +export function describeToolPermissionRequest(options: { + sessionId: string; + projectRoot: string; + toolCall: PermissionToolCall; + resolveSnippetPath?: (sessionId: string, snippetId: string) => string | null | undefined; +}): AskPermissionRequest { + const name = options.toolCall.function.name; + const args = parseToolArgumentsForPermissions(options.toolCall.function.arguments); + + if (name === "read" || name === "Read") { + const filePath = typeof args.file_path === "string" ? args.file_path : ""; + return { + toolCallId: options.toolCall.id, + name, + command: formatToolPathCommand("read", filePath), + scopes: filePath ? [isPathInProject(options.projectRoot, filePath) ? "read-in-cwd" : "read-out-cwd"] : [], + }; + } + + if (name === "write" || name === "Write") { + const filePath = typeof args.file_path === "string" ? args.file_path : ""; + return { + toolCallId: options.toolCall.id, + name, + command: formatToolPathCommand("write", filePath), + scopes: filePath ? [isPathInProject(options.projectRoot, filePath) ? "write-in-cwd" : "write-out-cwd"] : [], + }; + } + + if (name === "edit" || name === "Edit") { + const filePath = resolveEditPermissionPath(options.sessionId, args, options.resolveSnippetPath); + return { + toolCallId: options.toolCall.id, + name, + command: formatToolPathCommand("edit", filePath), + scopes: filePath + ? [isPathInProject(options.projectRoot, filePath) ? "write-in-cwd" : "write-out-cwd"] + : ["write-out-cwd"], + }; + } + + if (name === "bash" || name === "Bash") { + const command = typeof args.command === "string" ? args.command : "bash"; + const description = typeof args.description === "string" ? args.description : undefined; + return { + toolCallId: options.toolCall.id, + name: "bash", + command, + description, + scopes: parseBashSideEffects(args.sideEffects), + }; + } + + if (name === "WebSearch") { + const query = typeof args.query === "string" ? args.query : "WebSearch"; + return { + toolCallId: options.toolCall.id, + name, + command: query, + scopes: ["network"], + }; + } + + if (name.startsWith("mcp__")) { + return { + toolCallId: options.toolCall.id, + name, + command: name, + scopes: ["mcp"], + }; + } + + return { + toolCallId: options.toolCall.id, + name, + command: name, + scopes: [], + }; +} + +export function evaluatePermissionScopes( + scopes: AskPermissionScope[], + settings: Required = { + allow: [], + deny: [], + ask: [], + defaultMode: "allowAll", + } +): PermissionDecision { + if (scopes.includes("unknown")) { + return "ask"; + } + if (scopes.length === 0) { + return "allow"; + } + const permissionScopes = scopes.filter((scope): scope is PermissionScope => scope !== "unknown"); + if (permissionScopes.some((scope) => settings.deny.includes(scope))) { + return "deny"; + } + if (permissionScopes.some((scope) => settings.ask.includes(scope))) { + return "ask"; + } + if (permissionScopes.every((scope) => settings.allow.includes(scope))) { + return "allow"; + } + return settings.defaultMode === "askAll" ? "ask" : "allow"; +} + +export function parseBashSideEffects(value: unknown): AskPermissionScope[] { + const validScopes = new Set([ + "read-in-cwd", + "read-out-cwd", + "write-in-cwd", + "write-out-cwd", + "delete-in-cwd", + "delete-out-cwd", + "query-git-log", + "mutate-git-log", + "network", + "unknown", + ]); + if (!Array.isArray(value)) { + return ["unknown"]; + } + const scopes: AskPermissionScope[] = []; + for (const item of value) { + if (typeof item !== "string" || !validScopes.has(item as AskPermissionScope)) { + return ["unknown"]; + } + const scope = item as AskPermissionScope; + if (!scopes.includes(scope)) { + scopes.push(scope); + } + } + if (scopes.includes("unknown")) { + return ["unknown"]; + } + return scopes; +} + +export function parseToolArgumentsForPermissions(rawArguments: string): Record { + if (!rawArguments) { + return {}; + } + try { + const parsed = JSON.parse(rawArguments); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record) : {}; + } catch { + return {}; + } +} + +export function resolveEditPermissionPath( + sessionId: string, + args: Record, + resolveSnippetPath?: (sessionId: string, snippetId: string) => string | null | undefined +): string { + const filePath = typeof args.file_path === "string" ? args.file_path : ""; + if (filePath) { + return filePath; + } + const snippetId = typeof args.snippet_id === "string" ? args.snippet_id : ""; + return snippetId ? (resolveSnippetPath?.(sessionId, snippetId) ?? "") : ""; +} + +export function formatToolPathCommand(toolName: string, filePath: string): string { + return filePath ? `${toolName} ${filePath}` : toolName; +} + +export function isPathInProject(projectRoot: string, filePath: string): boolean { + const normalized = normalizeFilePath(filePath); + const absolutePath = isAbsoluteFilePath(normalized) ? normalized : path.resolve(projectRoot, normalized); + const relative = path.relative(path.resolve(projectRoot), path.resolve(absolutePath)); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); +} + +export function hasUserPermissionReplies(value: { permissions?: unknown; alwaysAllows?: unknown }): boolean { + return Boolean( + (Array.isArray(value.permissions) && value.permissions.length > 0) || + (Array.isArray(value.alwaysAllows) && value.alwaysAllows.length > 0) + ); +} + +export function appendProjectPermissionAllows(projectRoot: string, scopes: PermissionScope[] | undefined): void { + if (!Array.isArray(scopes) || scopes.length === 0) { + return; + } + const validScopes = new Set([ + "read-in-cwd", + "read-out-cwd", + "write-in-cwd", + "write-out-cwd", + "delete-in-cwd", + "delete-out-cwd", + "query-git-log", + "mutate-git-log", + "network", + "mcp", + ]); + const nextScopes = scopes.filter((scope) => validScopes.has(scope)); + if (nextScopes.length === 0) { + return; + } + const settingsPath = path.join(projectRoot, ".deepcode", "settings.json"); + let settings: DeepcodingSettings = {}; + try { + if (fs.existsSync(settingsPath)) { + const parsed = JSON.parse(fs.readFileSync(settingsPath, "utf8")); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { + settings = parsed as DeepcodingSettings; + } + } + } catch { + settings = {}; + } + const currentAllow = Array.isArray(settings.permissions?.allow) ? settings.permissions.allow : []; + const allow = [...currentAllow]; + for (const scope of nextScopes) { + if (!allow.includes(scope)) { + allow.push(scope); + } + } + if (allow.length === currentAllow.length) { + return; + } + fs.mkdirSync(path.dirname(settingsPath), { recursive: true }); + fs.writeFileSync( + settingsPath, + `${JSON.stringify( + { + ...settings, + permissions: { + ...(settings.permissions ?? {}), + allow, + }, + }, + null, + 2 + )}\n`, + "utf8" + ); +} + +export function normalizeAskPermissions(value: unknown): AskPermissionRequest[] | undefined { + if (!Array.isArray(value)) { + return undefined; + } + const result: AskPermissionRequest[] = []; + for (const item of value) { + if (!item || typeof item !== "object") { + continue; + } + const record = item as Record; + if (typeof record.toolCallId !== "string" || typeof record.name !== "string") { + continue; + } + const scopes = Array.isArray(record.scopes) + ? record.scopes.filter((scope): scope is AskPermissionScope => isAskPermissionScope(scope)) + : []; + result.push({ + toolCallId: record.toolCallId, + scopes, + name: record.name, + command: typeof record.command === "string" ? record.command : record.name, + description: typeof record.description === "string" ? record.description : undefined, + }); + } + return result.length > 0 ? result : undefined; +} + +export function isAskPermissionScope(value: unknown): value is AskPermissionScope { + return ( + value === "read-in-cwd" || + value === "read-out-cwd" || + value === "write-in-cwd" || + value === "write-out-cwd" || + value === "delete-in-cwd" || + value === "delete-out-cwd" || + value === "query-git-log" || + value === "mutate-git-log" || + value === "network" || + value === "mcp" || + value === "unknown" + ); +} diff --git a/src/prompt.ts b/src/prompt.ts index 717991b..ba9bf23 100644 --- a/src/prompt.ts +++ b/src/prompt.ts @@ -331,8 +331,29 @@ export function getTools(_options: PromptToolOptions = {}, externalTools: ToolDe description: 'Clear, concise description of what this command does in active voice. Never use words like "complex" or "risk" in the description - just describe what it does.', }, + sideEffects: { + description: + 'Permission scopes required by this bash command. Use [] only for commands that do not read, write, delete, or access the network. Use ["unknown"] when the effects cannot be classified safely.', + type: "array", + items: { + type: "string", + enum: [ + "read-in-cwd", + "read-out-cwd", + "write-in-cwd", + "write-out-cwd", + "delete-in-cwd", + "delete-out-cwd", + "query-git-log", + "mutate-git-log", + "network", + "unknown", + ], + }, + uniqueItems: true, + }, }, - required: ["command"], + required: ["command", "sideEffects"], additionalProperties: false, }, }, diff --git a/src/session.ts b/src/session.ts index 3144f88..c5da055 100644 --- a/src/session.ts +++ b/src/session.ts @@ -22,13 +22,38 @@ import { type CreateOpenAIClient, type ProcessTimeoutControl, type ProcessTimeoutInfo, + type ToolCallExecution, + type ToolExecutionHooks, } from "./tools/executor"; import { McpManager } from "./mcp/mcp-manager"; -import type { McpServerConfig } from "./settings"; +import type { McpServerConfig, PermissionScope, PermissionSettings } from "./settings"; import { logApiError } from "./common/error-logger"; import { logOpenAIChatCompletionDebug, normalizeDebugError } from "./common/debug-logger"; import { killProcessTree } from "./common/process-tree"; import { GitFileHistory } from "./common/file-history"; +import { getSnippet } from "./common/state"; +import { + appendProjectPermissionAllows, + buildPermissionToolExecution, + computeToolCallPermissions, + hasUserPermissionReplies, + normalizeAskPermissions, + parseToolCallForPermissions, + type AskPermissionRequest, + type MessageToolPermission, + type PermissionToolCall, + type UserToolPermission, +} from "./common/permissions"; + +export type { PermissionScope } from "./settings"; +export type { + AskPermissionRequest, + AskPermissionScope, + BashPermissionScope, + MessageToolPermission, + PermissionDecision, + UserToolPermission, +} from "./common/permissions"; const MAX_SESSION_ENTRIES = 50; const DEFAULT_NEW_PROMPT_API_URL = "https://deepcode.vegamo.cn/api/plugin/new"; @@ -127,7 +152,14 @@ function getTotalTokens(usage: ModelUsage | null | undefined): number { return typeof totalTokens === "number" ? totalTokens : 0; } -export type SessionStatus = "failed" | "pending" | "processing" | "waiting_for_user" | "completed" | "interrupted"; +export type SessionStatus = + | "failed" + | "pending" + | "processing" + | "waiting_for_user" + | "completed" + | "interrupted" + | "ask_permission"; export type ModelUsage = { prompt_tokens: number; @@ -170,6 +202,7 @@ export type SessionEntry = { createTime: string; updateTime: string; processes: Map | null; // {pid: process info} + askPermissions?: AskPermissionRequest[]; }; export type SessionsIndex = { @@ -188,6 +221,8 @@ export type MessageMeta = { isSummary?: boolean; isModelChange?: boolean; skill?: SkillInfo; + permissions?: MessageToolPermission[]; + userPrompt?: UserPromptContent; }; export type SessionMessage = { @@ -216,6 +251,8 @@ export type UserPromptContent = { text?: string; imageUrls?: string[]; skills?: SkillInfo[]; + permissions?: UserToolPermission[]; + alwaysAllows?: PermissionScope[]; }; export type SkillInfo = { @@ -228,7 +265,12 @@ export type SkillInfo = { type SessionManagerOptions = { projectRoot: string; createOpenAIClient: CreateOpenAIClient; - getResolvedSettings: () => { model: string; webSearchTool?: string; mcpServers?: Record }; + getResolvedSettings: () => { + model: string; + webSearchTool?: string; + mcpServers?: Record; + permissions?: Required; + }; renderMarkdown: (text: string) => string; onAssistantMessage: (message: SessionMessage, shouldConnect: boolean) => void; onSessionEntryUpdated?: (entry: SessionEntry) => void; @@ -253,6 +295,7 @@ export class SessionManager { model: string; webSearchTool?: string; mcpServers?: Record; + permissions?: Required; }; private readonly onAssistantMessage: (message: SessionMessage, shouldConnect: boolean) => void; private readonly onSessionEntryUpdated?: (entry: SessionEntry) => void; @@ -1002,11 +1045,13 @@ ${skillMd} async replySession(sessionId: string, userPrompt: UserPromptContent, controller?: AbortController): Promise { const signal = controller?.signal; this.throwIfAborted(signal); + appendProjectPermissionAllows(this.projectRoot, userPrompt.alwaysAllows); const now = new Date().toISOString(); const updated = this.updateSessionEntry(sessionId, (entry) => ({ ...entry, status: "pending", failReason: null, + askPermissions: undefined, updateTime: now, })); @@ -1015,9 +1060,15 @@ ${skillMd} return; } + if (hasUserPermissionReplies(userPrompt) && this.hasTrailingPendingToolCalls(sessionId)) { + this.activeSessionId = sessionId; + await this.activateSession(sessionId, controller, userPrompt); + return; + } + if (this.isContinuePrompt(userPrompt)) { this.activeSessionId = sessionId; - await this.activateSession(sessionId, controller); + await this.activateSession(sessionId, controller, userPrompt); return; } @@ -1070,7 +1121,11 @@ ${skillMd} ); } - async activateSession(sessionId: string, controller?: AbortController): Promise { + async activateSession( + sessionId: string, + controller?: AbortController, + permissionPrompt?: UserPromptContent + ): Promise { const startedAt = Date.now(); const { client, model, baseURL, thinkingEnabled, reasoningEffort, debugLogEnabled, notify, env } = this.createOpenAIClient(); @@ -1129,16 +1184,20 @@ ${skillMd} return; } - const pendingToolCalls = this.getTrailingPendingToolCalls(this.listSessionMessages(sessionId)); - if (pendingToolCalls.length > 0) { - const toolAppendResult = await this.appendToolMessages(sessionId, pendingToolCalls); + const pendingToolCallMessage = this.getTrailingPendingToolCallMessage(this.listSessionMessages(sessionId)); + if (pendingToolCallMessage.toolCalls.length > 0) { + const toolAppendResult = await this.appendToolMessages(sessionId, pendingToolCallMessage.toolCalls, { + permissionOverrides: permissionPrompt?.permissions, + messagePermissions: pendingToolCallMessage.message?.meta?.permissions, + }); + permissionPrompt = await this.appendDeferredPermissionPrompt(sessionId, permissionPrompt, sessionController); if (this.isInterrupted(sessionId)) { return; } if (toolAppendResult.waitingForUser) { this.updateSessionEntry(sessionId, (entry) => ({ ...entry, - toolCalls: pendingToolCalls, + toolCalls: pendingToolCallMessage.toolCalls, status: "waiting_for_user", updateTime: new Date().toISOString(), })); @@ -1192,12 +1251,47 @@ ${skillMd} return; } const assistantMessage = this.buildAssistantMessage(sessionId, content, toolCalls, thinking); + const permissionPlan = toolCalls + ? computeToolCallPermissions({ + sessionId, + projectRoot: this.projectRoot, + toolCalls, + settings: this.getResolvedSettings().permissions, + resolveSnippetPath: (id, snippetId) => getSnippet(id, snippetId)?.filePath, + }) + : null; + if (permissionPlan) { + assistantMessage.meta = { + ...(assistantMessage.meta ?? {}), + permissions: permissionPlan.permissions, + }; + } this.appendSessionMessage(sessionId, assistantMessage); this.onAssistantMessage(assistantMessage, true); let waitingForUser = false; + const responseUsage = response.usage ?? null; if (toolCalls) { - const toolAppendResult = await this.appendToolMessages(sessionId, toolCalls); + if (permissionPlan?.askPermissions.length) { + this.updateSessionEntry(sessionId, (entry) => ({ + ...entry, + assistantReply: content, + assistantThinking: thinking, + assistantRefusal: refusal, + toolCalls, + usage: accumulateUsage(entry.usage, responseUsage), + usagePerModel: accumulateUsagePerModel(entry.usagePerModel, model, responseUsage), + activeTokens: getTotalTokens(responseUsage), + status: "ask_permission", + failReason: null, + askPermissions: permissionPlan.askPermissions, + updateTime: new Date().toISOString(), + })); + return; + } + const toolAppendResult = await this.appendToolMessages(sessionId, toolCalls, { + messagePermissions: permissionPlan?.permissions, + }); waitingForUser = toolAppendResult.waitingForUser; } @@ -1205,7 +1299,6 @@ ${skillMd} return; } - const responseUsage = response.usage ?? null; this.updateSessionEntry(sessionId, (entry) => ({ ...entry, assistantReply: content, @@ -1217,6 +1310,7 @@ ${skillMd} activeTokens: getTotalTokens(responseUsage), status: refusal ? "failed" : waitingForUser ? "waiting_for_user" : toolCalls ? "processing" : "completed", failReason: refusal ? refusal : entry.failReason, + askPermissions: undefined, updateTime: new Date().toISOString(), })); @@ -1768,6 +1862,7 @@ ${skillMd} visible: true, createTime: now, updateTime: now, + meta: { userPrompt: this.cloneUserPromptForMeta(prompt) }, checkpointHash: this.getCurrentCheckpointHash(sessionId), }; } @@ -1957,8 +2052,15 @@ ${skillMd} }; } - private async appendToolMessages(sessionId: string, toolCalls: unknown[]): Promise<{ waitingForUser: boolean }> { - const toolExecutions = await this.toolExecutor.executeToolCalls(sessionId, toolCalls, { + private async appendToolMessages( + sessionId: string, + toolCalls: unknown[], + options: { + permissionOverrides?: UserToolPermission[]; + messagePermissions?: MessageToolPermission[]; + } = {} + ): Promise<{ waitingForUser: boolean }> { + const hooks: ToolExecutionHooks = { onProcessStart: (pid, command) => this.addSessionProcess(sessionId, pid, command), onProcessExit: (pid) => this.removeSessionProcess(sessionId, pid), onProcessStdout: (pid, chunk) => this.onProcessStdout?.(Number(pid), chunk), @@ -1966,7 +2068,23 @@ ${skillMd} onBeforeFileMutation: (filePath) => this.prepareFileMutationCheckpoint(sessionId, filePath), onAfterFileMutation: (filePath) => this.recordFileMutationCheckpoint(sessionId, filePath), shouldStop: () => this.isInterrupted(sessionId), - }); + }; + const parsedToolCalls = toolCalls + .map((toolCall) => parseToolCallForPermissions(toolCall)) + .filter((toolCall): toolCall is PermissionToolCall => Boolean(toolCall)); + const toolExecutions: ToolCallExecution[] = []; + for (const toolCall of parsedToolCalls) { + if (hooks.shouldStop?.()) { + break; + } + const blockedResult = buildPermissionToolExecution(toolCall, options); + if (blockedResult) { + toolExecutions.push(blockedResult); + continue; + } + const executions = await this.toolExecutor.executeToolCalls(sessionId, [toolCall], hooks); + toolExecutions.push(...executions); + } if (this.isInterrupted(sessionId)) { return { waitingForUser: false }; } @@ -1997,6 +2115,72 @@ ${skillMd} return { waitingForUser }; } + private cloneUserPromptForMeta(prompt: UserPromptContent): UserPromptContent { + return { + text: prompt.text, + imageUrls: prompt.imageUrls ? [...prompt.imageUrls] : undefined, + skills: prompt.skills ? prompt.skills.map((skill) => ({ ...skill })) : undefined, + permissions: prompt.permissions ? prompt.permissions.map((permission) => ({ ...permission })) : undefined, + alwaysAllows: prompt.alwaysAllows ? [...prompt.alwaysAllows] : undefined, + }; + } + + private hasTrailingPendingToolCalls(sessionId: string): boolean { + return this.getTrailingPendingToolCallMessage(this.listSessionMessages(sessionId)).toolCalls.length > 0; + } + + private async appendDeferredPermissionPrompt( + sessionId: string, + userPrompt: UserPromptContent | undefined, + controller: AbortController + ): Promise { + if (!userPrompt || this.isContinuePrompt(userPrompt)) { + return undefined; + } + const text = userPrompt.text ?? ""; + const hasUserContent = + text.trim().length > 0 || + (Array.isArray(userPrompt.imageUrls) && userPrompt.imageUrls.length > 0) || + (Array.isArray(userPrompt.skills) && userPrompt.skills.length > 0); + if (!hasUserContent) { + return undefined; + } + this.reportNewPrompt(); + const signal = controller.signal; + const userMessage = this.buildUserMessage(sessionId, userPrompt); + this.appendSessionMessage(sessionId, userMessage); + if (userPrompt.text) { + const skills = await this.listSkills(sessionId); + const skillNames = await this.identifyMatchingSkillNames(skills, userPrompt.text, { signal, sessionId }); + this.throwIfAborted(signal); + const skillSet = new Set(skillNames); + const matchedSkill = skills.filter((skill) => skillSet.has(skill.name)); + if (Array.isArray(userPrompt.skills)) { + userPrompt.skills.push(...matchedSkill); + } else if (matchedSkill.length > 0) { + userPrompt.skills = matchedSkill; + } + } + userPrompt.skills = await this.normalizeSkills(userPrompt.skills, sessionId); + this.throwIfAborted(signal); + if (userPrompt.skills && userPrompt.skills.length > 0) { + for (const skill of userPrompt.skills) { + if (skill.isLoaded) { + continue; + } + const skillMd = fs.readFileSync(this.resolveSkillPath(skill.path), "utf8"); + const skillPrompt = `Use the skill document below to assist the user:\n +<${skill.name}-skill path="${this.resolveSkillPath(skill.path)}"> +${skillMd} +`; + const skillMessage = this.buildSkillMessage(sessionId, skillPrompt, skill); + this.appendSessionMessage(sessionId, skillMessage); + this.onAssistantMessage(skillMessage, true); + } + } + return undefined; + } + private buildOpenAIMessages( messages: SessionMessage[], thinkingEnabled: boolean, @@ -2125,18 +2309,23 @@ ${skillMd} return pairings; } - private getTrailingPendingToolCalls(messages: SessionMessage[]): unknown[] { + private getTrailingPendingToolCallMessage( + messages: SessionMessage[] + ): { message: SessionMessage; toolCalls: unknown[] } | { message: null; toolCalls: [] } { const activeMessages = messages.filter((message) => !message.compacted); const latestMessage = activeMessages[activeMessages.length - 1]; if (!latestMessage || latestMessage.role !== "assistant") { - return []; + return { message: null, toolCalls: [] }; } const toolCalls = this.getAssistantToolCalls(latestMessage); if (toolCalls.length === 0) { - return []; + return { message: null, toolCalls: [] }; } - return toolCalls.filter((toolCall) => Boolean(this.getToolCallId(toolCall))); + return { + message: latestMessage, + toolCalls: toolCalls.filter((toolCall) => Boolean(this.getToolCallId(toolCall))), + }; } private findPairableToolMessageIndex( @@ -2490,6 +2679,7 @@ ${skillMd} createTime: typeof value.createTime === "string" ? value.createTime : new Date().toISOString(), updateTime: typeof value.updateTime === "string" ? value.updateTime : new Date().toISOString(), processes: this.deserializeProcesses(value.processes), + askPermissions: normalizeAskPermissions(value.askPermissions), }; } @@ -2500,7 +2690,8 @@ ${skillMd} status === "processing" || status === "waiting_for_user" || status === "completed" || - status === "interrupted" + status === "interrupted" || + status === "ask_permission" ) { return status; } diff --git a/src/settings.ts b/src/settings.ts index b5bb869..e0b1776 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -17,6 +17,27 @@ export type McpServerConfig = { env?: Record; }; +export type PermissionScope = + | "read-in-cwd" + | "read-out-cwd" + | "write-in-cwd" + | "write-out-cwd" + | "delete-in-cwd" + | "delete-out-cwd" + | "query-git-log" + | "mutate-git-log" + | "network" + | "mcp"; + +export type PermissionDefaultMode = "allowAll" | "askAll"; + +export type PermissionSettings = { + allow?: PermissionScope[]; + deny?: PermissionScope[]; + ask?: PermissionScope[]; + defaultMode?: PermissionDefaultMode; +}; + export type DeepcodingSettings = { env?: DeepcodingEnv; model?: string; @@ -26,6 +47,7 @@ export type DeepcodingSettings = { notify?: string; webSearchTool?: string; mcpServers?: Record; + permissions?: PermissionSettings; }; export type ResolvedDeepcodingSettings = { @@ -39,6 +61,7 @@ export type ResolvedDeepcodingSettings = { notify?: string; webSearchTool?: string; mcpServers?: Record; + permissions: Required; }; export type ModelConfigSelection = { @@ -75,6 +98,79 @@ function trimString(value: unknown): string { return typeof value === "string" ? value.trim() : ""; } +const VALID_PERMISSION_SCOPES = new Set([ + "read-in-cwd", + "read-out-cwd", + "write-in-cwd", + "write-out-cwd", + "delete-in-cwd", + "delete-out-cwd", + "query-git-log", + "mutate-git-log", + "network", + "mcp", +]); + +function normalizePermissionList(value: unknown): PermissionScope[] { + if (!Array.isArray(value)) { + return []; + } + const result: PermissionScope[] = []; + for (const item of value) { + if (typeof item !== "string" || !VALID_PERMISSION_SCOPES.has(item as PermissionScope)) { + continue; + } + const scope = item as PermissionScope; + if (!result.includes(scope)) { + result.push(scope); + } + } + return result; +} + +function mergePermissionLists(...lists: Array): PermissionScope[] { + const result: PermissionScope[] = []; + for (const list of lists) { + for (const scope of list ?? []) { + if (!result.includes(scope)) { + result.push(scope); + } + } + } + return result; +} + +function normalizePermissionDefaultMode(value: unknown): PermissionDefaultMode | undefined { + return value === "allowAll" || value === "askAll" ? value : undefined; +} + +function normalizePermissions(settings: PermissionSettings | null | undefined): Required { + return { + allow: normalizePermissionList(settings?.allow), + deny: normalizePermissionList(settings?.deny), + ask: normalizePermissionList(settings?.ask), + defaultMode: normalizePermissionDefaultMode(settings?.defaultMode) ?? "allowAll", + }; +} + +function mergePermissions( + userSettings: DeepcodingSettings | null | undefined, + projectSettings: DeepcodingSettings | null | undefined +): Required { + const userPermissions = normalizePermissions(userSettings?.permissions); + const projectPermissions = normalizePermissions(projectSettings?.permissions); + return { + allow: mergePermissionLists(userPermissions.allow, projectPermissions.allow), + deny: mergePermissionLists(userPermissions.deny, projectPermissions.deny), + ask: mergePermissionLists(userPermissions.ask, projectPermissions.ask), + defaultMode: projectSettings?.permissions + ? projectPermissions.defaultMode + : userSettings?.permissions + ? userPermissions.defaultMode + : "allowAll", + }; +} + function normalizeEnv(env: DeepcodingSettings["env"]): Record { const result: Record = {}; if (!env) { @@ -233,6 +329,7 @@ export function resolveSettingsSources( notify: notify || undefined, webSearchTool: webSearchTool || undefined, mcpServers: mergeMcpServers(userSettings, projectSettings, userEnv, projectEnv, systemEnv), + permissions: mergePermissions(userSettings, projectSettings), }; } diff --git a/src/tests/permissions.test.ts b/src/tests/permissions.test.ts new file mode 100644 index 0000000..adb5388 --- /dev/null +++ b/src/tests/permissions.test.ts @@ -0,0 +1,120 @@ +import { afterEach, test } from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { + appendProjectPermissionAllows, + computeToolCallPermissions, + evaluatePermissionScopes, + hasUserPermissionReplies, + parseBashSideEffects, +} from "../common/permissions"; + +const tempDirs: string[] = []; + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) { + fs.rmSync(dir, { recursive: true, force: true }); + } + } +}); + +test("parseBashSideEffects accepts valid scopes and normalizes unsafe values to unknown", () => { + assert.deepEqual(parseBashSideEffects(["read-in-cwd", "network", "read-in-cwd"]), ["read-in-cwd", "network"]); + assert.deepEqual(parseBashSideEffects(undefined), ["unknown"]); + assert.deepEqual(parseBashSideEffects(["read-in-cwd", "unknown"]), ["unknown"]); + assert.deepEqual(parseBashSideEffects(["mcp"]), ["unknown"]); +}); + +test("evaluatePermissionScopes applies deny, ask, allow, and default mode precedence", () => { + const settings = { + allow: ["read-in-cwd" as const], + deny: ["write-out-cwd" as const], + ask: ["network" as const], + defaultMode: "askAll" as const, + }; + + assert.equal(evaluatePermissionScopes(["write-out-cwd"], settings), "deny"); + assert.equal(evaluatePermissionScopes(["network"], settings), "ask"); + assert.equal(evaluatePermissionScopes(["read-in-cwd"], settings), "allow"); + assert.equal(evaluatePermissionScopes(["write-in-cwd"], settings), "ask"); + assert.equal(evaluatePermissionScopes([], settings), "allow"); + assert.equal(evaluatePermissionScopes(["unknown"], settings), "ask"); +}); + +test("computeToolCallPermissions maps tool calls to permission requests", () => { + const projectRoot = createTempDir("deepcode-permissions-workspace-"); + const plan = computeToolCallPermissions({ + sessionId: "session-1", + projectRoot, + settings: { + allow: [], + deny: [], + ask: ["write-out-cwd", "network"], + defaultMode: "allowAll", + }, + resolveSnippetPath: () => path.join(projectRoot, "src", "file.ts"), + toolCalls: [ + { + id: "call-write", + type: "function", + function: { name: "write", arguments: JSON.stringify({ file_path: "/tmp/out.txt", content: "x" }) }, + }, + { + id: "call-bash", + type: "function", + function: { + name: "bash", + arguments: JSON.stringify({ command: "curl https://example.com", sideEffects: ["network"] }), + }, + }, + { + id: "call-edit", + type: "function", + function: { name: "edit", arguments: JSON.stringify({ snippet_id: "snippet_1" }) }, + }, + ], + }); + + assert.deepEqual(plan.permissions, [ + { toolCallId: "call-write", permission: "ask" }, + { toolCallId: "call-bash", permission: "ask" }, + { toolCallId: "call-edit", permission: "allow" }, + ]); + assert.deepEqual( + plan.askPermissions.map((item) => ({ id: item.toolCallId, scopes: item.scopes })), + [ + { id: "call-write", scopes: ["write-out-cwd"] }, + { id: "call-bash", scopes: ["network"] }, + ] + ); +}); + +test("appendProjectPermissionAllows writes unique project-level allow scopes", () => { + const projectRoot = createTempDir("deepcode-permission-settings-"); + const settingsPath = path.join(projectRoot, ".deepcode", "settings.json"); + fs.mkdirSync(path.dirname(settingsPath), { recursive: true }); + fs.writeFileSync(settingsPath, JSON.stringify({ permissions: { allow: ["read-in-cwd"] } }), "utf8"); + + appendProjectPermissionAllows(projectRoot, ["read-in-cwd", "write-in-cwd"]); + appendProjectPermissionAllows(projectRoot, ["write-in-cwd"]); + + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); + assert.deepEqual(settings.permissions.allow, ["read-in-cwd", "write-in-cwd"]); +}); + +test("hasUserPermissionReplies detects permission reply payloads", () => { + assert.equal(hasUserPermissionReplies({}), false); + assert.equal(hasUserPermissionReplies({ permissions: [] }), false); + assert.equal(hasUserPermissionReplies({ permissions: [{ toolCallId: "call-1", permission: "allow" }] }), true); + assert.equal(hasUserPermissionReplies({ alwaysAllows: ["network"] }), true); +}); + +function createTempDir(prefix: string): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} diff --git a/src/tests/prompt.test.ts b/src/tests/prompt.test.ts index cc86712..953de7c 100644 --- a/src/tests/prompt.test.ts +++ b/src/tests/prompt.test.ts @@ -19,6 +19,19 @@ test("getTools includes UpdatePlan with string plan schema", () => { assert.equal((tool.function.parameters.properties.plan as { type?: unknown }).type, "string"); }); +test("getTools requires bash sideEffects permission scopes", () => { + const tool = getTools().find((candidate) => candidate.function.name === "bash"); + assert.ok(tool); + assert.deepEqual(tool.function.parameters.required, ["command", "sideEffects"]); + const sideEffects = tool.function.parameters.properties.sideEffects as { + type?: unknown; + items?: { enum?: unknown[] }; + }; + assert.equal(sideEffects.type, "array"); + assert.equal(sideEffects.items?.enum?.includes("write-out-cwd"), true); + assert.equal(sideEffects.items?.enum?.includes("unknown"), true); +}); + test("getSystemPrompt always includes WebSearch docs", () => { const prompt = getSystemPrompt("/tmp/project"); assert.equal(prompt.includes("## WebSearch"), true); diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index 08d61e9..b3c5de9 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1256,6 +1256,162 @@ test("replySession /continue runs trailing pending tool calls before requesting ); }); +test("activateSession pauses for permission when a tool call requires ask", async () => { + const workspace = createTempDir("deepcode-permission-ask-workspace-"); + const home = createTempDir("deepcode-permission-ask-home-"); + setHomeDir(home); + + const manager = createPermissionSessionManager( + workspace, + [ + { + choices: [ + { + message: { + content: "", + tool_calls: [ + { + id: "call-bash", + type: "function", + function: { + name: "bash", + arguments: JSON.stringify({ + command: "rg TODO src", + description: "Search TODO markers", + sideEffects: ["read-in-cwd"], + }), + }, + }, + ], + }, + }, + ], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }, + ], + { + allow: [], + deny: [], + ask: [], + defaultMode: "askAll", + } + ); + + const sessionId = await manager.createSession({ text: "search todos" }); + const session = manager.getSession(sessionId); + const assistant = manager + .listSessionMessages(sessionId) + .find((message) => message.role === "assistant" && (message.messageParams as any)?.tool_calls); + + assert.equal(session?.status, "ask_permission"); + assert.equal(session?.askPermissions?.[0]?.toolCallId, "call-bash"); + assert.deepEqual(session?.askPermissions?.[0]?.scopes, ["read-in-cwd"]); + assert.deepEqual(assistant?.meta?.permissions, [{ toolCallId: "call-bash", permission: "ask" }]); + assert.equal( + manager.listSessionMessages(sessionId).some((message) => message.role === "tool"), + false + ); +}); + +test("replySession applies permission replies, runs pending tools, and stores always allow scopes", async () => { + const workspace = createTempDir("deepcode-permission-allow-workspace-"); + const home = createTempDir("deepcode-permission-allow-home-"); + setHomeDir(home); + fs.writeFileSync(path.join(workspace, "note.txt"), "allowed content\n", "utf8"); + + const manager = createPermissionSessionManager( + workspace, + [createChatResponse("continued", { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 })], + { + allow: [], + deny: [], + ask: ["read-in-cwd"], + defaultMode: "allowAll", + } + ); + const originalActivateSession = manager.activateSession.bind(manager); + (manager as any).activateSession = async () => {}; + const sessionId = await manager.createSession({ text: "first prompt" }); + const assistant = (manager as any).buildAssistantMessage( + sessionId, + "Need to read", + [ + { + id: "call-read", + type: "function", + function: { name: "read", arguments: JSON.stringify({ file_path: path.join(workspace, "note.txt") }) }, + }, + ], + null + ) as SessionMessage; + assistant.meta = { ...(assistant.meta ?? {}), permissions: [{ toolCallId: "call-read", permission: "ask" }] }; + (manager as any).appendSessionMessage(sessionId, assistant); + (manager as any).activateSession = originalActivateSession; + + await manager.replySession(sessionId, { + text: "/continue", + permissions: [{ toolCallId: "call-read", permission: "allow" }], + alwaysAllows: ["read-in-cwd"], + }); + + const toolMessage = manager.listSessionMessages(sessionId).find((message) => message.role === "tool"); + const settings = JSON.parse(fs.readFileSync(path.join(workspace, ".deepcode", "settings.json"), "utf8")); + + assert.match(toolMessage?.content ?? "", /allowed content/); + assert.deepEqual(settings.permissions.allow, ["read-in-cwd"]); + assert.equal(manager.getSession(sessionId)?.status, "completed"); +}); + +test("replySession turns denied permission replies into tool errors before appending user text", async () => { + const workspace = createTempDir("deepcode-permission-deny-workspace-"); + const home = createTempDir("deepcode-permission-deny-home-"); + setHomeDir(home); + + const manager = createPermissionSessionManager( + workspace, + [createChatResponse("handled denial", { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 })], + { + allow: [], + deny: [], + ask: ["write-out-cwd"], + defaultMode: "allowAll", + } + ); + const originalActivateSession = manager.activateSession.bind(manager); + (manager as any).activateSession = async () => {}; + const sessionId = await manager.createSession({ text: "first prompt" }); + const assistant = (manager as any).buildAssistantMessage( + sessionId, + "Need to write", + [ + { + id: "call-write", + type: "function", + function: { name: "write", arguments: JSON.stringify({ file_path: "/tmp/outside.txt", content: "x" }) }, + }, + ], + null + ) as SessionMessage; + assistant.meta = { ...(assistant.meta ?? {}), permissions: [{ toolCallId: "call-write", permission: "ask" }] }; + (manager as any).appendSessionMessage(sessionId, assistant); + (manager as any).activateSession = originalActivateSession; + + await manager.replySession(sessionId, { + text: "Do not write outside the workspace.", + permissions: [{ toolCallId: "call-write", permission: "deny" }], + }); + + const messages = manager.listSessionMessages(sessionId); + const assistantIndex = messages.findIndex((message) => message.id === assistant.id); + const toolMessage = messages[assistantIndex + 1]; + const userMessage = messages[assistantIndex + 2]; + + assert.equal(toolMessage?.role, "tool"); + assert.match(toolMessage?.content ?? "", /User denied the required permission/); + assert.equal(userMessage?.role, "user"); + assert.equal(userMessage?.content, "Do not write outside the workspace."); +}); + test("replySession preserves raw session messages when a previous tool call is pending", async () => { const workspace = createTempDir("deepcode-pending-tool-workspace-"); const home = createTempDir("deepcode-pending-tool-home-"); @@ -2315,6 +2471,42 @@ function createMockedClientSessionManager(projectRoot: string, responses: unknow }); } +function createPermissionSessionManager( + projectRoot: string, + responses: unknown[], + permissions: { + allow: any[]; + deny: any[]; + ask: any[]; + defaultMode: "allowAll" | "askAll"; + } +): SessionManager { + const client = { + chat: { + completions: { + create: async () => { + const response = responses.shift(); + assert.ok(response, "expected a queued chat response"); + return response; + }, + }, + }, + }; + + return new SessionManager({ + projectRoot, + createOpenAIClient: () => ({ + client: client as any, + model: "test-model", + baseURL: "https://api.deepseek.com", + thinkingEnabled: false, + }), + getResolvedSettings: () => ({ model: "test-model", permissions }), + renderMarkdown: (text) => text, + onAssistantMessage: () => {}, + }); +} + function createMockedClientSessionManagerWithClient(projectRoot: string, client: unknown): SessionManager { return new SessionManager({ projectRoot, diff --git a/src/tests/settings-and-notify.test.ts b/src/tests/settings-and-notify.test.ts index 1707aff..52f8671 100644 --- a/src/tests/settings-and-notify.test.ts +++ b/src/tests/settings-and-notify.test.ts @@ -147,6 +147,35 @@ test("resolveSettingsSources applies user, project, and DEEPCODE environment pre assert.equal(resolved.env.WEBHOOK, "system-webhook"); }); +test("resolveSettingsSources merges permission settings", () => { + const resolved = resolveSettingsSources( + { + permissions: { + allow: ["read-in-cwd", "network"], + ask: ["write-out-cwd"], + defaultMode: "askAll", + }, + }, + { + permissions: { + allow: ["write-in-cwd", "read-in-cwd"], + deny: ["delete-out-cwd"], + defaultMode: "allowAll", + }, + }, + { + model: "default-model", + baseURL: "https://default.example.com", + }, + TEST_PROCESS_ENV + ); + + assert.deepEqual(resolved.permissions.allow, ["read-in-cwd", "network", "write-in-cwd"]); + assert.deepEqual(resolved.permissions.ask, ["write-out-cwd"]); + assert.deepEqual(resolved.permissions.deny, ["delete-out-cwd"]); + assert.equal(resolved.permissions.defaultMode, "allowAll"); +}); + test("resolveSettingsSources merges MCP env with documented priority", () => { const resolved = resolveSettingsSources( { diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 5419a2a..c8c24f1 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -8,6 +8,7 @@ import { createOpenAIClient } from "../common/openai-client"; import { type LlmStreamProgress, type MessageMeta, + type PermissionScope, type SessionEntry, SessionManager, type SessionMessage, @@ -38,6 +39,7 @@ import { findPendingAskUserQuestion, formatAskUserQuestionAnswers, } from "./askUserQuestion"; +import { PermissionPrompt, type PermissionPromptResult } from "./PermissionPrompt"; import { buildExitSummaryText } from "./exitSummary"; import { RawMode, useRawModeContext } from "./contexts"; import { renderMessageToStdout } from "./components/MessageView/utils"; @@ -76,6 +78,12 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. const [streamProgress, setStreamProgress] = useState(null); const [runningProcesses, setRunningProcesses] = useState(null); const [activeStatus, setActiveStatus] = useState(null); + const [activeAskPermissions, setActiveAskPermissions] = useState(undefined); + const [pendingPermissionReply, setPendingPermissionReply] = useState<{ + sessionId: string; + permissions: PermissionPromptResult["permissions"]; + alwaysAllows: PermissionScope[]; + } | null>(null); const [dismissedQuestionIds, setDismissedQuestionIds] = useState>(() => new Set()); const [isExiting, setIsExiting] = useState(false); const [showWelcome, setShowWelcome] = useState(true); @@ -105,6 +113,7 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setStatusLine(buildStatusLine(entry)); setRunningProcesses(entry.processes); setActiveStatus(entry.status); + setActiveAskPermissions(entry.askPermissions); }, onLlmStreamProgress: (progress) => { if (progress.phase === "end") { @@ -214,6 +223,8 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setErrorLine(null); setRunningProcesses(null); setActiveStatus(null); + setActiveAskPermissions(undefined); + setPendingPermissionReply(null); setDismissedQuestionIds(new Set()); setShowWelcome(true); setWelcomeNonce((n) => n + 1); @@ -257,7 +268,16 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. imageUrls: submission.imageUrls, skills: submission.selectedSkills && submission.selectedSkills.length > 0 ? submission.selectedSkills : undefined, + permissions: submission.permissions, + alwaysAllows: submission.alwaysAllows, }; + const activeSessionId = sessionManager.getActiveSessionId(); + const permissionReply = + pendingPermissionReply && activeSessionId === pendingPermissionReply.sessionId ? pendingPermissionReply : null; + if (permissionReply) { + prompt.permissions = permissionReply.permissions; + prompt.alwaysAllows = permissionReply.alwaysAllows; + } const trimmedText = (submission.text ?? "").trim(); const selectedSkillNames = submission.selectedSkills?.map((skill) => skill.name).filter(Boolean) ?? []; @@ -277,6 +297,9 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. processStdoutRef.current.clear(); try { await sessionManager.handleUserPrompt(prompt); + if (permissionReply) { + setPendingPermissionReply(null); + } await refreshSkills(); refreshSessionsList(); } catch (error) { @@ -288,7 +311,7 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setRunningProcesses(null); } }, - [exit, onRestart, sessionManager, refreshSkills, refreshSessionsList] + [exit, onRestart, pendingPermissionReply, sessionManager, refreshSkills, refreshSessionsList] ); const handleInterrupt = useCallback(() => { @@ -407,9 +430,13 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setStatusLine(session ? buildStatusLine(session) : ""); setRunningProcesses(session?.processes ?? null); setActiveStatus(session?.status ?? null); + setActiveAskPermissions(session?.askPermissions); + if (pendingPermissionReply && pendingPermissionReply.sessionId !== sessionId) { + setPendingPermissionReply(null); + } await refreshSkills(sessionId); }, - [sessionManager, refreshSkills] + [pendingPermissionReply, sessionManager, refreshSkills] ); const handleUndoRestore = useCallback( @@ -605,6 +632,39 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setDismissedQuestionIds((prev) => new Set(prev).add(pendingQuestion.messageId)); }, [pendingQuestion]); + const handlePermissionResult = useCallback( + (result: PermissionPromptResult) => { + const sessionId = sessionManager.getActiveSessionId(); + if (!sessionId) { + return; + } + if (result.hasDeny) { + setPendingPermissionReply({ + sessionId, + permissions: result.permissions, + alwaysAllows: result.alwaysAllows, + }); + setStatusLine("Permission denied. Add a reply, then press Enter to continue."); + return; + } + void handlePrompt({ + text: "/continue", + imageUrls: [], + command: "continue", + permissions: result.permissions, + alwaysAllows: result.alwaysAllows, + }); + }, + [handlePrompt, sessionManager] + ); + + const handlePermissionCancel = useCallback(() => { + sessionManager.interruptActiveSession(); + setActiveStatus("interrupted"); + setActiveAskPermissions(undefined); + refreshSessionsList(); + }, [refreshSessionsList, sessionManager]); + if (mode === RawMode.Raw) { return handleRawModeChange(prev)} />; } @@ -683,6 +743,16 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. onSubmit={handleQuestionAnswers} onCancel={handleQuestionCancel} /> + ) : activeStatus === "ask_permission" && + activeAskPermissions && + activeAskPermissions.length > 0 && + !pendingPermissionReply && + !busy ? ( + ) : isExiting ? null : ( void; + onCancel: () => void; +}; + +type ScopePrompt = { + request: AskPermissionRequest; + scope: AskPermissionScope; +}; + +const ALWAYS_ALLOWED_SCOPES = new Set([ + "read-in-cwd", + "read-out-cwd", + "write-in-cwd", + "write-out-cwd", + "delete-in-cwd", + "delete-out-cwd", + "query-git-log", + "mutate-git-log", + "network", + "mcp", +]); + +export function PermissionPrompt({ requests, onSubmit, onCancel }: Props): React.ReactElement | null { + const prompts = useMemo(() => buildScopePrompts(requests), [requests]); + const [index, setIndex] = useState(0); + const [cursor, setCursor] = useState(0); + const [decisions, setDecisions] = useState>({}); + const [alwaysAllows, setAlwaysAllows] = useState([]); + + const effectiveIndex = findNextPromptIndex(prompts, index, alwaysAllows); + const prompt = prompts[effectiveIndex] ?? null; + const options = prompt ? buildOptions(prompt.scope) : []; + + useEffect(() => { + setIndex(0); + setCursor(0); + setDecisions({}); + setAlwaysAllows([]); + }, [requests]); + + useEffect(() => { + if (!prompt) { + onSubmit(buildResult(requests, decisions, alwaysAllows)); + } + }, [alwaysAllows, decisions, onSubmit, prompt, requests]); + + useEffect(() => { + if (cursor >= options.length) { + setCursor(Math.max(0, options.length - 1)); + } + }, [cursor, options.length]); + + useTerminalInput((input, key) => { + if (!prompt) { + return; + } + if (key.escape || (key.ctrl && (input === "c" || input === "C"))) { + onCancel(); + return; + } + if (key.upArrow) { + setCursor((value) => Math.max(0, value - 1)); + return; + } + if (key.downArrow) { + setCursor((value) => Math.min(options.length - 1, value + 1)); + return; + } + if (input && /^[1-3]$/.test(input)) { + const nextCursor = Number(input) - 1; + if (nextCursor >= 0 && nextCursor < options.length) { + commit(options[nextCursor]!.kind); + } + return; + } + if (key.return) { + commit(options[cursor]?.kind ?? "allow"); + } + }); + + if (!prompt) { + return null; + } + + function commit(kind: "allow" | "always" | "deny"): void { + if (!prompt) { + return; + } + if (kind === "always" && isAlwaysAllowedScope(prompt.scope)) { + const scope = prompt.scope; + setAlwaysAllows((prev) => (prev.includes(scope) ? prev : [...prev, scope])); + setDecisions((prev) => ({ + ...prev, + [prompt.request.toolCallId]: prev[prompt.request.toolCallId] === "deny" ? "deny" : "allow", + })); + } else { + setDecisions((prev) => ({ + ...prev, + [prompt.request.toolCallId]: + kind === "deny" ? "deny" : prev[prompt.request.toolCallId] === "deny" ? "deny" : "allow", + })); + } + setIndex(effectiveIndex + 1); + setCursor(0); + } + + return ( + + + + Permission required + + + {" "} + {Math.min(effectiveIndex + 1, prompts.length)}/{prompts.length} + + + {prompt.request.name} + {prompt.request.command} + {prompt.request.description ? {prompt.request.description} : null} + + Do you want to proceed? + + + {options.map((option, optionIndex) => ( + + {optionIndex === cursor ? "> " : " "} + {optionIndex + 1}. {option.label} + + ))} + + + ↑/↓ move · Enter select · Esc interrupt + + + ); +} + +function buildScopePrompts(requests: AskPermissionRequest[]): ScopePrompt[] { + const prompts: ScopePrompt[] = []; + for (const request of requests) { + for (const scope of request.scopes.length > 0 ? request.scopes : ["unknown" as const]) { + prompts.push({ request, scope }); + } + } + return prompts; +} + +function buildOptions(scope: AskPermissionScope): Array<{ kind: "allow" | "always" | "deny"; label: string }> { + const options: Array<{ kind: "allow" | "always" | "deny"; label: string }> = [{ kind: "allow", label: "Yes" }]; + if (isAlwaysAllowedScope(scope)) { + options.push({ kind: "always", label: `Yes, and always allow ${describeScope(scope)}` }); + } + options.push({ kind: "deny", label: "No" }); + return options; +} + +function findNextPromptIndex(prompts: ScopePrompt[], startIndex: number, alwaysAllows: PermissionScope[]): number { + let index = startIndex; + while (index < prompts.length) { + const scope = prompts[index]!.scope; + if (isAlwaysAllowedScope(scope) && alwaysAllows.includes(scope)) { + index += 1; + continue; + } + return index; + } + return prompts.length; +} + +function buildResult( + requests: AskPermissionRequest[], + decisions: Record, + alwaysAllows: PermissionScope[] +): PermissionPromptResult { + const permissions = requests.map((request) => ({ + toolCallId: request.toolCallId, + permission: decisions[request.toolCallId] === "deny" ? ("deny" as const) : ("allow" as const), + })); + return { + permissions, + alwaysAllows, + hasDeny: permissions.some((permission) => permission.permission === "deny"), + }; +} + +function isAlwaysAllowedScope(scope: AskPermissionScope): scope is PermissionScope { + return ALWAYS_ALLOWED_SCOPES.has(scope); +} + +function describeScope(scope: PermissionScope): string { + switch (scope) { + case "read-in-cwd": + return "reads inside this workspace"; + case "read-out-cwd": + return "reads outside this workspace"; + case "write-in-cwd": + return "writes inside this workspace"; + case "write-out-cwd": + return "writes outside this workspace"; + case "delete-in-cwd": + return "deletes inside this workspace"; + case "delete-out-cwd": + return "deletes outside this workspace"; + case "query-git-log": + return "Git history queries"; + case "mutate-git-log": + return "Git history changes"; + case "network": + return "network access"; + case "mcp": + return "MCP tool access"; + default: + return scope; + } +} diff --git a/src/ui/PromptInput.tsx b/src/ui/PromptInput.tsx index 8897fd3..8c808e9 100644 --- a/src/ui/PromptInput.tsx +++ b/src/ui/PromptInput.tsx @@ -46,7 +46,7 @@ import { } from "./fileMentions"; import type { FileMentionItem } from "./fileMentions"; import { readClipboardImageAsync } from "./clipboard"; -import type { SessionEntry, SkillInfo } from "../session"; +import type { PermissionScope, SessionEntry, SkillInfo, UserToolPermission } from "../session"; // Re-exported from prompt modules for backward compatibility export { useTerminalInput, parseTerminalInput, dispatchTerminalInput } from "./prompt"; @@ -68,6 +68,8 @@ export type PromptSubmission = { text: string; imageUrls: string[]; selectedSkills?: SkillInfo[]; + permissions?: UserToolPermission[]; + alwaysAllows?: PermissionScope[]; command?: "new" | "resume" | "continue" | "undo" | "mcp" | "exit"; }; diff --git a/templates/tools/bash.md b/templates/tools/bash.md index 0705120..e8597ab 100644 --- a/templates/tools/bash.md +++ b/templates/tools/bash.md @@ -28,6 +28,11 @@ Before executing the command, please follow these steps: Usage notes: - The command argument is required. + - The sideEffects argument is required. Declare the minimum permission scopes the command may need. + - Use `sideEffects: []` only for commands that do not read, write, delete, query Git history, mutate Git history, or access the network, such as `date` or `node --version`. + - Use `*-out-cwd` when the command accesses paths outside the current workspace. For example, `cat /etc/hosts` requires `["read-out-cwd"]`. + - Use `query-git-log` for commands such as `git log`, `git show HEAD`, `git blame`, or history diffs. Use `mutate-git-log` for commands such as `git commit`, `git reset`, `git rebase`, `git merge`, `git cherry-pick`, or `git tag`. + - Use `["unknown"]` when you cannot classify the command safely. `unknown` must appear alone. - It is very helpful if you write a clear, concise description of what this command does. For simple commands, keep it brief (5-10 words). For complex commands (piped commands, obscure flags, or anything hard to understand at a glance), add enough context to clarify what it does. - If the output exceeds 30000 characters, output will be truncated before being returned to you. - Always prefer using the dedicated tools for these commands: @@ -60,10 +65,31 @@ Usage notes: "description": { "description": "Clear, concise description of what this command does in active voice. Never use words like \"complex\" or \"risk\" in the description - just describe what it does.\n\nFor simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):\n- ls → \"List files in current directory\"\n- git status → \"Show working tree status\"\n- npm install → \"Install package dependencies\"\n\nFor commands that are harder to parse at a glance (piped commands, obscure flags, etc.), add enough context to clarify what it does:\n- find . -name \"*.tmp\" -exec rm {} \\; → \"Find and delete all .tmp files recursively\"\n- git reset --hard origin/main → \"Discard all local changes and match remote main\"\n- curl -s url | jq '.data[]' → \"Fetch JSON from URL and extract data array elements\"", "type": "string" + }, + "sideEffects": { + "description": "Permission scopes required by this bash command. Use [] only for commands that do not read, write, delete, or access the network. Use [\"unknown\"] when the effects cannot be classified safely.", + "type": "array", + "items": { + "type": "string", + "enum": [ + "read-in-cwd", + "read-out-cwd", + "write-in-cwd", + "write-out-cwd", + "delete-in-cwd", + "delete-out-cwd", + "query-git-log", + "mutate-git-log", + "network", + "unknown" + ] + }, + "uniqueItems": true } }, "required": [ - "command" + "command", + "sideEffects" ], "additionalProperties": false } From 90c6b2e7ea6c6c1e343c074c06f00c5c09391d68 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Fri, 22 May 2026 21:42:32 +0800 Subject: [PATCH 115/129] chore: update bash.md --- templates/tools/bash.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/tools/bash.md b/templates/tools/bash.md index e8597ab..83027d3 100644 --- a/templates/tools/bash.md +++ b/templates/tools/bash.md @@ -32,7 +32,7 @@ Usage notes: - Use `sideEffects: []` only for commands that do not read, write, delete, query Git history, mutate Git history, or access the network, such as `date` or `node --version`. - Use `*-out-cwd` when the command accesses paths outside the current workspace. For example, `cat /etc/hosts` requires `["read-out-cwd"]`. - Use `query-git-log` for commands such as `git log`, `git show HEAD`, `git blame`, or history diffs. Use `mutate-git-log` for commands such as `git commit`, `git reset`, `git rebase`, `git merge`, `git cherry-pick`, or `git tag`. - - Use `["unknown"]` when you cannot classify the command safely. `unknown` must appear alone. + - Use `["unknown"]` when you cannot classify the command safely. - It is very helpful if you write a clear, concise description of what this command does. For simple commands, keep it brief (5-10 words). For complex commands (piped commands, obscure flags, or anything hard to understand at a glance), add enough context to clarify what it does. - If the output exceeds 30000 characters, output will be truncated before being returned to you. - Always prefer using the dedicated tools for these commands: From 104acff28f6fdc72ee7731813c3aa6069eb73235 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Sat, 23 May 2026 00:02:13 +0800 Subject: [PATCH 116/129] feat: enhance appendProjectPermissionAllows to support inherited permissions --- .gitignore | 1 + src/common/permissions.ts | 35 ++++++++-- src/session.ts | 4 +- src/tests/permissions.test.ts | 120 ++++++++++++++++++++++++++++++++++ 4 files changed, 155 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 11b67ce..8f054d4 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ dist/ .vscode/ *.tgz *.log +.deepcode/settings.json diff --git a/src/common/permissions.ts b/src/common/permissions.ts index e9aae01..aa87e0d 100644 --- a/src/common/permissions.ts +++ b/src/common/permissions.ts @@ -360,7 +360,11 @@ export function hasUserPermissionReplies(value: { permissions?: unknown; alwaysA ); } -export function appendProjectPermissionAllows(projectRoot: string, scopes: PermissionScope[] | undefined): void { +export function appendProjectPermissionAllows( + projectRoot: string, + scopes: PermissionScope[] | undefined, + options: { inheritedPermissions?: Required } = {} +): void { if (!Array.isArray(scopes) || scopes.length === 0) { return; } @@ -392,14 +396,35 @@ export function appendProjectPermissionAllows(projectRoot: string, scopes: Permi } catch { settings = {}; } - const currentAllow = Array.isArray(settings.permissions?.allow) ? settings.permissions.allow : []; + + const existingPermissions = settings.permissions; + const permissions: PermissionSettings = existingPermissions + ? { ...existingPermissions } + : options.inheritedPermissions + ? { + allow: [...options.inheritedPermissions.allow], + deny: [...options.inheritedPermissions.deny], + ask: [...options.inheritedPermissions.ask], + defaultMode: options.inheritedPermissions.defaultMode, + } + : {}; + + const currentAllow = Array.isArray(permissions.allow) ? permissions.allow : []; const allow = [...currentAllow]; for (const scope of nextScopes) { if (!allow.includes(scope)) { allow.push(scope); } } - if (allow.length === currentAllow.length) { + const currentDeny = Array.isArray(permissions.deny) ? permissions.deny : undefined; + const currentAsk = Array.isArray(permissions.ask) ? permissions.ask : undefined; + const deny = currentDeny ? currentDeny.filter((scope) => !nextScopes.includes(scope)) : permissions.deny; + const ask = currentAsk ? currentAsk.filter((scope) => !nextScopes.includes(scope)) : permissions.ask; + const changed = + allow.length !== currentAllow.length || + (currentDeny ? (deny as PermissionScope[]).length !== currentDeny.length : false) || + (currentAsk ? (ask as PermissionScope[]).length !== currentAsk.length : false); + if (existingPermissions && !changed) { return; } fs.mkdirSync(path.dirname(settingsPath), { recursive: true }); @@ -409,7 +434,9 @@ export function appendProjectPermissionAllows(projectRoot: string, scopes: Permi { ...settings, permissions: { - ...(settings.permissions ?? {}), + ...permissions, + deny, + ask, allow, }, }, diff --git a/src/session.ts b/src/session.ts index c5da055..a8a194e 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1045,7 +1045,9 @@ ${skillMd} async replySession(sessionId: string, userPrompt: UserPromptContent, controller?: AbortController): Promise { const signal = controller?.signal; this.throwIfAborted(signal); - appendProjectPermissionAllows(this.projectRoot, userPrompt.alwaysAllows); + appendProjectPermissionAllows(this.projectRoot, userPrompt.alwaysAllows, { + inheritedPermissions: this.getResolvedSettings().permissions, + }); const now = new Date().toISOString(); const updated = this.updateSessionEntry(sessionId, (entry) => ({ ...entry, diff --git a/src/tests/permissions.test.ts b/src/tests/permissions.test.ts index adb5388..8babf11 100644 --- a/src/tests/permissions.test.ts +++ b/src/tests/permissions.test.ts @@ -106,6 +106,126 @@ test("appendProjectPermissionAllows writes unique project-level allow scopes", ( assert.deepEqual(settings.permissions.allow, ["read-in-cwd", "write-in-cwd"]); }); +test("appendProjectPermissionAllows seeds inherited permissions before adding allow scopes", () => { + const projectRoot = createTempDir("deepcode-permission-settings-default-"); + + appendProjectPermissionAllows(projectRoot, ["query-git-log"], { + inheritedPermissions: { + allow: ["read-in-cwd"], + deny: ["write-out-cwd"], + ask: ["network"], + defaultMode: "askAll", + }, + }); + + const settingsPath = path.join(projectRoot, ".deepcode", "settings.json"); + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); + assert.deepEqual(settings.permissions, { + allow: ["read-in-cwd", "query-git-log"], + deny: ["write-out-cwd"], + ask: ["network"], + defaultMode: "askAll", + }); +}); + +test("appendProjectPermissionAllows moves inherited ask and deny scopes into allow", () => { + const projectRoot = createTempDir("deepcode-permission-settings-move-inherited-"); + + appendProjectPermissionAllows(projectRoot, ["network", "write-out-cwd"], { + inheritedPermissions: { + allow: ["read-in-cwd"], + deny: ["write-out-cwd"], + ask: ["network", "mcp"], + defaultMode: "askAll", + }, + }); + + const settingsPath = path.join(projectRoot, ".deepcode", "settings.json"); + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); + assert.deepEqual(settings.permissions, { + allow: ["read-in-cwd", "network", "write-out-cwd"], + deny: [], + ask: ["mcp"], + defaultMode: "askAll", + }); +}); + +test("appendProjectPermissionAllows writes inherited permissions even when scope is already allowed", () => { + const projectRoot = createTempDir("deepcode-permission-settings-inherited-existing-"); + + appendProjectPermissionAllows(projectRoot, ["read-in-cwd"], { + inheritedPermissions: { + allow: ["read-in-cwd"], + deny: [], + ask: ["network"], + defaultMode: "askAll", + }, + }); + + const settingsPath = path.join(projectRoot, ".deepcode", "settings.json"); + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); + assert.deepEqual(settings.permissions, { + allow: ["read-in-cwd"], + deny: [], + ask: ["network"], + defaultMode: "askAll", + }); +}); + +test("appendProjectPermissionAllows preserves existing project permissions", () => { + const projectRoot = createTempDir("deepcode-permission-settings-explicit-default-"); + const settingsPath = path.join(projectRoot, ".deepcode", "settings.json"); + fs.mkdirSync(path.dirname(settingsPath), { recursive: true }); + fs.writeFileSync( + settingsPath, + JSON.stringify({ permissions: { allow: ["read-in-cwd"], defaultMode: "allowAll" } }), + "utf8" + ); + + appendProjectPermissionAllows(projectRoot, ["query-git-log"], { + inheritedPermissions: { + allow: ["write-in-cwd"], + deny: ["write-out-cwd"], + ask: ["network"], + defaultMode: "askAll", + }, + }); + + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); + assert.deepEqual(settings.permissions, { + allow: ["read-in-cwd", "query-git-log"], + defaultMode: "allowAll", + }); +}); + +test("appendProjectPermissionAllows removes existing ask and deny conflicts", () => { + const projectRoot = createTempDir("deepcode-permission-settings-existing-conflict-"); + const settingsPath = path.join(projectRoot, ".deepcode", "settings.json"); + fs.mkdirSync(path.dirname(settingsPath), { recursive: true }); + fs.writeFileSync( + settingsPath, + JSON.stringify({ + permissions: { + allow: ["read-in-cwd"], + deny: ["network", "write-out-cwd"], + ask: ["network", "mcp"], + defaultMode: "askAll", + }, + }), + "utf8" + ); + + appendProjectPermissionAllows(projectRoot, ["network"]); + + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); + assert.deepEqual(settings.permissions, { + allow: ["read-in-cwd", "network"], + deny: ["write-out-cwd"], + ask: ["mcp"], + defaultMode: "askAll", + }); +}); + test("hasUserPermissionReplies detects permission reply payloads", () => { assert.equal(hasUserPermissionReplies({}), false); assert.equal(hasUserPermissionReplies({ permissions: [] }), false); From bacb6a4fab37a38be434485eeea194dd36f6b4bc Mon Sep 17 00:00:00 2001 From: xinggitxing Date: Sat, 23 May 2026 18:32:52 +0800 Subject: [PATCH 117/129] feat(ui): add session deletion with Delete key confirmation - Add SessionManager.deleteSession() to remove session index entry and messages file - Add Delete key to trigger session deletion confirmation in SessionList - Two-step confirmation: Enter to confirm, Esc to cancel - Separate backspace (search) and delete (delete trigger) key behavior - Clear active session if deleted session was the active one - Add comprehensive test coverage for deleteSession --- src/session.ts | 22 +++++++ src/tests/session.test.ts | 129 ++++++++++++++++++++++++++++++++++++++ src/ui/App.tsx | 8 +++ src/ui/SessionList.tsx | 71 +++++++++++++++++---- 4 files changed, 218 insertions(+), 12 deletions(-) diff --git a/src/session.ts b/src/session.ts index 54340e7..a3a6dd1 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1476,6 +1476,28 @@ ${skillMd} return index.entries.find((entry) => entry.id === sessionId) ?? null; } + /** + * Delete a session by its ID. + * Removes the session entry from the index and deletes the associated messages file. + * Returns true if the session was found and deleted, false otherwise. + */ + deleteSession(sessionId: string): boolean { + const index = this.loadSessionsIndex(); + const entryIndex = index.entries.findIndex((entry) => entry.id === sessionId); + if (entryIndex === -1) { + return false; + } + + // Remove from index + index.entries.splice(entryIndex, 1); + this.saveSessionsIndex(index); + + // Remove messages file + this.removeSessionMessages([sessionId]); + + return true; + } + listSessionMessages(sessionId: string): SessionMessage[] { const messagePath = this.getSessionMessagesPath(sessionId); if (!fs.existsSync(messagePath)) { diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index fd83199..a8d943f 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -2123,6 +2123,135 @@ test("SessionManager adjusts the active Bash timeout control and session metadat assert.equal(processInfo?.deadlineAt, new Date(timeoutInfo.deadlineAtMs).toISOString()); }); +test("SessionManager.deleteSession removes session entry from the index", () => { + const workspace = createTempDir("deepcode-delete-workspace-"); + const home = createTempDir("deepcode-delete-home-"); + setHomeDir(home); + + const manager = createSessionManager(workspace, "machine-id-delete"); + (manager as any).activateSession = async () => {}; + + // Create two sessions + const session1 = createSessionAndMessages(manager, "session-delete-1", "First session"); + const session2 = createSessionAndMessages(manager, "session-delete-2", "Second session"); + + assert.equal(manager.listSessions().length, 2); + + // Delete the first session + const result = manager.deleteSession(session1); + assert.equal(result, true); + + const remaining = manager.listSessions(); + assert.equal(remaining.length, 1); + assert.equal(remaining[0]?.id, session2); +}); + +test("SessionManager.deleteSession removes the messages file", () => { + const workspace = createTempDir("deepcode-delete-msg-workspace-"); + const home = createTempDir("deepcode-delete-msg-home-"); + setHomeDir(home); + + const manager = createSessionManager(workspace, "machine-id-delete-msg"); + (manager as any).activateSession = async () => {}; + + const sessionId = createSessionAndMessages(manager, "session-delete-msg", "Test session"); + const messagePath = path.join( + home, + ".deepcode", + "projects", + workspace.replace(/[\\\\/]/g, "-").replace(/:/g, ""), + `${sessionId}.jsonl` + ); + + // Verify messages file exists + assert.ok(fs.existsSync(messagePath)); + + manager.deleteSession(sessionId); + + // Verify messages file is removed + assert.equal(fs.existsSync(messagePath), false); +}); + +test("SessionManager.deleteSession returns false when session does not exist", () => { + const workspace = createTempDir("deepcode-delete-nonexist-workspace-"); + const home = createTempDir("deepcode-delete-nonexist-home-"); + setHomeDir(home); + + const manager = createSessionManager(workspace, "machine-id-delete-nonexist"); + + const result = manager.deleteSession("nonexistent-session-id"); + assert.equal(result, false); + assert.equal(manager.listSessions().length, 0); +}); + +test("SessionManager.deleteSession does not affect other sessions", () => { + const workspace = createTempDir("deepcode-delete-others-workspace-"); + const home = createTempDir("deepcode-delete-others-home-"); + setHomeDir(home); + + const manager = createSessionManager(workspace, "machine-id-delete-others"); + (manager as any).activateSession = async () => {}; + + const session1 = createSessionAndMessages(manager, "session-keep-1", "Keep session 1"); + const session2 = createSessionAndMessages(manager, "session-keep-2", "Keep session 2"); + + // Delete non-existent session + const result = manager.deleteSession("non-existent"); + assert.equal(result, false); + assert.equal(manager.listSessions().length, 2); + + // Delete one session + assert.equal(manager.deleteSession(session1), true); + assert.equal(manager.listSessions().length, 1); + assert.equal(manager.listSessions()[0]?.id, session2); + + // The remaining session should still have its messages accessible + const messages = manager.listSessionMessages(session2); + assert.ok(messages.length > 0); +}); + +/** + * Helper: creates a session and writes a few messages to it so we can test + * that deleteSession removes both the index entry and the messages file. + */ +function createSessionAndMessages(manager: SessionManager, sessionId: string, summary: string): string { + const now = new Date().toISOString(); + const index = (manager as any).loadSessionsIndex(); + index.entries.push({ + id: sessionId, + summary, + assistantReply: null, + assistantThinking: null, + assistantRefusal: null, + toolCalls: null, + status: "completed", + failReason: null, + usage: null, + usagePerModel: null, + activeTokens: 0, + createTime: now, + updateTime: now, + processes: null, + }); + (manager as any).saveSessionsIndex(index); + + // Write a couple of message lines to the messages file + const projectDir = (manager as any).getProjectStorage().projectDir; + const messagePath = path.join(projectDir, `${sessionId}.jsonl`); + const msg = JSON.stringify({ + id: "msg-1", + sessionId, + role: "user", + content: summary, + visible: true, + createTime: now, + updateTime: now, + }); + fs.writeFileSync(messagePath, `${msg}\n`, "utf8"); + + return sessionId; +} + function hasGit(): boolean { try { execFileSync("git", ["--version"], { stdio: "ignore" }); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 5419a2a..942bbf8 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -658,6 +658,14 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. sessions={sessions} onSelect={(id) => void handleSelectSession(id)} onCancel={() => setView("chat")} + onDelete={(id) => { + // If the deleted session is the active one, clear it + if (sessionManager.getActiveSessionId() === id) { + sessionManager.setActiveSessionId(null); + } + sessionManager.deleteSession(id); + refreshSessionsList(); + }} /> ) : view === "undo" ? ( void; onCancel: () => void; + onDelete?: (sessionId: string) => void; }; /** @@ -36,9 +37,10 @@ export function filterSessions(sessions: SessionEntry[], query: string): Session }); } -export function SessionList({ sessions, onSelect, onCancel }: Props): React.ReactElement { +export function SessionList({ sessions, onSelect, onCancel, onDelete }: Props): React.ReactElement { const [index, setIndex] = useState(0); const [searchQuery, setSearchQuery] = useState(""); + const [confirmDeleteSessionId, setConfirmDeleteSessionId] = useState(null); const { columns, rows } = useWindowSize(); // Filter sessions by search query @@ -77,7 +79,23 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac setIndex(0); }, []); + const selectedSession = filteredSessions[safeIndex]; + useInput((input, key) => { + // If in delete confirmation mode, handle confirm/cancel + if (confirmDeleteSessionId) { + if (key.return) { + onDelete?.(confirmDeleteSessionId); + setConfirmDeleteSessionId(null); + return; + } + if (key.escape) { + setConfirmDeleteSessionId(null); + return; + } + return; + } + // ESC: clear search first, then cancel if (key.escape) { if (searchQuery) { @@ -95,13 +113,25 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac return; } - // Backspace / Delete: remove last search character - if (key.backspace || key.delete) { + // Backspace: remove last search character + if (key.backspace) { + if (searchQuery) { + handleBackspace(); + return; + } + } + + // Delete key: remove search character, or start delete confirmation + if (key.delete) { if (searchQuery) { handleBackspace(); return; } - // If no search query, navigation keys below handle the rest + // No search query: start delete confirmation if session is selected + if (selectedSession && onDelete) { + setConfirmDeleteSessionId(selectedSession.id); + return; + } } // Printable character: append to search query @@ -211,20 +241,23 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac ) : ( visibleSessions.map((session, i) => { const actualIndex = scrollOffset + i; + const isSelected = actualIndex === safeIndex; + const isConfirming = confirmDeleteSessionId === session.id; return ( - {actualIndex === safeIndex ? "> " : " "} + {isSelected ? "> " : " "} - + {formatSessionTitle(session.summary || "Untitled")} - ({formatSessionStatus(session.status)}) + {isConfirming ? ( + [Delete? Enter=yes, Esc=no] + ) : ( + ({formatSessionStatus(session.status)}) + )} {formatTimestamp(session.updateTime)} @@ -245,14 +278,28 @@ export function SessionList({ sessions, onSelect, onCancel }: Props): React.Reac {/* Footer */} - {hasActiveSearch ? ( + {confirmDeleteSessionId ? ( + + Delete this session? + + Enter + + to confirm · + + Esc + + to cancel + + ) : hasActiveSearch ? ( Esc clear search · ↑/↓ navigate · Enter select · Esc again to cancel ) : ( - Type to search · ↑/↓ navigate · PgUp/PgDn page · Enter select · Esc cancel + + Type to search · ↑/↓ navigate · PgUp/PgDn page · Enter select · Esc cancel · Del delete + )} From 928551e127b0df5f77b44aaee030863f838406e0 Mon Sep 17 00:00:00 2001 From: dengm Date: Sat, 23 May 2026 19:58:33 +0800 Subject: [PATCH 118/129] feat: add closed-border markdown table rendering with CJK/emoji support - Detect markdown tables and render with Unicode box-drawing characters - Calculate visual terminal width for CJK/emoji (2 cols) vs ASCII (1 col) - Wrap long cells across multiple lines, prefer word-boundary breaks - Allocate column widths: narrow columns (#, status, count, date) minimal, content columns kept >= 12 chars - Render tables with to prevent Ink from breaking box-drawing lines at cell boundary spaces - Expose renderMarkdownSegments() for per-segment wrapping control --- Screenshot_2026-05-23_195028.png | Bin 0 -> 105561 bytes src/ui/components/MessageView/index.tsx | 17 +- src/ui/components/MessageView/markdown.ts | 324 +++++++++++++++++++--- src/ui/index.ts | 2 +- 4 files changed, 304 insertions(+), 39 deletions(-) create mode 100644 Screenshot_2026-05-23_195028.png diff --git a/Screenshot_2026-05-23_195028.png b/Screenshot_2026-05-23_195028.png new file mode 100644 index 0000000000000000000000000000000000000000..870fbaae9e6cb8f3940673faac16d3811fea2f41 GIT binary patch literal 105561 zcmeFZcT`hbyFDCKY>3!^14^?X9i>VOD7}PUBs7)YMVbTx*cGHHz4ug2t`Z(ip7z{?O ztR$xmgB=Wo!6=uG9tM9|6!QEDzEQYpE8cpjqqe_1)L#FG1QbyO5L_0Lx&60b;g8M@>T$0+{y`~Qt`Xp%)B z5F=k2s&Al4W&Iin;yrV+_&7qGkgc}Roe%!g+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V%j`@%#2 zYw?%%!!=|N!bH)VPCK9edYA`RiAK=4-;5C&$}4Q`D+?FXz;lkdTGGJ9j0vi&8A53G zmF&nk{{5VRQ@RE2d7mE#Q%YpLjPITvSTrgD9Bcj3k`fIs);=x%>HI6xt3M>o3@&3x zyanaQVP3ZNE{lG)FV}&<%r3#CH9ER1z;Afoim5;O@A6LW5oomUs9$=T3>g`jv)U;d zGBUaAv}$1IwT|3rGP1$Q(@bP!0nb?Cz^`_50?v?;WnG{U1UoH4yr;;>mX-gH{7WCR zy1F{#=2`>r#nb%->itV+6bXm_N{hO9(w05(z~tU%vs>3dWe+9M zr?-1}%u3i0CS|p<@PfObU2?*UPvl^W1Ze4gvTNjFXJNR~F(UZ}i%|%6}1eo51Bv9%*3o(lM$543Tc=O8dMO2aI1k}uby~9kH zA6!k^t@fWkf2wNwVkI?h%0vsZLFSPghsBM=@lY%VN-QI_;0xoA+<@1a|Gb@}T^g+@DNCo}SSdvp&loumzh7t_S zTULVii+#*woQ}XB2&qvvsRvg}oEEk&LYfa$c4)!VDXE7#CKKN - - {content ? {renderMarkdown(content)} : null} + + {content + ? renderMarkdownSegments(content, Math.max(20, contentWidth - 4)).map((seg, i) => { + if (seg.kind === "table") { + return ( + + {seg.body} + + ); + } + return {seg.body}; + }) + : null} ); diff --git a/src/ui/components/MessageView/markdown.ts b/src/ui/components/MessageView/markdown.ts index 11fb0ea..8c86534 100644 --- a/src/ui/components/MessageView/markdown.ts +++ b/src/ui/components/MessageView/markdown.ts @@ -1,22 +1,61 @@ import chalk from "chalk"; -export function renderMarkdown(text: string): string { - if (!text) { - return ""; - } +/** + * A rendered piece of markdown. Consumers should use `wrap="truncate-end"` for + * `table` segments and the default wrap mode for `text` segments so that Ink + * never breaks box-drawing lines at cell boundary spaces. + */ +export type MarkdownSegment = + | { kind: "text"; body: string } + | { kind: "table"; body: string } + | { kind: "code"; body: string; lang: string }; + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/** Render markdown to a single string (backward-compatible). */ +export function renderMarkdown(text: string, maxWidth?: number): string { + return renderMarkdownSegments(text, maxWidth) + .map((s) => s.body) + .join(""); +} + +/** Render markdown, returning typed segments so the caller can choose the + right `` per segment. */ +export function renderMarkdownSegments(text: string, maxWidth?: number): MarkdownSegment[] { + if (!text) return []; + const segments: MarkdownSegment[] = []; const fenceSegments = splitByFences(text); - return fenceSegments - .map((segment) => { - if (segment.kind === "code") { - const langTag = segment.lang ? chalk.dim(`[${segment.lang}]`) + "\n" : ""; - return langTag + chalk.cyan(segment.body); + + for (const seg of fenceSegments) { + if (seg.kind === "code") { + const langTag = seg.lang ? chalk.dim(`[${seg.lang}]`) + "\n" : ""; + segments.push({ kind: "code", body: langTag + chalk.cyan(seg.body), lang: seg.lang }); + continue; + } + const blocks = splitTableBlocks(seg.body); + for (const b of blocks) { + if (b.kind === "table") { + segments.push({ kind: "table", body: renderTableBorder(b.rows, maxWidth) }); + } else { + const body = b.body + .split("\n") + .map((line) => renderInlineLine(line)) + .join("\n"); + if (body) segments.push({ kind: "text", body }); } - return renderInlineBlock(segment.body); - }) - .join(""); + } + } + + return segments; } +// --------------------------------------------------------------------------- +// Code fences +// --------------------------------------------------------------------------- + type FenceSegment = { kind: "text"; body: string } | { kind: "code"; lang: string; body: string }; function splitByFences(text: string): FenceSegment[] { @@ -28,35 +67,27 @@ function splitByFences(text: string): FenceSegment[] { let fenceBody: string[] = []; const flushText = () => { - if (buffer.length === 0) { - return; + if (buffer.length > 0) { + segments.push({ kind: "text", body: buffer.join("\n") }); + buffer = []; } - segments.push({ kind: "text", body: buffer.join("\n") }); - buffer = []; }; for (const line of lines) { - const fenceMatch = /^\s*```(\w*)\s*$/.exec(line); - if (fenceMatch) { + const m = /^\s*```(\w*)\s*$/.exec(line); + if (m) { if (!inFence) { flushText(); inFence = true; - fenceLang = fenceMatch[1] ?? ""; + fenceLang = m[1] ?? ""; fenceBody = []; } else { segments.push({ kind: "code", lang: fenceLang, body: fenceBody.join("\n") }); inFence = false; - fenceLang = ""; - fenceBody = []; } continue; } - - if (inFence) { - fenceBody.push(line); - } else { - buffer.push(line); - } + (inFence ? fenceBody : buffer).push(line); } if (inFence) { @@ -68,13 +99,238 @@ function splitByFences(text: string): FenceSegment[] { return segments; } -function renderInlineBlock(text: string): string { - return text - .split("\n") - .map((line) => renderInlineLine(line)) - .join("\n"); +// --------------------------------------------------------------------------- +// Table parsing +// --------------------------------------------------------------------------- + +type TableBlock = { kind: "text"; body: string } | { kind: "table"; rows: string[][] }; + +function splitTableBlocks(text: string): TableBlock[] { + const lines = text.split(/\r?\n/); + const blocks: TableBlock[] = []; + let buffer: string[] = []; + let tableRows: string[][] = []; + let inTable = false; + + const flushText = () => { + if (buffer.length > 0) { + blocks.push({ kind: "text", body: buffer.join("\n") }); + buffer = []; + } + }; + const flushTable = () => { + if (tableRows.length >= 2) { + blocks.push({ kind: "table", rows: tableRows }); + } else if (tableRows.length > 0) { + buffer.push(...tableRows.map((r) => r.join(" | "))); + } + tableRows = []; + }; + + const sepRe = /^\|?\s*:?[-]{3,}:?\s*(\|\s*:?[-]{3,}:?\s*)*\|?\s*$/; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const trimmed = line.trim(); + const nextTrimmed = (lines[i + 1] ?? "").trim(); + + // skip separator line + if (inTable && sepRe.test(trimmed) && tableRows.length === 1) continue; + + const isRow = /^\|.+\|$/.test(trimmed); + const isHeader = isRow && i + 1 < lines.length && sepRe.test(nextTrimmed); + + if (isHeader && !inTable) { + flushText(); + inTable = true; + tableRows = [ + trimmed + .split("|") + .filter(Boolean) + .map((s) => s.trim()), + ]; + continue; + } + + if (isRow && inTable) { + tableRows.push( + trimmed + .split("|") + .filter(Boolean) + .map((s) => s.trim()) + ); + continue; + } + + if (inTable && !isRow) { + flushTable(); + inTable = false; + } + buffer.push(line); + } + + return inTable ? [...blocks, ...flushTableResult(tableRows)] : [...blocks, ...flushTextOnly(buffer, tableRows)]; +} + +function flushTableResult(rows: string[][]): TableBlock[] { + if (rows.length >= 2) return [{ kind: "table", rows }]; + if (rows.length > 0) return [{ kind: "text", body: rows.map((r) => r.join(" | ")).join("\n") }]; + return []; +} + +function flushTextOnly(buffer: string[], tableRows: string[][]): TableBlock[] { + const result: TableBlock[] = []; + if (buffer.length > 0) result.push({ kind: "text", body: buffer.join("\n") }); + if (tableRows.length >= 2) result.push({ kind: "table", rows: tableRows }); + else if (tableRows.length > 0) result.push({ kind: "text", body: tableRows.map((r) => r.join(" | ")).join("\n") }); + return result; +} + +// --------------------------------------------------------------------------- +// Terminal visual width (CJK / emoji = 2 cols, ASCII = 1) +// --------------------------------------------------------------------------- + +function visualWidth(text: string): number { + let w = 0; + for (const ch of text) { + if (ch.length >= 2) { + w += 2; + continue; + } + const code = ch.codePointAt(0) ?? ch.charCodeAt(0); + w += isWideChar(code) ? 2 : 1; + } + return w; +} + +function isWideChar(code: number): boolean { + return ( + (code >= 0x1100 && code <= 0x115f) || // Hangul Jamo + (code >= 0x2329 && code <= 0x232a) || // Misc technical + (code >= 0x2e80 && code <= 0xa4cf) || // CJK Radicals, Kangxi, CJK all + (code >= 0xac00 && code <= 0xd7af) || // Hangul Syllables + (code >= 0xf900 && code <= 0xfaff) || // CJK Compat + (code >= 0xfe10 && code <= 0xfe6f) || // CJK Compat Forms + (code >= 0xff00 && code <= 0xffe6) || // Fullwidth + (code >= 0x20000 && code <= 0x3fffd) || // CJK Ext B+ + (code >= 0x1f300 && code <= 0x1faff) || // Emoji & pictographs + (code >= 0x2600 && code <= 0x27bf) || // Misc Symbols + (code >= 0x2300 && code <= 0x23ff) || // Misc Technical + (code >= 0x2b00 && code <= 0x2bff) || // Misc Symbols & Arrows + (code >= 0x1f000 && code <= 0x1f02f) // Mahjong & Domino + ); +} + +// --------------------------------------------------------------------------- +// Table rendering +// --------------------------------------------------------------------------- + +function renderTableBorder(rows: string[][], maxWidth?: number): string { + if (rows.length === 0) return ""; + + const colCount = rows[0].length; + const calcW = (cs: number[]) => cs.reduce((a, b) => a + b + 2, 0) + cs.length + 1; + + // Ideal widths — longest word / 1.5 so cells can wrap in 2-3 lines + const ideal: number[] = Array.from({ length: colCount }, (_, i) => { + const texts = rows.map((r) => r[i] ?? ""); + const maxLine = Math.max(...texts.map((t) => visualWidth(t))); + const words = texts.flatMap((t) => t.split(/\s+/)); + const maxWord = Math.max(4, ...words.map((w) => visualWidth(w))); + return Math.max(maxWord + 2, Math.ceil(maxLine / 1.5)); + }); + + const colWidths = [...ideal]; + + // Shrink to fit terminal width + if (maxWidth != null && calcW(colWidths) > maxWidth) { + const narrow = new Set([0, 1, colCount - 2, colCount - 1]); // #, status, count, date + const MIN_NARROW = 6; + const MIN_CONTENT = 12; + const contentCols = Array.from({ length: colCount }, (_, i) => i).filter((i) => !narrow.has(i)); + + // Cap narrow columns first + for (const ci of narrow) colWidths[ci] = Math.min(colWidths[ci], MIN_NARROW); + + // Shrink until we fit + while (calcW(colWidths) > maxWidth) { + // Try narrow columns first + let shrunk = false; + for (const ci of narrow) { + if (colWidths[ci] > 4 && calcW(colWidths) > maxWidth) { + colWidths[ci]--; + shrunk = true; + } + } + if (shrunk) continue; + // Then content columns + const widest = contentCols.reduce((a, b) => (colWidths[a] > colWidths[b] ? a : b), contentCols[0]); + if (colWidths[widest] > MIN_CONTENT) colWidths[widest]--; + else break; + } + } + + // Word-wrap a single cell + const wrapCell = (text: string, width: number): string[] => { + if (!text) return [""]; + const lines: string[] = []; + let cur = ""; + const flush = () => { + if (cur.trim()) lines.push(cur.replace(/\s+$/, "")); + cur = ""; + }; + + for (const ch of text) { + const cw = visualWidth(ch); + if (visualWidth(cur) + cw > width) { + const lastSpace = cur.lastIndexOf(" "); + if (lastSpace > width / 3) { + const carry = cur.slice(lastSpace + 1); + cur = cur.slice(0, lastSpace); + flush(); + cur = carry + ch; + } else { + flush(); + cur = ch; + } + } else { + cur += ch; + } + } + if (cur.trim()) lines.push(cur.replace(/\s+$/, "")); + return lines.length > 0 ? lines : [""]; + }; + + const wrapped = rows.map((r) => r.map((c, ci) => wrapCell(c, colWidths[ci]))); + const heights = wrapped.map((wr) => Math.max(1, ...wr.map((lines) => lines.length))); + + const pad = (s: string, w: number) => s + " ".repeat(Math.max(0, w - visualWidth(s))); + + const top = "┌" + colWidths.map((w) => "─".repeat(w + 2)).join("┬") + "┐"; + const hdr = "├" + colWidths.map((w) => "─".repeat(w + 2)).join("┼") + "┤"; + const sep = "├" + colWidths.map((w) => "─".repeat(w + 2)).join("┼") + "┤"; + const bot = "└" + colWidths.map((w) => "─".repeat(w + 2)).join("┴") + "┘"; + + const out: string[] = [top]; + + for (let ri = 0; ri < wrapped.length; ri++) { + const h = heights[ri]; + for (let li = 0; li < h; li++) { + const line = wrapped[ri].map((cellLines, ci) => " " + pad(cellLines[li] ?? "", colWidths[ci]) + " "); + out.push("│" + line.join("│") + "│"); + } + if (ri === 0 && rows.length > 1) out.push(hdr); + else if (ri < rows.length - 1) out.push(sep); + } + + out.push(bot); + return out.join("\n"); } +// --------------------------------------------------------------------------- +// Inline formatting (headings, lists, quotes, bold/italic/code) +// --------------------------------------------------------------------------- + function renderInlineLine(line: string): string { const headingMatch = /^(\s*)(#{1,6})\s+(.*)$/.exec(line); if (headingMatch) { @@ -105,9 +361,7 @@ function renderInlineLine(line: string): string { } function renderInlineSpans(text: string): string { - if (!text) { - return text; - } + if (!text) return text; let result = text; result = result.replace(/`([^`]+)`/g, (_, inner) => chalk.cyan(inner)); result = result.replace(/\*\*([^*]+)\*\*/g, (_, inner) => chalk.bold(inner)); diff --git a/src/ui/index.ts b/src/ui/index.ts index d899d4b..1348903 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -54,7 +54,7 @@ export { } from "./askUserQuestion"; export { readClipboardImage, type ClipboardImage } from "./clipboard"; export { buildLoadingText, type LoadingTextInput } from "./loadingText"; -export { renderMarkdown } from "./components/MessageView/markdown"; +export { renderMarkdown, renderMarkdownSegments, type MarkdownSegment } from "./components/MessageView/markdown"; export { EMPTY_BUFFER, insertText, From 809670952601f7dedf738008190b9d8d84054491 Mon Sep 17 00:00:00 2001 From: dengmik-commits Date: Sat, 23 May 2026 20:05:13 +0800 Subject: [PATCH 119/129] add screenshot --- Screenshot_2026-05-23_195028.png | Bin 105561 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/Screenshot_2026-05-23_195028.png b/Screenshot_2026-05-23_195028.png index 870fbaae9e6cb8f3940673faac16d3811fea2f41..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 GIT binary patch literal 0 HcmV?d00001 literal 105561 zcmeFZcT`hbyFDCKY>3!^14^?X9i>VOD7}PUBs7)YMVbTx*cGHHz4ug2t`Z(ip7z{?O ztR$xmgB=Wo!6=uG9tM9|6!QEDzEQYpE8cpjqqe_1)L#FG1QbyO5L_0Lx&60b;g8M@>T$0+{y`~Qt`Xp%)B z5F=k2s&Al4W&Iin;yrV+_&7qGkgc}Roe%!g+nXz0Q%Qcz(s2c;@z}03MMc-i*6R&M zl}^ImEVL6V7bG9v7jpW3!_{Z>%dygq1B8|%gjoh$6pa~P)V%(+&D^(Qtq}}5jZOCX zmkx!l0;9@SkNJV}?1BPbUlH&0B5Sw0wnQljQkpa=t=r9{>OLEO_T2?spKHW|H9fzn zL*XDCO_CFJ9)8`PAYl+i?A_WjP#IC&DR^}7NPUMKJNm^*rT{*Znsd@`6F@YMSaHRz0Gn(r^Y>bv?e%68#YJ zm4Kz?)|b z%Rh}sz4?Y`5itT8Ix)!hI`8#VLF@Ktf&Qpvk#SBpl)+zN^xbfP4H%k z`}W3C@bkyKMip{ruc`|*C~vJVF1ne;Kg-8wl}YVxjODDCPvEYIN6pXAKT~BfxlN`1 zacr_J4&fLm@LDTPL7tbFx9d6e`PSJQ*3~K@!LF?e=MiRUEp97;H6pS;@YNt_{>X1TY`BIjCst3da0+A~Y#HD_54XW+xxGTfF>1?AX%loh zYA>?+^Hj0yOe-#RJqc71KHMy%Yo5#>XlEy9LZ|yA1<{b&D`^rfpSjmjA)ec*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N Date: Mon, 25 May 2026 08:46:26 +0800 Subject: [PATCH 120/129] feat: add getScopeRiskColor function for permission scope risk mapping --- src/common/permissions.ts | 35 ++++++++++++++++++- src/tests/permission-prompt.test.ts | 19 +++++++++++ src/tests/permissions.test.ts | 33 ++++++++++++++++++ src/ui/PermissionPrompt.tsx | 53 ++++++++++++++++++++++++++--- 4 files changed, 135 insertions(+), 5 deletions(-) create mode 100644 src/tests/permission-prompt.test.ts diff --git a/src/common/permissions.ts b/src/common/permissions.ts index aa87e0d..564bfeb 100644 --- a/src/common/permissions.ts +++ b/src/common/permissions.ts @@ -164,9 +164,10 @@ export function computeToolCallPermissions(options: ComputeToolCallPermissionsOp const permission = evaluatePermissionScopes(request.scopes, options.settings); permissions.push({ toolCallId: toolCall.id, permission }); if (permission === "ask") { + const askScopes = getPermissionScopesRequiringAsk(request.scopes, options.settings); askPermissions.push({ toolCallId: toolCall.id, - scopes: request.scopes, + scopes: askScopes.length > 0 ? askScopes : request.scopes, name: request.name, command: request.command, description: request.description, @@ -285,6 +286,38 @@ export function evaluatePermissionScopes( return settings.defaultMode === "askAll" ? "ask" : "allow"; } +export function getPermissionScopesRequiringAsk( + scopes: AskPermissionScope[], + settings: Required = { + allow: [], + deny: [], + ask: [], + defaultMode: "allowAll", + } +): AskPermissionScope[] { + const result: AskPermissionScope[] = []; + for (const scope of scopes) { + if (scope === "unknown") { + result.push(scope); + continue; + } + if (settings.deny.includes(scope)) { + continue; + } + if (settings.ask.includes(scope)) { + result.push(scope); + continue; + } + if (settings.allow.includes(scope)) { + continue; + } + if (settings.defaultMode === "askAll") { + result.push(scope); + } + } + return result; +} + export function parseBashSideEffects(value: unknown): AskPermissionScope[] { const validScopes = new Set([ "read-in-cwd", diff --git a/src/tests/permission-prompt.test.ts b/src/tests/permission-prompt.test.ts new file mode 100644 index 0000000..aa4f372 --- /dev/null +++ b/src/tests/permission-prompt.test.ts @@ -0,0 +1,19 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { getScopeRiskColor } from "../ui/PermissionPrompt"; + +test("getScopeRiskColor maps permission scopes by risk", () => { + assert.equal(getScopeRiskColor("read-in-cwd"), "#22c55e"); + assert.equal(getScopeRiskColor("query-git-log"), "#22c55e"); + + assert.equal(getScopeRiskColor("read-out-cwd"), "#f59e0b"); + assert.equal(getScopeRiskColor("write-in-cwd"), "#f59e0b"); + assert.equal(getScopeRiskColor("network"), "#f59e0b"); + assert.equal(getScopeRiskColor("mcp"), "#f59e0b"); + + assert.equal(getScopeRiskColor("write-out-cwd"), "#ef4444"); + assert.equal(getScopeRiskColor("delete-in-cwd"), "#ef4444"); + assert.equal(getScopeRiskColor("delete-out-cwd"), "#ef4444"); + assert.equal(getScopeRiskColor("mutate-git-log"), "#ef4444"); + assert.equal(getScopeRiskColor("unknown"), "#ef4444"); +}); diff --git a/src/tests/permissions.test.ts b/src/tests/permissions.test.ts index 8babf11..3a28616 100644 --- a/src/tests/permissions.test.ts +++ b/src/tests/permissions.test.ts @@ -93,6 +93,39 @@ test("computeToolCallPermissions maps tool calls to permission requests", () => ); }); +test("computeToolCallPermissions only asks for scopes not already allowed", () => { + const projectRoot = createTempDir("deepcode-permissions-filter-workspace-"); + const plan = computeToolCallPermissions({ + sessionId: "session-1", + projectRoot, + settings: { + allow: ["read-in-cwd"], + deny: [], + ask: [], + defaultMode: "askAll", + }, + toolCalls: [ + { + id: "call-bash", + type: "function", + function: { + name: "bash", + arguments: JSON.stringify({ + command: "curl -s http://localhost:8899/ && ls index.html", + sideEffects: ["network", "read-in-cwd"], + }), + }, + }, + ], + }); + + assert.deepEqual(plan.permissions, [{ toolCallId: "call-bash", permission: "ask" }]); + assert.deepEqual( + plan.askPermissions.map((item) => ({ id: item.toolCallId, scopes: item.scopes })), + [{ id: "call-bash", scopes: ["network"] }] + ); +}); + test("appendProjectPermissionAllows writes unique project-level allow scopes", () => { const projectRoot = createTempDir("deepcode-permission-settings-"); const settingsPath = path.join(projectRoot, ".deepcode", "settings.json"); diff --git a/src/ui/PermissionPrompt.tsx b/src/ui/PermissionPrompt.tsx index 4613639..03881a5 100644 --- a/src/ui/PermissionPrompt.tsx +++ b/src/ui/PermissionPrompt.tsx @@ -20,6 +20,13 @@ type ScopePrompt = { scope: AskPermissionScope; }; +type PromptOption = { + kind: "allow" | "always" | "deny"; + label: string; + scopeDescription?: string; + scopeColor?: string; +}; + const ALWAYS_ALLOWED_SCOPES = new Set([ "read-in-cwd", "read-out-cwd", @@ -138,7 +145,7 @@ export function PermissionPrompt({ requests, onSubmit, onCancel }: Props): React {options.map((option, optionIndex) => ( {optionIndex === cursor ? "> " : " "} - {optionIndex + 1}. {option.label} + {optionIndex + 1}. {renderOptionLabel(option)} ))} @@ -149,6 +156,18 @@ export function PermissionPrompt({ requests, onSubmit, onCancel }: Props): React ); } +function renderOptionLabel(option: PromptOption): React.ReactNode { + if (option.scopeDescription && option.scopeColor) { + return ( + <> + {option.label} + {option.scopeDescription} + + ); + } + return option.label; +} + function buildScopePrompts(requests: AskPermissionRequest[]): ScopePrompt[] { const prompts: ScopePrompt[] = []; for (const request of requests) { @@ -159,10 +178,15 @@ function buildScopePrompts(requests: AskPermissionRequest[]): ScopePrompt[] { return prompts; } -function buildOptions(scope: AskPermissionScope): Array<{ kind: "allow" | "always" | "deny"; label: string }> { - const options: Array<{ kind: "allow" | "always" | "deny"; label: string }> = [{ kind: "allow", label: "Yes" }]; +function buildOptions(scope: AskPermissionScope): PromptOption[] { + const options: PromptOption[] = [{ kind: "allow", label: "Yes" }]; if (isAlwaysAllowedScope(scope)) { - options.push({ kind: "always", label: `Yes, and always allow ${describeScope(scope)}` }); + options.push({ + kind: "always", + label: "Yes, and always allow ", + scopeDescription: describeScope(scope), + scopeColor: getScopeRiskColor(scope), + }); } options.push({ kind: "deny", label: "No" }); return options; @@ -201,6 +225,27 @@ function isAlwaysAllowedScope(scope: AskPermissionScope): scope is PermissionSco return ALWAYS_ALLOWED_SCOPES.has(scope); } +export function getScopeRiskColor(scope: AskPermissionScope): string { + switch (scope) { + case "read-in-cwd": + case "query-git-log": + return "#22c55e"; + case "read-out-cwd": + case "write-in-cwd": + case "network": + case "mcp": + return "#f59e0b"; + case "write-out-cwd": + case "delete-in-cwd": + case "delete-out-cwd": + case "mutate-git-log": + case "unknown": + return "#ef4444"; + default: + return "#ef4444"; + } +} + function describeScope(scope: PermissionScope): string { switch (scope) { case "read-in-cwd": From 5d6f727eb686ebdf662e715fe8513c5df05adfbb Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 25 May 2026 11:15:09 +0800 Subject: [PATCH 121/129] feat: add permission.md and update README.md --- README-en.md | 4 ++ README-zh_CN.md | 5 +++ README.md | 5 +++ docs/permission.md | 101 ++++++++++++++++++++++++++++++++++++++++++ docs/permission_en.md | 100 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 215 insertions(+) create mode 100644 docs/permission.md create mode 100644 docs/permission_en.md diff --git a/README-en.md b/README-en.md index 4bff6af..c1d4acb 100644 --- a/README-en.md +++ b/README-en.md @@ -137,6 +137,10 @@ When the AI assistant completes a task, Deep Code can automatically execute a no For detailed configuration instructions, see: [docs/notify_en.md](docs/notify_en.md) +### Does Deep Code only support YOLO mode? + +No. Deep Code has a built-in fine-grained permission control mechanism that lets you confirm operations before the AI assistant executes shell commands, reads/writes files, accesses the network, and more. You can configure each permission scope's policy — always allow, always ask, or deny — via the `permissions` field in `settings.json`. See [docs/permission.md](docs/permission.md) for details. + ## Contributing Contributions are welcome! Here's how to get started: diff --git a/README-zh_CN.md b/README-zh_CN.md index 77db497..2643756 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -122,6 +122,10 @@ Deep Code 支持 MCP(Model Context Protocol),可以连接 GitHub、浏览 详细配置指南:[docs/notify.md](docs/notify.md) +### Deep Code 只支持 YOLO 模式吗? + +不是。Deep Code 内置了细粒度的权限控制机制,支持在 AI 助手执行 Shell 命令、读写文件、访问网络等操作前进行确认。你可以通过 `settings.json` 中的 `permissions` 字段按需配置每种权限范围的策略:始终允许、始终询问、或直接拒绝。详见 [docs/permission.md](docs/permission.md)。 + ### 是否支持 Coding Plan? 支持。只要把 `~/.deepcode/settings.json` 的 `env.BASE_URL` 配置为 OpenAI 兼容的接口地址就行。以火山方舟的 Coding Plan 为例: @@ -136,6 +140,7 @@ Deep Code 支持 MCP(Model Context Protocol),可以连接 GitHub、浏览 "thinkingEnabled": true } ``` + ## 贡献 欢迎贡献代码!以下是参与方式: diff --git a/README.md b/README.md index 77db497..2643756 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,10 @@ Deep Code 支持 MCP(Model Context Protocol),可以连接 GitHub、浏览 详细配置指南:[docs/notify.md](docs/notify.md) +### Deep Code 只支持 YOLO 模式吗? + +不是。Deep Code 内置了细粒度的权限控制机制,支持在 AI 助手执行 Shell 命令、读写文件、访问网络等操作前进行确认。你可以通过 `settings.json` 中的 `permissions` 字段按需配置每种权限范围的策略:始终允许、始终询问、或直接拒绝。详见 [docs/permission.md](docs/permission.md)。 + ### 是否支持 Coding Plan? 支持。只要把 `~/.deepcode/settings.json` 的 `env.BASE_URL` 配置为 OpenAI 兼容的接口地址就行。以火山方舟的 Coding Plan 为例: @@ -136,6 +140,7 @@ Deep Code 支持 MCP(Model Context Protocol),可以连接 GitHub、浏览 "thinkingEnabled": true } ``` + ## 贡献 欢迎贡献代码!以下是参与方式: diff --git a/docs/permission.md b/docs/permission.md new file mode 100644 index 0000000..91c19c6 --- /dev/null +++ b/docs/permission.md @@ -0,0 +1,101 @@ +# Deep Code 权限机制 + +Deep Code 内置了一套细粒度的权限控制机制,在 AI 助手执行工具调用(如执行 Shell 命令、读写文件、访问网络等)前,根据用户配置的策略决定是自动放行、直接拒绝、还是弹出交互式确认。 + +## 概述 + +每次 AI 助手调用工具时,系统会自动分析该操作涉及的**权限范围(Permission Scope)**,然后根据 `settings.json` 中的权限配置做出决策。对于需要用户确认的操作,会在终端中弹出交互式选择界面,用户可以选择: + +- **Yes** — 仅本次放行 +- **Yes, and always allow** — 本次放行,并将该权限范围写入项目配置文件,后续同类操作不再询问 +- **No** — 拒绝本次操作 + +## 权限范围 + +Deep Code 定义了以下 10 种权限范围,覆盖了工具调用的各类风险场景: + +| 权限范围 | 说明 | +| -------- | ---- | +| `read-in-cwd` | 读取当前工作区内的文件 | +| `read-out-cwd` | 读取当前工作区外的文件 | +| `write-in-cwd` | 在当前工作区内创建或覆写文件 | +| `write-out-cwd` | 在当前工作区外创建或覆写文件 | +| `delete-in-cwd` | 删除当前工作区内的文件 | +| `delete-out-cwd` | 删除当前工作区外的文件 | +| `query-git-log` | 查询 Git 历史(如 `git log`、`git show`、`git blame`) | +| `mutate-git-log` | 修改 Git 历史(如 `git commit`、`git rebase`、`git tag`) | +| `network` | 访问网络(如 `curl`、`npm install` 等联网操作) | +| `mcp` | 调用 MCP 外部工具 | + +此外还有一个特殊的 `unknown` 范围,当 LLM 无法准确分类命令的副作用时使用,**`unknown` 总是触发询问**。 + +## 权限配置 + +在 `~/.deepcode/settings.json`(用户级)或 `.deepcode/settings.json`(项目级)中通过 `permissions` 字段配置: + +```json +{ + "permissions": { + "allow": [], + "deny": [], + "ask": [], + "defaultMode": "allowAll" + } +} +``` + +### 配置项说明 + +| 字段 | 类型 | 说明 | +| ---- | ---- | ---- | +| `allow` | `string[]` | 始终自动放行的权限范围列表 | +| `deny` | `string[]` | 始终自动拒绝的权限范围列表 | +| `ask` | `string[]` | 始终弹出询问的权限范围列表 | +| `defaultMode` | `"allowAll"` \| `"askAll"` | 未在 `allow`/`deny`/`ask` 中明确列出的权限范围的默认处理方式。默认为 `"allowAll"` | + +### 优先级规则 + +当一个工具调用涉及多个权限范围时,决策按以下优先级进行: + +1. 若任一范围命中 `deny` → **拒绝** +2. 若任一范围命中 `ask` → **询问** +3. 若所有范围均在 `allow` 中 → **自动放行** +4. 否则 → 按 `defaultMode` 处理 + +### 示例:宽松模式(默认) + +```json +{ + "permissions": { + "defaultMode": "allowAll" + } +} +``` + +默认行为:所有操作自动放行,无需确认。 + +### 示例:严格模式 + +```json +{ + "permissions": { + "allow": ["read-in-cwd", "write-in-cwd", "query-git-log"], + "defaultMode": "askAll" + } +} +``` + +此配置的效果: +- 工作区内读写、Git 查询 → 自动放行 +- 其他操作都需要用户确认。 + + +## 持久化机制 + +当用户在权限提示中选择 "Yes, and always allow" 后,对应的权限范围会被写入当前项目的 `.deepcode/settings.json` 文件中: + +- 新增范围会追加到 `permissions.allow` 列表 +- 如果该范围之前存在于 `deny` 或 `ask` 中,会被自动移除 +- 不会重复写入已存在的范围 + +这样后续同类操作就不再询问。 diff --git a/docs/permission_en.md b/docs/permission_en.md new file mode 100644 index 0000000..dae739c --- /dev/null +++ b/docs/permission_en.md @@ -0,0 +1,100 @@ +# Deep Code Permission Mechanism + +Deep Code includes a fine-grained permission control mechanism. Before the AI assistant executes a tool call (such as running a shell command, reading/writing files, accessing the network, etc.), the system determines whether to auto-allow, auto-deny, or prompt for interactive confirmation based on your configured policy. + +## Overview + +Each time the AI assistant invokes a tool, the system automatically analyzes the **permission scopes** involved and makes a decision based on the permission configuration in `settings.json`. For operations requiring user confirmation, an interactive prompt appears in the terminal with the following choices: + +- **Yes** — Allow this one time only +- **Yes, and always allow** — Allow this time and persistently save the scope to the project configuration so future calls skip the prompt +- **No** — Deny this operation + +## Permission Scopes + +Deep Code defines the following 10 permission scopes, covering various risk scenarios for tool calls: + +| Permission Scope | Description | +| ---------------- | ----------- | +| `read-in-cwd` | Read files inside the current workspace | +| `read-out-cwd` | Read files outside the current workspace | +| `write-in-cwd` | Create or overwrite files inside the current workspace | +| `write-out-cwd` | Create or overwrite files outside the current workspace | +| `delete-in-cwd` | Delete files inside the current workspace | +| `delete-out-cwd` | Delete files outside the current workspace | +| `query-git-log` | Query Git history (e.g., `git log`, `git show`, `git blame`) | +| `mutate-git-log` | Mutate Git history (e.g., `git commit`, `git rebase`, `git tag`) | +| `network` | Access the network (e.g., `curl`, `npm install`) | +| `mcp` | Invoke MCP external tools | + +There is also a special `unknown` scope used when the LLM cannot classify a command's side effects — **`unknown` always triggers a prompt**. + +## Permission Configuration + +Configure permissions in `~/.deepcode/settings.json` (user-level) or `.deepcode/settings.json` (project-level) via the `permissions` field: + +```json +{ + "permissions": { + "allow": [], + "deny": [], + "ask": [], + "defaultMode": "allowAll" + } +} +``` + +### Configuration Fields + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allow` | `string[]` | Permission scopes that are always auto-allowed | +| `deny` | `string[]` | Permission scopes that are always auto-denied | +| `ask` | `string[]` | Permission scopes that always trigger a confirmation prompt | +| `defaultMode` | `"allowAll"` \| `"askAll"` | Default behavior for scopes not explicitly listed in `allow`/`deny`/`ask`. Defaults to `"allowAll"` | + +### Priority Rules + +When a tool call involves multiple permission scopes, the decision follows this priority: + +1. If any scope matches `deny` → **Deny** +2. If any scope matches `ask` → **Prompt** +3. If all scopes are in `allow` → **Auto-allow** +4. Otherwise → use `defaultMode` + +### Example: Relaxed Mode (default) + +```json +{ + "permissions": { + "defaultMode": "allowAll" + } +} +``` + +Default behavior: all operations are auto-allowed with no confirmation required. + +### Example: Strict Mode + +```json +{ + "permissions": { + "allow": ["read-in-cwd", "write-in-cwd", "query-git-log"], + "defaultMode": "askAll" + } +} +``` + +With this configuration: +- Reading/writing inside the workspace and querying Git history → auto-allowed +- All other operations → require user confirmation + +## Persistence + +When you select "Yes, and always allow" in a permission prompt, the corresponding scope is written to the project's `.deepcode/settings.json`: + +- The scope is appended to the `permissions.allow` list +- If the scope was previously in `deny` or `ask`, it is automatically removed +- Duplicate scopes are not written again + +This means subsequent calls involving the same scope will no longer prompt for confirmation. From 7c95312f68623c9da6ce1c865f2dd996d16b2cf5 Mon Sep 17 00:00:00 2001 From: dengm Date: Mon, 25 May 2026 11:17:12 +0800 Subject: [PATCH 122/129] =?UTF-8?q?fix:=20improve=20table=20column=20width?= =?UTF-8?q?=20allocation=20=E2=80=94=20use=20natural=20widths=20and=20grow?= =?UTF-8?q?=20to=20fill=20terminal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the aggressive maxLine/1.5 ideal-width heuristic with full natural widths. When the total fits within the available terminal width (defaulting to 120 cols), distribute slack proportionally to content columns instead of leaving them cramped. Detect narrow label columns by actual content width (≤8 chars) rather than hardcoded position ([0, 1, -2, -1]). When compression is necessary, start from per-column minimums (longest word) and share the remaining budget proportionally based on each column's deficit. This fixes the "tables too narrow and too tall" issue reported on PR #115 where every column was forced to ~67% of its natural width regardless of available screen real estate. --- src/ui/components/MessageView/markdown.ts | 84 +++++++++++++++-------- 1 file changed, 55 insertions(+), 29 deletions(-) diff --git a/src/ui/components/MessageView/markdown.ts b/src/ui/components/MessageView/markdown.ts index 8c86534..f5b72bc 100644 --- a/src/ui/components/MessageView/markdown.ts +++ b/src/ui/components/MessageView/markdown.ts @@ -231,42 +231,68 @@ function renderTableBorder(rows: string[][], maxWidth?: number): string { const colCount = rows[0].length; const calcW = (cs: number[]) => cs.reduce((a, b) => a + b + 2, 0) + cs.length + 1; - // Ideal widths — longest word / 1.5 so cells can wrap in 2-3 lines - const ideal: number[] = Array.from({ length: colCount }, (_, i) => { + // Natural width per column: longest line + cell padding + const natural: number[] = Array.from({ length: colCount }, (_, i) => { + const texts = rows.map((r) => r[i] ?? ""); + const maxLine = Math.max(4, ...texts.map((t) => visualWidth(t))); + return maxLine + 2; + }); + + // Minimum width per column: longest word + padding (can't go below this) + const minWidths: number[] = Array.from({ length: colCount }, (_, i) => { const texts = rows.map((r) => r[i] ?? ""); - const maxLine = Math.max(...texts.map((t) => visualWidth(t))); const words = texts.flatMap((t) => t.split(/\s+/)); const maxWord = Math.max(4, ...words.map((w) => visualWidth(w))); - return Math.max(maxWord + 2, Math.ceil(maxLine / 1.5)); + return maxWord + 2; }); - const colWidths = [...ideal]; - - // Shrink to fit terminal width - if (maxWidth != null && calcW(colWidths) > maxWidth) { - const narrow = new Set([0, 1, colCount - 2, colCount - 1]); // #, status, count, date - const MIN_NARROW = 6; - const MIN_CONTENT = 12; - const contentCols = Array.from({ length: colCount }, (_, i) => i).filter((i) => !narrow.has(i)); - - // Cap narrow columns first - for (const ci of narrow) colWidths[ci] = Math.min(colWidths[ci], MIN_NARROW); - - // Shrink until we fit - while (calcW(colWidths) > maxWidth) { - // Try narrow columns first - let shrunk = false; - for (const ci of narrow) { - if (colWidths[ci] > 4 && calcW(colWidths) > maxWidth) { - colWidths[ci]--; - shrunk = true; + let colWidths: number[]; + const totalNatural = calcW(natural); + const totalMin = calcW(minWidths); + + const effectiveMax = maxWidth ?? 120; // default to a generous terminal width + + if (totalNatural <= effectiveMax) { + // Content fits comfortably — use natural widths and grow to fill available space + colWidths = [...natural]; + const slack = effectiveMax - totalNatural; + if (slack > 0) { + // Distribute slack proportionally to content columns (skip tiny label columns) + const isLabel = colWidths.map((w) => w <= 8); + const candidates = colWidths.map((w, i) => (isLabel[i] ? 0 : w)); + const totalWeight = candidates.reduce((a, b) => a + b, 0); + if (totalWeight > 0) { + for (let ci = 0; ci < colCount; ci++) { + if (candidates[ci] > 0) { + colWidths[ci] += Math.floor((slack * candidates[ci]) / totalWeight); + } } } - if (shrunk) continue; - // Then content columns - const widest = contentCols.reduce((a, b) => (colWidths[a] > colWidths[b] ? a : b), contentCols[0]); - if (colWidths[widest] > MIN_CONTENT) colWidths[widest]--; - else break; + } + } else if (totalMin >= effectiveMax) { + // Even minimums don't fit — use mins and accept truncation + colWidths = [...minWidths]; + } else { + // Need to compress — start from mins, share remaining budget proportionally + const budget = effectiveMax - totalMin; + const deficits = natural.map((n, i) => Math.max(0, n - minWidths[i])); + const totalDeficit = deficits.reduce((a, b) => a + b, 0); + colWidths = [...minWidths]; + if (totalDeficit > 0) { + for (let ci = 0; ci < colCount; ci++) { + colWidths[ci] += Math.floor((budget * deficits[ci]) / totalDeficit); + } + } + // Distribute any leftover due to flooring + let used = calcW(colWidths); + const deficitByIdx = colWidths.map((w, i) => ({ i, gap: natural[i] - w })); + deficitByIdx.sort((a, b) => b.gap - a.gap); + for (const { i } of deficitByIdx) { + if (used >= effectiveMax) break; + if (colWidths[i] < natural[i]) { + colWidths[i]++; + used = calcW(colWidths); + } } } From abed1495821b1c9d82f870d05e62dd83afffbaa6 Mon Sep 17 00:00:00 2001 From: hcyang Date: Mon, 25 May 2026 11:47:09 +0800 Subject: [PATCH 123/129] =?UTF-8?q?feat(ui):=20=E5=A2=9E=E5=8A=A0=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E5=88=A0=E9=99=A4=E5=8F=8A=E7=9B=B8=E5=85=B3UI?= =?UTF-8?q?=E9=87=8D=E7=BD=AE=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 handleDeleteSession 方法,支持删除会话并更新会话列表 - 删除当前激活会话时,清除屏幕、重置UI状态并显示欢迎界面 - 删除按钮调用封装的删除处理函数,统一逻辑 - 优化 SessionList 中搜索逻辑,调整删除和退格键处理 - 移除 SessionList 文件内重复的 truncate 函数实现 --- src/ui/App.tsx | 181 ++++++++++++++++++++++------------------ src/ui/AppContainer.tsx | 2 +- src/ui/SessionList.tsx | 19 +---- src/ui/constants.ts | 3 + src/ui/utils/index.ts | 24 ++++++ 5 files changed, 132 insertions(+), 97 deletions(-) create mode 100644 src/ui/utils/index.ts diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 3879915..71e9ca3 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -43,6 +43,8 @@ import { PermissionPrompt, type PermissionPromptResult } from "./PermissionPromp import { buildExitSummaryText } from "./exitSummary"; import { RawMode, useRawModeContext } from "./contexts"; import { renderMessageToStdout } from "./components/MessageView/utils"; +import { renderRawModeMessages } from "./utils"; +import { ANSI_CLEAR_SCREEN } from "./constants"; const DEFAULT_MODEL = "deepseek-v4-pro"; const DEFAULT_BASE_URL = "https://api.deepseek.com"; @@ -55,7 +57,7 @@ type AppProps = { onRestart?: () => void; }; -export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React.ReactElement { +function App({ projectRoot, initialPrompt, onRestart }: AppProps): React.ReactElement { const { exit } = useApp(); const { stdout, write } = useStdout(); const { columns, rows } = useWindowSize(); @@ -142,6 +144,33 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. }); }, [projectRoot]); + /** + * Navigate to a sub-view. + */ + const navigateToSubView = useCallback((targetView: View) => { + setShowWelcome(false); + setView(targetView); + }, []); + + /** + * Reset the static view to the welcome screen. + */ + const resetStaticView = useCallback( + (loadedMessages: SessionMessage[], options?: { clearScreen?: boolean }) => { + if (options?.clearScreen) { + process.stdout.write(ANSI_CLEAR_SCREEN); + } + setMessages([]); + setWelcomeNonce((n) => n + 1); + navigateToSubView("chat"); + setTimeout(() => { + setMessages(loadedMessages); + setShowWelcome(true); + }, 0); + }, + [navigateToSubView] + ); + useEffect(() => { if (!busy) { return; @@ -170,6 +199,26 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. [sessionManager] ); + /** + * Reset the app to the welcome screen. + */ + const resetToWelcome = useCallback(async () => { + writeRef.current(ANSI_CLEAR_SCREEN); + sessionManager.setActiveSessionId(null); + setStatusLine(""); + setErrorLine(null); + setRunningProcesses(null); + setActiveStatus(null); + setActiveAskPermissions(undefined); + setPendingPermissionReply(null); + setDismissedQuestionIds(new Set()); + resetStaticView([]); + await refreshSkills(); + }, [sessionManager, resetStaticView, refreshSkills]); + + /** + * Refresh the list of sessions. + */ useEffect(() => { refreshSessionsList(); void refreshSkills(); @@ -182,11 +231,17 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. createOpenAIClient(projectRoot); }, [projectRoot]); + /** + * Initialize MCP servers. + */ useLayoutEffect(() => { const settings = resolveCurrentSettings(projectRoot); void sessionManager.initMcpServers(settings.mcpServers); }, [projectRoot, sessionManager]); + /** + * Dispose the session manager on unmount. + */ useEffect(() => { return () => { sessionManager.dispose(); @@ -216,33 +271,19 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. if (onRestart) { onRestart(); } else { - writeRef.current("\u001B[2J\u001B[3J\u001B[H"); - sessionManager.setActiveSessionId(null); - setMessages([]); - setStatusLine(""); - setErrorLine(null); - setRunningProcesses(null); - setActiveStatus(null); - setActiveAskPermissions(undefined); - setPendingPermissionReply(null); - setDismissedQuestionIds(new Set()); - setShowWelcome(true); - setWelcomeNonce((n) => n + 1); - await refreshSkills(); + await resetToWelcome(); refreshSessionsList(); } return; } if (submission.command === "resume") { - setShowWelcome(false); refreshSessionsList(); - setView("session-list"); + navigateToSubView("session-list"); return; } if (submission.command === "continue" && isCurrentSessionEmpty(sessionManager)) { - setShowWelcome(false); refreshSessionsList(); - setView("session-list"); + navigateToSubView("session-list"); return; } if (submission.command === "undo") { @@ -251,15 +292,13 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setErrorLine("No active session to undo."); return; } - setShowWelcome(false); setUndoTargets(sessionManager.listUndoTargets(activeSessionId)); - setView("undo"); + navigateToSubView("undo"); return; } if (submission.command === "mcp") { - setShowWelcome(false); setMcpStatuses(sessionManager.getMcpStatus()); - setView("mcp-status"); + navigateToSubView("mcp-status"); return; } @@ -311,7 +350,16 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setRunningProcesses(null); } }, - [exit, onRestart, pendingPermissionReply, sessionManager, refreshSkills, refreshSessionsList] + [ + sessionManager, + pendingPermissionReply, + exit, + onRestart, + refreshSkills, + refreshSessionsList, + navigateToSubView, + resetToWelcome, + ] ); const handleInterrupt = useCallback(() => { @@ -384,16 +432,9 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. const reloadActiveSessionView = useCallback( (sessionId: string): void => { - process.stdout.write("\u001B[2J\u001B[3J\u001B[H"); - setMessages([]); - setShowWelcome(false); - setWelcomeNonce((n) => n + 1); - setTimeout(() => { - setMessages(loadVisibleMessages(sessionManager, sessionId)); - setShowWelcome(true); - }, 0); + resetStaticView(loadVisibleMessages(sessionManager, sessionId), { clearScreen: true }); }, - [sessionManager] + [resetStaticView, sessionManager] ); useEffect(() => { @@ -411,21 +452,9 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. const handleSelectSession = useCallback( async (sessionId: string) => { - const currentSessionId = sessionManager.getActiveSessionId(); - if (currentSessionId !== sessionId) { - process.stdout.write("\u001B[2J\u001B[3J\u001B[H"); - } sessionManager.setActiveSessionId(sessionId); // Clear first so resets its index to 0. - setMessages([]); - setShowWelcome(false); - setWelcomeNonce((n) => n + 1); - setView("chat"); - // Load messages after the reset so all static items are rendered. - setTimeout(() => { - setMessages(loadVisibleMessages(sessionManager, sessionId)); - setShowWelcome(true); - }, 0); + resetStaticView(loadVisibleMessages(sessionManager, sessionId), { clearScreen: true }); const session = sessionManager.getSession(sessionId); setStatusLine(session ? buildStatusLine(session) : ""); setRunningProcesses(session?.processes ?? null); @@ -436,7 +465,26 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. } await refreshSkills(sessionId); }, - [pendingPermissionReply, sessionManager, refreshSkills] + [sessionManager, resetStaticView, pendingPermissionReply, refreshSkills] + ); + + const handleDeleteSession = useCallback( + async (id: string): Promise => { + const isActiveSession = sessionManager.getActiveSessionId() === id; + + // If the deleted session is the active one, clear the active session first + if (isActiveSession) { + sessionManager.setActiveSessionId(null); + } + + sessionManager.deleteSession(id); + refreshSessionsList(); + + if (isActiveSession) { + await resetToWelcome(); + } + }, + [sessionManager, refreshSessionsList, resetToWelcome] ); const handleUndoRestore = useCallback( @@ -487,25 +535,13 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. setShowWelcome(false); setMessages([]); // Clear screen to remove stale formatted text. - process.stdout.write("\u001B[2J\u001B[3J\u001B[H"); + process.stdout.write(ANSI_CLEAR_SCREEN); setTimeout(() => { if (nextMode === RawMode.Raw) { // Write all messages directly to stdout for raw scrollback mode. const allMessages = activeSessionId ? loadVisibleMessages(sessionManager, activeSessionId) : []; - for (const msg of allMessages) { - process.stdout.write("\n"); - process.stdout.write(renderMessageToStdout(msg, nextMode) + "\n\n"); - } - if (allMessages.length > 0) { - process.stdout.write("\n\n"); - process.stdout.write(chalk.dim("Press ESC to exit raw mode")); - } else { - process.stdout.write("\n"); - process.stdout.write(chalk.dim("(No messages in this session yet. Start chatting to see them here.)")); - process.stdout.write("\n\n"); - process.stdout.write(chalk.dim("Press ESC to exit raw mode")); - } + renderRawModeMessages(allMessages, nextMode); } else if (activeSessionId) { // Switch to chat view to render messages. handleSelectSession(activeSessionId); @@ -538,22 +574,10 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. if (mode === RawMode.Raw) { // In raw mode, re-render all messages directly to stdout at the new width. // Use process.stdout.write instead of writeRef to avoid Ink interference. - process.stdout.write("\u001B[2J\u001B[3J\u001B[H"); + process.stdout.write(ANSI_CLEAR_SCREEN); const activeSessionId = sessionManager.getActiveSessionId(); const allMessages = activeSessionId ? loadVisibleMessages(sessionManager, activeSessionId) : []; - for (const msg of allMessages) { - process.stdout.write("\n"); - process.stdout.write(renderMessageToStdout(msg, mode) + "\n\n"); - } - if (allMessages.length > 0) { - process.stdout.write("\n\n"); - process.stdout.write(chalk.dim("Press ESC to exit raw mode")); - } else { - process.stdout.write("\n"); - process.stdout.write(chalk.dim("(No messages in this session yet. Start chatting to see them here.)")); - process.stdout.write("\n\n"); - process.stdout.write(chalk.dim("Press ESC to exit raw mode")); - } + renderRawModeMessages(allMessages, mode); return; } @@ -719,12 +743,7 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. onSelect={(id) => void handleSelectSession(id)} onCancel={() => setView("chat")} onDelete={(id) => { - // If the deleted session is the active one, clear it - if (sessionManager.getActiveSessionId() === id) { - sessionManager.setActiveSessionId(null); - } - sessionManager.deleteSession(id); - refreshSessionsList(); + void handleDeleteSession(id); }} /> ) : view === "undo" ? ( @@ -784,6 +803,8 @@ export function App({ projectRoot, initialPrompt, onRestart }: AppProps): React. ); } +export default App; + function isCollapsedThinking(message: SessionMessage, expandedId: string | null): boolean { if (message.role !== "assistant") { return false; diff --git a/src/ui/AppContainer.tsx b/src/ui/AppContainer.tsx index e437b44..c8b3177 100644 --- a/src/ui/AppContainer.tsx +++ b/src/ui/AppContainer.tsx @@ -1,6 +1,6 @@ import React from "react"; import { AppContext } from "./contexts"; -import { App } from "./App"; +import App from "./App"; import { RawModeProvider } from "./contexts/RawModeContext"; const AppContainer: React.FC<{ diff --git a/src/ui/SessionList.tsx b/src/ui/SessionList.tsx index 7d7e04e..82ca797 100644 --- a/src/ui/SessionList.tsx +++ b/src/ui/SessionList.tsx @@ -1,6 +1,7 @@ import React, { useState, useMemo, useCallback } from "react"; import { Box, Text, useInput, useWindowSize } from "ink"; import type { SessionEntry, SessionStatus } from "../session"; +import { truncate } from "./components/MessageView/utils"; type Props = { sessions: SessionEntry[]; @@ -113,17 +114,10 @@ export function SessionList({ sessions, onSelect, onCancel, onDelete }: Props): return; } - // Backspace: remove last search character - if (key.backspace) { - if (searchQuery) { - handleBackspace(); - return; - } - } - // Delete key: remove search character, or start delete confirmation - if (key.delete) { + if (key.delete || key.backspace) { if (searchQuery) { + // remove last search character handleBackspace(); return; } @@ -342,10 +336,3 @@ export function formatSessionStatus(status: SessionStatus): string { return status; } } - -function truncate(value: string, max: number): string { - if (value.length <= max) { - return value; - } - return `${value.slice(0, max)}…`; -} diff --git a/src/ui/constants.ts b/src/ui/constants.ts index 7c74597..43372f8 100644 --- a/src/ui/constants.ts +++ b/src/ui/constants.ts @@ -2,3 +2,6 @@ /** Separator used when rendering command arguments inline (e.g., `arg1 | arg2 | arg3`). */ export const ARGS_SEPARATOR = " | "; + +/** ANSI escape code to clear the screen. */ +export const ANSI_CLEAR_SCREEN = "\u001B[2J\u001B[3J\u001B[H"; diff --git a/src/ui/utils/index.ts b/src/ui/utils/index.ts new file mode 100644 index 0000000..4b498a0 --- /dev/null +++ b/src/ui/utils/index.ts @@ -0,0 +1,24 @@ +import chalk from "chalk"; +import type { SessionMessage } from "../../session"; +import { renderMessageToStdout } from "../components/MessageView/utils"; +import type { RawMode } from "../contexts"; + +/** + * Render all messages directly to stdout for Raw mode display. + * Writes each message followed by the "Press ESC to exit raw mode" footer. + */ +export function renderRawModeMessages(allMessages: SessionMessage[], mode: string | RawMode): void { + for (const msg of allMessages) { + process.stdout.write("\n"); + process.stdout.write(renderMessageToStdout(msg, mode as RawMode) + "\n\n"); + } + if (allMessages.length > 0) { + process.stdout.write("\n\n"); + process.stdout.write(chalk.dim("Press ESC to exit raw mode")); + } else { + process.stdout.write("\n"); + process.stdout.write(chalk.dim("(No messages in this session yet. Start chatting to see them here.)")); + process.stdout.write("\n\n"); + process.stdout.write(chalk.dim("Press ESC to exit raw mode")); + } +} From 679eb003515d15a9bf2c6f3d147650cd5d768fb9 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 25 May 2026 14:45:39 +0800 Subject: [PATCH 124/129] feat: enhance markdown table rendering with CJK support and improved width handling --- src/tests/markdown.test.ts | 55 ++++++++++++++++++++++- src/ui/components/MessageView/index.tsx | 10 +++-- src/ui/components/MessageView/markdown.ts | 54 ++++++++++++---------- 3 files changed, 92 insertions(+), 27 deletions(-) diff --git a/src/tests/markdown.test.ts b/src/tests/markdown.test.ts index a0127fc..bc5d33c 100644 --- a/src/tests/markdown.test.ts +++ b/src/tests/markdown.test.ts @@ -1,11 +1,26 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { renderMarkdown } from "../ui"; +import { renderMarkdown, renderMarkdownSegments } from "../ui"; function stripAnsi(text: string): string { return text.replace(/\[[0-9;]*m/g, ""); } +function visualWidth(text: string): number { + let width = 0; + for (const ch of text) { + const code = ch.codePointAt(0) ?? 0; + width += + ch.length >= 2 || + (code >= 0x2e80 && code <= 0xa4cf) || + (code >= 0xf900 && code <= 0xfaff) || + (code >= 0xff00 && code <= 0xffe6) + ? 2 + : 1; + } + return width; +} + test("renderMarkdown returns empty string for empty input", () => { assert.equal(renderMarkdown(""), ""); }); @@ -38,3 +53,41 @@ test("renderMarkdown handles plain text unchanged in stripped form", () => { const result = stripAnsi(renderMarkdown(text)); assert.equal(result, text); }); + +test("renderMarkdownSegments renders CJK table cells within the requested width", () => { + const table = [ + "| 编号 | 状态 | 任务 | 备注 |", + "|---|---|---|---|", + "| 1 | ✅ | 写代码 | 这是一个很长很长的中文备注用于验证表格在终端宽度不足时是否能够自动换行而不是溢出 |", + ].join("\n"); + + const segment = renderMarkdownSegments(table, 60).find((item) => item.kind === "table"); + assert.ok(segment); + const lines = stripAnsi(segment.body).split("\n"); + assert.equal(lines[0].startsWith("┌"), true); + assert.equal(lines.at(-1)?.startsWith("└"), true); + assert.equal( + lines.every((line) => visualWidth(line) <= 60), + true + ); + assert.equal(lines.length > 4, true); +}); + +test("renderMarkdown preserves empty table cells", () => { + const result = stripAnsi(renderMarkdown("| A | B | C |\n|---|---|---|\n|x||z|", 80)); + const bodyRow = result.split("\n").find((line) => line.includes("x") && line.includes("z")); + assert.ok(bodyRow); + assert.equal((bodyRow.match(/│/g) ?? []).length, 4); +}); + +test("renderMarkdown keeps text separated from rendered table blocks", () => { + const result = stripAnsi(renderMarkdown("Before\n| A | B |\n|---|---|\n| 1 | 2 |\nAfter", 40)); + assert.equal(result.includes("Before\n┌"), true); + assert.equal(result.includes("┘\nAfter"), true); +}); + +test("renderMarkdown does not render tables inside code fences", () => { + const result = stripAnsi(renderMarkdown("```md\n| A | B |\n|---|---|\n| 1 | 2 |\n```", 40)); + assert.equal(result.includes("| A | B |"), true); + assert.equal(result.includes("┌"), false); +}); diff --git a/src/ui/components/MessageView/index.tsx b/src/ui/components/MessageView/index.tsx index 093dbc2..9c31551 100644 --- a/src/ui/components/MessageView/index.tsx +++ b/src/ui/components/MessageView/index.tsx @@ -71,9 +71,13 @@ export function MessageView({ message, collapsed, width = 80 }: MessageViewProps ? renderMarkdownSegments(content, Math.max(20, contentWidth - 4)).map((seg, i) => { if (seg.kind === "table") { return ( - - {seg.body} - + + {seg.body.split("\n").map((line, lineIndex) => ( + + {line} + + ))} + ); } return {seg.body}; diff --git a/src/ui/components/MessageView/markdown.ts b/src/ui/components/MessageView/markdown.ts index f5b72bc..3ebb58b 100644 --- a/src/ui/components/MessageView/markdown.ts +++ b/src/ui/components/MessageView/markdown.ts @@ -18,7 +18,11 @@ export type MarkdownSegment = export function renderMarkdown(text: string, maxWidth?: number): string { return renderMarkdownSegments(text, maxWidth) .map((s) => s.body) - .join(""); + .reduce((out, body) => { + if (!out) return body; + if (!body) return out; + return out.endsWith("\n") || body.startsWith("\n") ? out + body : `${out}\n${body}`; + }, ""); } /** Render markdown, returning typed segments so the caller can choose the @@ -128,6 +132,12 @@ function splitTableBlocks(text: string): TableBlock[] { }; const sepRe = /^\|?\s*:?[-]{3,}:?\s*(\|\s*:?[-]{3,}:?\s*)*\|?\s*$/; + const parseRow = (row: string) => { + let body = row.trim(); + if (body.startsWith("|")) body = body.slice(1); + if (body.endsWith("|")) body = body.slice(0, -1); + return body.split("|").map((s) => s.trim()); + }; for (let i = 0; i < lines.length; i++) { const line = lines[i]; @@ -143,22 +153,12 @@ function splitTableBlocks(text: string): TableBlock[] { if (isHeader && !inTable) { flushText(); inTable = true; - tableRows = [ - trimmed - .split("|") - .filter(Boolean) - .map((s) => s.trim()), - ]; + tableRows = [parseRow(trimmed)]; continue; } if (isRow && inTable) { - tableRows.push( - trimmed - .split("|") - .filter(Boolean) - .map((s) => s.trim()) - ); + tableRows.push(parseRow(trimmed)); continue; } @@ -229,21 +229,26 @@ function renderTableBorder(rows: string[][], maxWidth?: number): string { if (rows.length === 0) return ""; const colCount = rows[0].length; + const normalizedRows = rows.map((row) => + Array.from({ length: colCount }, (_, i) => { + return row[i] ?? ""; + }) + ); const calcW = (cs: number[]) => cs.reduce((a, b) => a + b + 2, 0) + cs.length + 1; - // Natural width per column: longest line + cell padding + // Natural width per column, measured as terminal cells rather than UTF-16 units. const natural: number[] = Array.from({ length: colCount }, (_, i) => { - const texts = rows.map((r) => r[i] ?? ""); + const texts = normalizedRows.map((r) => r[i] ?? ""); const maxLine = Math.max(4, ...texts.map((t) => visualWidth(t))); - return maxLine + 2; + return maxLine; }); - // Minimum width per column: longest word + padding (can't go below this) + // Keep minimums small so long CJK text or unbroken tokens can wrap by character. const minWidths: number[] = Array.from({ length: colCount }, (_, i) => { - const texts = rows.map((r) => r[i] ?? ""); - const words = texts.flatMap((t) => t.split(/\s+/)); - const maxWord = Math.max(4, ...words.map((w) => visualWidth(w))); - return maxWord + 2; + const headerWidth = visualWidth(normalizedRows[0]?.[i] ?? ""); + const labelColumn = natural[i] <= 12; + const minReadable = labelColumn ? natural[i] : Math.max(4, Math.min(headerWidth, 12)); + return Math.min(natural[i], minReadable); }); let colWidths: number[]; @@ -270,8 +275,11 @@ function renderTableBorder(rows: string[][], maxWidth?: number): string { } } } else if (totalMin >= effectiveMax) { - // Even minimums don't fit — use mins and accept truncation colWidths = [...minWidths]; + while (calcW(colWidths) > effectiveMax && colWidths.some((w) => w > 1)) { + const widest = colWidths.reduce((maxIdx, width, idx) => (width > colWidths[maxIdx] ? idx : maxIdx), 0); + colWidths[widest]--; + } } else { // Need to compress — start from mins, share remaining budget proportionally const budget = effectiveMax - totalMin; @@ -327,7 +335,7 @@ function renderTableBorder(rows: string[][], maxWidth?: number): string { return lines.length > 0 ? lines : [""]; }; - const wrapped = rows.map((r) => r.map((c, ci) => wrapCell(c, colWidths[ci]))); + const wrapped = normalizedRows.map((r) => r.map((c, ci) => wrapCell(c, colWidths[ci]))); const heights = wrapped.map((wr) => Math.max(1, ...wr.map((lines) => lines.length))); const pad = (s: string, w: number) => s + " ".repeat(Math.max(0, w - visualWidth(s))); From 670b118cd64c28a01c0a1ae985279e0807300e2d Mon Sep 17 00:00:00 2001 From: hcyang Date: Mon, 25 May 2026 15:10:37 +0800 Subject: [PATCH 125/129] =?UTF-8?q?fix(session):=20=E5=A4=84=E7=90=86?= =?UTF-8?q?=E6=9D=83=E9=99=90=E6=8B=92=E7=BB=9D=E7=8A=B6=E6=80=81=E4=B8=8E?= =?UTF-8?q?=E7=95=8C=E9=9D=A2=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 permission_denied 会话状态表示权限被拒绝 - 添加 denySessionPermission 方法以更新会话状态为拒绝并设置失败原因 - 在权限拒绝时清除提示草稿并调用拒绝权限处理逻辑 - 中断会话时清除提示草稿以防止残留输入 - 会话列表中新增 permission_denied 状态对应的 UI 状态映射为 denied --- src/session.ts | 17 ++++++++++++++++- src/ui/App.tsx | 3 +++ src/ui/SessionList.tsx | 4 ++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/session.ts b/src/session.ts index c81ae4a..4b34f20 100644 --- a/src/session.ts +++ b/src/session.ts @@ -159,7 +159,8 @@ export type SessionStatus = | "waiting_for_user" | "completed" | "interrupted" - | "ask_permission"; + | "ask_permission" + | "permission_denied"; export type ModelUsage = { prompt_tokens: number; @@ -1532,6 +1533,20 @@ ${skillMd} return !this.sessionControllers.has(sessionId); } + /** + * Mark a session's permission as denied by the user. + * Updates the session entry status and failReason so the denial is visible in the session list. + */ + denySessionPermission(sessionId: string, reason?: string): void { + const now = new Date().toISOString(); + this.updateSessionEntry(sessionId, (entry) => ({ + ...entry, + status: "permission_denied", + failReason: reason ?? "Permission denied by user", + updateTime: now, + })); + } + adjustActiveBashTimeout(deltaMs: number): BashTimeoutAdjustment | null { const sessionId = this.activeSessionId; if (!sessionId || !Number.isFinite(deltaMs)) { diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 71e9ca3..ae94fa0 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -669,6 +669,8 @@ function App({ projectRoot, initialPrompt, onRestart }: AppProps): React.ReactEl alwaysAllows: result.alwaysAllows, }); setStatusLine("Permission denied. Add a reply, then press Enter to continue."); + setPromptDraft(null); + sessionManager.denySessionPermission(sessionId); return; } void handlePrompt({ @@ -686,6 +688,7 @@ function App({ projectRoot, initialPrompt, onRestart }: AppProps): React.ReactEl sessionManager.interruptActiveSession(); setActiveStatus("interrupted"); setActiveAskPermissions(undefined); + setPromptDraft(null); refreshSessionsList(); }, [refreshSessionsList, sessionManager]); diff --git a/src/ui/SessionList.tsx b/src/ui/SessionList.tsx index 82ca797..2d83b84 100644 --- a/src/ui/SessionList.tsx +++ b/src/ui/SessionList.tsx @@ -332,6 +332,10 @@ export function formatSessionStatus(status: SessionStatus): string { return "failed"; case "interrupted": return "stopped"; + case "ask_permission": + return "waiting"; + case "permission_denied": + return "denied"; default: return status; } From f1ecc26f4cf9f29c820138d005cfa604a76ffce4 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 25 May 2026 16:03:22 +0800 Subject: [PATCH 126/129] feat: update the MCP spawn to avoid DEP0190 problem --- src/mcp/mcp-client.ts | 61 +++++++++++++++++++++++++----------- src/tests/mcp-client.test.ts | 34 ++++++++++++++++++++ 2 files changed, 76 insertions(+), 19 deletions(-) create mode 100644 src/tests/mcp-client.test.ts diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts index b859bf5..26a7a32 100644 --- a/src/mcp/mcp-client.ts +++ b/src/mcp/mcp-client.ts @@ -1,6 +1,5 @@ import { spawn, type ChildProcess } from "child_process"; import { createInterface, type Interface } from "readline"; -import * as os from "os"; import * as path from "path"; import { killProcessTree } from "../common/process-tree"; @@ -97,6 +96,13 @@ type ReadResourceResult = { export type McpNotificationHandler = (method: string, params?: Record) => void; +export type McpSpawnSpec = { + command: string; + args: string[]; + shell: boolean; + windowsHide?: boolean; +}; + export class McpClient { private process: ChildProcess | null = null; private reader: Interface | null = null; @@ -130,25 +136,14 @@ export class McpClient { ...this.env, }; const args = this.withNpxYesArg(this.command, this.args); + const spawnSpec = createMcpSpawnSpec(this.command, args); - const isWindows = os.platform() === "win32"; - - if (isWindows) { - // On Windows, shell: true lets cmd.exe resolve the command via - // PATHEXT (npx → npx.cmd, etc.) without blindly appending .cmd, - // which would break absolute paths like process.execPath. - this.process = spawn(this.command, args, { - stdio: ["pipe", "pipe", "pipe"], - env: childEnv, - shell: true, - windowsHide: true, - }); - } else { - this.process = spawn(this.command, args, { - stdio: ["pipe", "pipe", "pipe"], - env: childEnv, - }); - } + this.process = spawn(spawnSpec.command, spawnSpec.args, { + stdio: ["pipe", "pipe", "pipe"], + env: childEnv, + shell: spawnSpec.shell, + windowsHide: spawnSpec.windowsHide, + }); let resolved = false; const safeReject = (err: Error) => { @@ -421,3 +416,31 @@ export class McpClient { return new Error(stderr ? `${message}. stderr: ${stderr}` : message); } } + +export function createMcpSpawnSpec( + command: string, + args: string[], + platform: NodeJS.Platform = process.platform +): McpSpawnSpec { + if (platform === "win32") { + return { + // On Windows, shell: true lets cmd.exe resolve the command via PATHEXT + // (npx -> npx.cmd, etc.). Pass one quoted command line with no spawn + // args to avoid Node 24 DEP0190. + command: [command, ...args].map(quoteWindowsShellArg).join(" "), + args: [], + shell: true, + windowsHide: true, + }; + } + + return { + command, + args, + shell: false, + }; +} + +function quoteWindowsShellArg(arg: string): string { + return `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/\\+$/g, "$&$&")}"`; +} diff --git a/src/tests/mcp-client.test.ts b/src/tests/mcp-client.test.ts new file mode 100644 index 0000000..e161aad --- /dev/null +++ b/src/tests/mcp-client.test.ts @@ -0,0 +1,34 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createMcpSpawnSpec } from "../mcp/mcp-client"; + +test("createMcpSpawnSpec keeps non-Windows MCP launches shell-free", () => { + assert.deepEqual(createMcpSpawnSpec("npx", ["-y", "@playwright/mcp@latest"], "darwin"), { + command: "npx", + args: ["-y", "@playwright/mcp@latest"], + shell: false, + }); +}); + +test("createMcpSpawnSpec avoids Windows shell args for Node 24", () => { + assert.deepEqual(createMcpSpawnSpec("npx", ["-y", "@playwright/mcp@latest"], "win32"), { + command: '"npx" "-y" "@playwright/mcp@latest"', + args: [], + shell: true, + windowsHide: true, + }); +}); + +test("createMcpSpawnSpec quotes Windows command paths and arguments", () => { + const spec = createMcpSpawnSpec( + String.raw`C:\Program Files\nodejs\node.exe`, + [String.raw`C:\tmp\mcp server.cjs`, 'a "quoted" value'], + "win32" + ); + + assert.equal( + spec.command, + String.raw`"C:\Program Files\nodejs\node.exe" "C:\tmp\mcp server.cjs" "a \"quoted\" value"` + ); + assert.deepEqual(spec.args, []); +}); From a1b31c635263d22c486559f2c029242d51e35462 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 25 May 2026 16:15:14 +0800 Subject: [PATCH 127/129] feat(session): Add support for permission_denied status --- src/session.ts | 3 ++- src/tests/session.test.ts | 51 +++++++++++++++++++++++++++++++++++ src/tests/sessionList.test.ts | 2 ++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/session.ts b/src/session.ts index 4b34f20..a9fc39e 100644 --- a/src/session.ts +++ b/src/session.ts @@ -2730,7 +2730,8 @@ ${skillMd} status === "waiting_for_user" || status === "completed" || status === "interrupted" || - status === "ask_permission" + status === "ask_permission" || + status === "permission_denied" ) { return status; } diff --git a/src/tests/session.test.ts b/src/tests/session.test.ts index e0a863e..95de8e3 100644 --- a/src/tests/session.test.ts +++ b/src/tests/session.test.ts @@ -1313,6 +1313,57 @@ test("activateSession pauses for permission when a tool call requires ask", asyn ); }); +test("SessionManager preserves permission_denied status when sessions are reloaded", async () => { + const workspace = createTempDir("deepcode-permission-denied-workspace-"); + const home = createTempDir("deepcode-permission-denied-home-"); + setHomeDir(home); + + const permissions = { + allow: [], + deny: [], + ask: [], + defaultMode: "askAll" as const, + }; + const manager = createPermissionSessionManager( + workspace, + [ + { + choices: [ + { + message: { + content: "", + tool_calls: [ + { + id: "call-bash", + type: "function", + function: { + name: "bash", + arguments: JSON.stringify({ + command: "rg TODO src", + description: "Search TODO markers", + sideEffects: ["read-in-cwd"], + }), + }, + }, + ], + }, + }, + ], + }, + ], + permissions + ); + + const sessionId = await manager.createSession({ text: "search todos" }); + manager.denySessionPermission(sessionId); + + const reloadedManager = createPermissionSessionManager(workspace, [], permissions); + const reloadedSession = reloadedManager.getSession(sessionId); + + assert.equal(reloadedSession?.status, "permission_denied"); + assert.equal(reloadedSession?.failReason, "Permission denied by user"); +}); + test("replySession applies permission replies, runs pending tools, and stores always allow scopes", async () => { const workspace = createTempDir("deepcode-permission-allow-workspace-"); const home = createTempDir("deepcode-permission-allow-home-"); diff --git a/src/tests/sessionList.test.ts b/src/tests/sessionList.test.ts index 3dfda33..6fe41c7 100644 --- a/src/tests/sessionList.test.ts +++ b/src/tests/sessionList.test.ts @@ -18,6 +18,8 @@ test("formatSessionStatus maps status values to display labels", () => { assert.equal(formatSessionStatus("waiting_for_user"), "waiting"); assert.equal(formatSessionStatus("failed"), "failed"); assert.equal(formatSessionStatus("interrupted"), "stopped"); + assert.equal(formatSessionStatus("ask_permission"), "waiting"); + assert.equal(formatSessionStatus("permission_denied"), "denied"); assert.equal(formatSessionStatus("unknown_status" as any), "unknown_status"); }); From 09ae2b43f02a5dbb0c1e36e0825d8910b17061b0 Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 25 May 2026 16:29:49 +0800 Subject: [PATCH 128/129] chore: clean up non-project files --- Screenshot_2026-05-23_195028.png | 0 docs/issue_0522.md | 241 ------------------------------- 2 files changed, 241 deletions(-) delete mode 100644 Screenshot_2026-05-23_195028.png delete mode 100644 docs/issue_0522.md diff --git a/Screenshot_2026-05-23_195028.png b/Screenshot_2026-05-23_195028.png deleted file mode 100644 index e69de29..0000000 diff --git a/docs/issue_0522.md b/docs/issue_0522.md deleted file mode 100644 index 2e9fd1a..0000000 --- a/docs/issue_0522.md +++ /dev/null @@ -1,241 +0,0 @@ -# Deep Code Permission System (设计文档) - -scopes是枚举值,列表如下: - -``` -# PermissionScope -read-in-cwd -read-out-cwd -write-in-cwd -write-out-cwd -delete-in-cwd -delete-out-cwd -query-git-log -mutate-git-log -network -mcp -``` - -settings.json的配置项(例子): - -``` -{ - "permissions": { - "allow": [ - "write-in-cwd" - ], - "deny": [ - "write-out-cwd" - ], - "ask": [ - "read-out-cwd" - ], - "defaultMode": "allowAll|askAll" // 默认是allowAll - } -} -``` - -工具和PermissionScope可能的对应关系: - -- read: read-in-cwd, read-out-cwd -- write: write-in-cwd, write-out-cwd -- edit: write-in-cwd, write-out-cwd -- WebSearch: network -- mcp__*: mcp -- bash: 每一次bash命令需要的scope在sideEffects字段中。如果sideEffects字段为undefined|null,或者sideEffects包含了"unknown"则总是ask -- 其他: 无权限要求,总是允许 - -## bash tool的参数schema新增sideEffects字段 - -目标:让LLM在每一次调用`bash`时显式声明该命令可能需要的权限范围,后端只信任这个结构化字段,不从自然语言`description`中推断权限。 - -需要同步修改两处schema: - -1. `src/prompt.ts`里的`getTools()`内置`bash`工具定义。 -2. `templates/tools/bash.md`里的`bash`工具说明和JSON schema示例。 - -新增字段: - -``` -sideEffects: PermissionScope[] | ["unknown"] -``` - -`bash`可声明的scope只包含文件系统、Git历史和网络权限,不包含`mcp`: - -``` -read-in-cwd -read-out-cwd -write-in-cwd -write-out-cwd -delete-in-cwd -delete-out-cwd -query-git-log -mutate-git-log -network -unknown -``` - -建议schema如下: - -```json -{ - "type": "object", - "properties": { - "command": { - "description": "The command to execute", - "type": "string" - }, - "description": { - "description": "Clear, concise description of what this command does in active voice.", - "type": "string" - }, - "sideEffects": { - "description": "Permission scopes required by this bash command. Use [] only for commands that do not read, write, delete, or access the network. Use [\"unknown\"] when the effects cannot be classified safely.", - "type": "array", - "items": { - "type": "string", - "enum": [ - "read-in-cwd", - "read-out-cwd", - "write-in-cwd", - "write-out-cwd", - "delete-in-cwd", - "delete-out-cwd", - "query-git-log", - "mutate-git-log", - "network", - "unknown" - ] - }, - "uniqueItems": true - } - }, - "required": [ - "command", - "sideEffects" - ], - "additionalProperties": false -} -``` - -字段语义: - -- `sideEffects: []`表示命令不需要权限,例如`date`、`node --version`这类只读取进程环境或输出版本信息的命令。 -- `sideEffects`必须按最小必要权限填写;例如`rg foo src`是`["read-in-cwd"]`,`npm install`通常是`["write-in-cwd", "network"]`。 -- 如果命令访问项目目录之外的路径,需要使用`*-out-cwd`;例如`cat /etc/hosts`是`["read-out-cwd"]`。 -- 删除类操作使用`delete-*`;如果同一条命令还会写入其他文件,再同时声明对应的`write-*`。 -- 查询Git历史使用`query-git-log`;例如`git log`、`git show HEAD`、`git blame`、`git diff HEAD~1..HEAD`这类读取提交历史、提交对象或历史diff的命令。 -- 修改Git历史或引用使用`mutate-git-log`;例如`git commit`、`git reset`、`git rebase`、`git merge`、`git cherry-pick`、`git tag`这类会创建提交、移动引用或改写提交图的命令。 -- Git命令如果同时读写工作区文件,也需要同时声明文件系统scope;例如`git checkout -- src/foo.ts`需要`["write-in-cwd"]`,`git reset --hard HEAD~1`需要`["write-in-cwd", "mutate-git-log"]`。 -- `unknown`只能单独出现为`["unknown"]`,不能和其他scope混用。 - -示例: - -```json -{ "command": "date", "description": "Show current date", "sideEffects": [] } -{ "command": "rg \"TODO\" src", "description": "Search TODO markers in source files", "sideEffects": ["read-in-cwd"] } -{ "command": "npm install", "description": "Install package dependencies", "sideEffects": ["write-in-cwd", "network"] } -{ "command": "rm -rf dist", "description": "Delete build output directory", "sideEffects": ["delete-in-cwd"] } -{ "command": "curl -s https://example.com", "description": "Fetch example.com response", "sideEffects": ["network"] } -{ "command": "git show --stat HEAD", "description": "Show file statistics for HEAD", "sideEffects": ["query-git-log"] } -{ "command": "git blame src/prompt.ts", "description": "Show line authorship for prompt source", "sideEffects": ["read-in-cwd", "query-git-log"] } -{ "command": "git reset --hard HEAD~1", "description": "Reset branch and worktree to previous commit", "sideEffects": ["write-in-cwd", "mutate-git-log"] } -``` - -## 核心数据结构设计 - -``` -export type UserPromptContent = { - text?: string; - imageUrls?: string[]; - skills?: SkillInfo[]; -+ permissions?: [{toolCallId: "...", permission: "allow|deny"}]; -+ alwaysAllows?: [""]; -}; - -export type SessionEntry = { - id: string; - ... - toolCalls: unknown[] | null; // 例如:[{"id":"...","function":{"name":"bash","arguments":"{\"command\": \"...\", \"description\": \"...\"}"}}] - status: SessionStatus; -+ askPermissions?: [{toolCallId: "...", scopes: [""], name: "...", command: "...", description?: "..."}]; -}; - -export type SessionStatus = "... | "completed" | "interrupted" | "ask_permission"; // 新增 ask_permission 状态 - -export type SessionMessage = { - ... - meta?: MessageMeta; - ... -}; - -export type MessageMeta = { - ... -+ permissions?: [{toolCallId: "...", permission: "allow|deny|ask"}]; -+ userPrompt?: UserPromptContent; //对于role为user的消息,持久化userPrompt可方便后续排查问题 -}; -``` - -## 前端流程 - -如果当前会话状态不是ask_permission,则保持现状。会话状态是ask_permission时: - -对SessionEntry.askPermissions中每一个toolCallId的每一个scope,显示权限弹窗(示例): - -``` - - - - - - Do you want to proceed? - ❯ 1. Yes - 2. Yes, and always allow - 3. No -``` - -注意对于read/write/edit的``,格式可以是"工具名称+相对或绝对文件路径",例如:`read ~/dev/main.c` - -如果在权限弹窗过程中,用户按Esc,则走现有的interrupt流程(会话状态也应该变成"interrupted")。 - -提醒注意一种情况:例如askPermissions里面有好几个item的scopes是`["write-in-cwd"]`,如果用户已经在第一个权限弹窗选了"always allow write in CWD `~/dev/qrcode_test/`",则后面的几个scopes是`["write-in-cwd"]`的item就不用显示权限弹窗了。 - -如果用户完成了所有权限弹窗的选择,则判断: - -1. 如果用户提交的结果中包含deny,则需要用户输入user prompt,按回车手动提交replySession()。 - - 如果用户没有输入user prompt就退出了,或者切换到了其他会话。则重新开始这个会话时,由于会话状态还是ask_permission,则会重新显示权限弹窗,要求用户选择。 -2. 如果用户提交的结果中不包含deny,则以`/continue`作为UserPromptContent.text内容,前端自动提交replySession()。 - - -## 后端流程 - -后端主要是对replySession()和activateSession()进行升级: - -1. 支持传入UserPromptContent.permissions和alwaysAllows -2. 如果UserPromptContent.alwaysAllows非空,将其中的scopes追加写入项目级别的settings.json配置文件(`permissions.allow`字段),避免重复写入已存在的项。 -3. 检查当前会话消息列表末尾是否存在连续的role为assistant的有tool_calls的消息,也就是"待执行消息"。如果没有,则走现有流程。 -4. 对于每一条待执行消息,先检查UserPromptContent.permissions中对应的toolCallId的用户授权是allow还是deny - - 如果是allow,则正常执行这个toolCall - - 如果是deny,则直接返回失败结果,报错信息提示LLM用户禁用相关权限。例如: - ``` - { - "ok": false, - "name": "edit", - "error": "用户已禁用了在项目目录之外修改文件的权限,请不要尝试用任何方式修改目录之外的文件" - } - ``` -5. 如果对于某条待执行消息,在UserPromptContent.permissions没有出现对应的toolCallId的用户授权,则检查它的 SessionMessage.meta.permissions[].permission 是allow还是deny还是ask - - 如果是allow,则正常执行这个toolCall - - 如果是deny,则直接返回失败结果,报错信息提示LLM用户禁用相关权限 - - 如果是ask,则直接返回失败结果,报错信息提示LLM用户未授权执行。例如: - ``` - { - "ok": false, - "name": "edit", - "error": "用户暂未授权执行,如果有必要,可重新尝试执行" - } - ``` - - 如果不存在,则正常执行这个toolCall(兼容老版本会话数据) -6. 当LLM返回了新的待执行消息时,不要立即执行,而是: - 1. 根据配置的permissions和defaultMode,计算出SessionMessage.meta.permissions字段 - 2. 如果存在一个待执行消息的SessionMessage.meta.permissions[].permission是ask,则把SessionEntry.status设置为"ask_permission",并设置好SessionEntry.askPermissions,然后退出activateSession,这样就回到了上面的前端流程。 From d07d225a072ffea03bcac41d5b6ab70bc46575cb Mon Sep 17 00:00:00 2001 From: Ji Zhang Date: Mon, 25 May 2026 16:42:02 +0800 Subject: [PATCH 129/129] 0.1.25 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 12b9abc..dfa3fbb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.24", + "version": "0.1.25", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@vegamo/deepcode-cli", - "version": "0.1.24", + "version": "0.1.25", "license": "MIT", "dependencies": { "chalk": "^5.6.2", diff --git a/package.json b/package.json index ef70520..71c171c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@vegamo/deepcode-cli", - "version": "0.1.24", + "version": "0.1.25", "description": "Deep Code CLI - Vibe coding for the deepseek-v4 model in your terminal", "license": "MIT", "type": "module",