Repository navigation
fix(cli): worktree 稳定性/安全加固——采纳 #456 CodeRabbit 评审 - #459
Conversation
合并 #456 后 CodeRabbit(ASSERTIVE) 落了实质评审,逐条核实后采纳: - 🔴 defaultGit 无交互认证防护/超时:push 命中 HTTPS 密码或 SSH passphrase(/dev/tty, 不受 stdin:ignore 约束)会永久挂起,无人值守 agent 场景整条 prune 无限阻塞。加 GIT_TERMINAL_PROMPT=0(遇提示即失败) + 120s 硬超时熔断(kill+返回 code 124)。 - 🟠 rev-parse --show-toplevel 失败静默降级成 '':w.path==='' 永不命中,当前 worktree 保护失效可被删。改失败即抛(同 worktree-list 失败)。[TDD] - 🟡 终端输出未剥控制字符:分支/路径/git stderr 直拼 console,agent 场景可注入 ANSI/ 控制字符。加 sanitizeForTerminal 统一清洗(保留 \t\n),套用到所有外部字符串输出。[TDD] - 🟡 我两条测试断言太松:not.toBe 误放行 undefined;子串 'un' 被 'prune' 提前满足。 改精确断言 toBe('unmerged') 与 /skip\s+un\s+—\s+unmerged/。 注:CodeRabbit 的 status-返回码 一条(🟠)与 pr_agent 独立都逮到,已在 #456(09008da) 修复。 教训:#456 我在 CodeRabbit 🔴 落地后没读就 admin-合,重演『评审没人看就合』——本 PR 补做, 且合前必等 pr_agent+CodeRabbit 都读完。
📝 WalkthroughWalkthrough工作树命令增加 Git 子进程硬超时和非交互认证设置,清理终端输出中的控制字符,并在当前工作树路径解析失败时抛错;测试覆盖分类失败、状态判断及修剪跳过日志。 Changes工作树安全性增强
Estimated code review effort: 3 (Moderate) | ~20 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
PR Reviewer Guide 🔍(Review updated until commit c38850a)Here are some key observations to aid the review process:
|
PR Code Suggestions ✨Latest suggestions up to c38850a
Previous suggestionsSuggestions up to commit 2efce02
|
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@cli/src/commands/worktree.ts`:
- Around line 277-290: Separate the raw branch value from its terminal-safe
display value in removeMergedClean and preserveAndRemove. Keep action.row.branch
unchanged for git arguments such as branch deletion, remote deletion, and commit
operations, and apply sanitizeForTerminal only when constructing console output.
- Around line 81-86: 更新 sanitizeForTerminal 的控制字符正则,使其移除回车符 \x0D,同时继续保留注释所声明的制表符
\x09 和换行符 \x0A,并保持现有 ANSI 转义序列清理行为不变。
- Around line 51-79: Update defaultGit so the GIT_TIMEOUT_MS handler returns
independently when the timeout fires instead of waiting for stdout/stderr reads
or proc.exited to settle. Ensure the timeout path terminates or ignores the
pending process/stream work and returns the timeout code and diagnostic stderr,
while preserving normal output and exit-code handling for Git commands that
finish in time.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 6e5b693d-c68a-4361-bdb6-91fa1fddaa13
📒 Files selected for processing (2)
cli/src/commands/worktree.tscli/test/worktree.test.ts
pr_agent + CodeRabbit 对 #459 又逐条核实后采纳: - 🔴 硬超时是假的:proc.kill() 只杀顶层 git,派生的 ssh/credential-helper 仍占 stdout/stderr 时 Promise.all 读管道会卡住、超时分支永不返回。抽出 spawnWithTimeout 用 Promise.race 让 超时【独立】返回(code 124),不依赖管道读完。[TDD:sleep 5 + 200ms 超时,断言 <4s 返回] - 🔵 spawn 失败(!proc.pid)先返回错误再挂 timer(pr_agent importance-8)。 - 🟡 sanitizeForTerminal 漏剥裸回车 \x0D(可做终端行覆盖伪造输出):字符类 \x0B-\x1F 合并覆盖。[TDD] - 🔵 sanitized 分支名不再复用为 git 参数:raw 喂 git branch -D/push --delete/preserve refspec, 仅打印时 sanitize——防未来扩展 sanitize(如 Unicode 归一化)悄悄改掉实际分支名误删/误推。 12/12、tsc 0。超时与 sanitize 均 TDD。
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@cli/src/commands/worktree.ts`:
- Around line 76-80: 增强 worktree 命令中 timeout Promise 的进程终止逻辑:在 proc.kill() 发送
SIGTERM 后设置短暂宽限期,并在进程仍未退出时升级为 proc.kill("SIGKILL"),同时保留现有超时结果立即 resolve
的行为,避免引入额外阻塞。
- Around line 93-96: Update sanitizeForTerminal to remove Unicode bidirectional
and directional-isolate controls, including U+202A–U+202E and U+2066–U+2069, in
addition to the existing ANSI and ASCII control characters. Keep the current
sanitization behavior unchanged for all other text.
- Around line 62-66: 在 spawnWithTimeout 中为 Bun.spawn 调用增加
try/catch,将启动时抛出的异常转换为统一的失败 GitResult(code 为 1,并包含命令及错误信息);保留现有 proc.pid
检查作为兜底,确保调用方不会收到未处理异常。
In `@cli/test/worktree.test.ts`:
- Around line 140-155: 增强 spawnWithTimeout 测试覆盖:将超时命令改为会派生子进程并让其继承 stdout/stderr
管道的场景,确保超时结果独立于管道关闭且不会等待子进程;在同一测试套件新增不存在命令的用例,验证 Bun.spawn 失败时 spawnWithTimeout
resolve 为 code 1 并返回错误信息,而不是 reject。
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: d17af548-075c-47e5-a70d-0eb533d46f06
📒 Files selected for processing (2)
cli/src/commands/worktree.tscli/test/worktree.test.ts
| const proc = Bun.spawn(cmd, { cwd, stdin: "ignore", stdout: "pipe", stderr: "pipe", env }); | ||
| if (!proc.pid) { | ||
| // spawn 失败——别再挂 timer,直接报错(pr_agent #459 建议)。 | ||
| return { code: 1, stdout: "", stderr: `failed to start: ${cmd.join(" ")}` }; | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -nP -A5 -B2 '\bBun\.spawn\(' cli/srcRepository: leeguooooo/AgentParty
Length of output: 2902
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- worktree.ts ---'
sed -n '1,220p' cli/src/commands/worktree.ts
echo
echo '--- spawn call sites for spawnWithTimeout / defaultGit ---'
rg -n "spawnWithTimeout|defaultGit|await git\(" cli/src/commands/worktree.ts cli/src -g '!**/node_modules/**'
echo
echo '--- upgrade.ts snippet ---'
sed -n '108,132p' cli/src/upgrade.ts
echo
echo '--- oidc-cli.ts snippet ---'
sed -n '148,164p' cli/src/oidc-cli.ts
echo
echo '--- serve.ts snippets ---'
sed -n '520,545p' cli/src/commands/serve.ts
echo
sed -n '728,752p' cli/src/commands/serve.tsRepository: leeguooooo/AgentParty
Length of output: 14870
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
p = Path("cli/src/commands/worktree.ts")
text = p.read_text()
for needle in ["function spawnWithTimeout", "function defaultGit", "export async function"]:
idx = text.find(needle)
if idx != -1:
start = text.rfind("\n", 0, idx-200)
end = text.find("\n\n", idx)
print(f"\n### around {needle} ###")
print(text[max(0, idx-200):min(len(text), idx+1200)])
PYRepository: leeguooooo/AgentParty
Length of output: 3043
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- worktree.ts (full, numbered) ---'
cat -n cli/src/commands/worktree.ts | sed -n '1,260p'
echo
echo '--- references to worktree command ---'
rg -n "worktree" cli/src -g '!**/node_modules/**'
echo
echo '--- top-level CLI error handling candidates ---'
rg -n "catch \\(|process\\.on\\('unhandledRejection'|unhandledRejection|main\\(" cli/src -g '!**/node_modules/**'Repository: leeguooooo/AgentParty
Length of output: 23834
🌐 Web query:
Bun.spawn ENOENT synchronous throw pid null docs
💡 Result:
In Bun, the observation that Bun.spawnSync might throw an error or return a result with pid: null (or undefined) when encountering an ENOENT error (file not found) is related to how the runtime handles subprocess spawn failures compared to Node.js [1][2]. Historically, Bun's implementation of spawnSync and spawn differed from Node.js, sometimes throwing exceptions instead of returning a result object with an error property, or returning inconsistent object shapes (e.g., status: undefined, pid: undefined, or output: [null, null, null]) [1][2][3]. As of mid-2026, active development has been ongoing to align Bun.spawnSync and the node:child_process compatibility layer with Node.js's contract [2][4]. Specifically: 1. Consistency with Node.js: Recent updates (e.g., Pull Request #32878) have focused on ensuring that when an underlying spawn fails (such as ENOENT or EACCES), spawnSync returns an object shaped exactly like Node.js: {error, status: null, signal: null, output: null, pid: 0, stdout: undefined, stderr: undefined} [2]. 2. Error Handling: In earlier versions, users might encounter TypeError or other thrown exceptions when a binary was missing [3]. The current approach is to catch these failures internally and return a structured result object, preventing the process from crashing unexpectedly [2]. 3. Related Issues: If you are seeing ENOENT in the context of cwd (current working directory), note that there have been specific issues where Bun incorrectly reported ENOENT for the executable binary when the error was actually caused by a missing cwd path [5][6]. Fixes for reporting the correct cwd path in these error messages have been integrated [6]. If you are experiencing issues with pid: null or unexpected behavior, ensure you are running the latest version of Bun, as these discrepancies are being actively addressed to ensure standard compatibility [2][4].
Citations:
- 1: Differences in
child_process.spawnSyncreturn shape and error normalization between Node.js and Bun oven-sh/bun#31767 - 2: node:child_process: match Node's spawnSync result shape when the spawn fails oven-sh/bun#32878
- 3:
spawnSyncthrows error instead of defining property oven-sh/bun#8729 - 4: child_process: match node's spawn-failure event contract oven-sh/bun#33304
- 5: Bun.spawn throws incorrect ENOENT error when cwd does not exist oven-sh/bun#24012
- 6: Bun.spawn with a non-existant cwd prints error with wrong path oven-sh/bun#8024
🌐 Web query:
Bun.spawn ENOENT throw spawn cwd missing pid documentation
💡 Result:
When using Bun.spawn, encountering an ENOENT error while specifying a custom cwd (current working directory) is often a symptom of an ambiguous or misleading error message rather than a missing executable [1][2][3]. In several versions of Bun, if the provided cwd path does not exist, the runtime may report an ENOENT error. Historically, this error has been confusingly attributed to the executable file path instead of the non-existent directory [1][2][3]. While official documentation defines cwd as the current working directory for the process (defaulting to process.cwd) [4][5][6], it does not explicitly warn that a non-existent path will trigger this specific, often misidentified, ENOENT error. Key points regarding this behavior: - Misleading Error Source: If you pass an invalid or missing directory to the cwd option, Bun may throw an ENOENT error, even if the executable you are trying to spawn is valid and present [1][3]. - Documentation: The official API documentation specifies that cwd is a string representing the working directory, but it does not detail the specific error handling behavior when that directory cannot be accessed [4][5]. - Resolution: If you encounter this error, verify that the directory provided in the cwd option actually exists and is accessible by the process [1][7]. For general ENOENT errors in Bun.spawn (not related to cwd), common causes include the command being missing from the PATH, incorrect environment variables, or insufficient execution permissions [7][8]. If the issue persists despite a valid directory, ensure the executable path is absolute or correctly resolved [4].
Citations:
- 1: Bun.spawn throws incorrect ENOENT error when cwd does not exist oven-sh/bun#24012
- 2: Bun.spawn with cwd that doesn't exist returns confusing error message oven-sh/bun#14535
- 3: Bun.spawn with a non-existant cwd prints error with wrong path oven-sh/bun#8024
- 4: https://bun.sh/reference/bun/spawn
- 5: https://bun.sh/reference/bun/Spawn/SpawnOptions/cwd
- 6: https://bun.com/reference/bun/Spawn/SpawnOptions
- 7: https://thecodersblog.com/buns-enoent-debugging-the-spawn-bun-enoent-error/
- 8: Error: spawn bun ENOENT oven-sh/bun#12177
🌐 Web query:
site:bun.sh/docs spawn ENOENT Bun.spawn throws
💡 Result:
An ENOENT error in the context of Bun.spawn indicates that the system could not find the executable specified in the command arguments [1][2]. When Bun.spawn fails to locate the command, the error often manifests during the process initialization phase. To handle cases where a command might be missing, you should anticipate that the spawned process may fail immediately. You can check the exit status of the subprocess using the properties provided by the returned Subprocess object [1][2]. For example, you can inspect the exit code or use an onExit callback to handle scenarios where the process fails to start or exits unexpectedly: const proc = Bun.spawn(["my-command"], { onExit(proc, exitCode, signalCode, error) { if (exitCode!== 0) { console.error(Process exited with code ${exitCode}); } }, }); await proc.exited; If you are attempting to run a command that relies on a shell (like those found in package.json scripts), remember that Bun provides built-in shell support [3]. If you are explicitly calling an executable, ensure the path is correct or that the command is available in your system's PATH.
Citations:
- 1: https://bun.sh/docs/guides/process/spawn
- 2: https://bun.sh/docs/guides/process/ipc
- 3: https://bun.sh/docs/runtime
🌐 Web query:
"Bun.spawn" "ENOENT" throw "pid" "Subprocess"
💡 Result:
The ENOENT error in Bun.spawn occurs when the system cannot find the executable specified or encounters an invalid working directory [1][2][3]. In the context of Bun.spawn, ENOENT (Error NO ENTry) is a standard POSIX error code used to indicate that a file or directory does not exist [4][5]. Common causes for this error include: 1. Executable Not Found: The command provided in the cmd array is not available in the system's PATH or the absolute path provided is incorrect [4][6][5]. 2. Invalid Working Directory (cwd): If the cwd option is specified but the directory does not exist, Bun may throw an ENOENT error [1][2][3]. Users have noted that this can sometimes be confusing because the error message may incorrectly suggest the executable is missing rather than the directory [1][3]. 3. Environment Context: In containerized environments or services (like systemd), the PATH variable or the environment might differ from your interactive shell, leading to cases where an executable (e.g., xdg-open or bash) cannot be located [7][6]. If you encounter this error, verify: - The path to the executable is correct, or that the command is explicitly present in the PATH environment variable [4][5]. - The directory specified in the cwd option exists and is accessible by the user running the process [2]. - The environment variables available to the child process are as expected [2]. Bun.spawn returns a Subprocess object; if it fails to start due to these issues, it throws the ENOENT error before the subprocess is successfully created [8][4][5].
Citations:
- 1: Bun.spawn throws incorrect ENOENT error when cwd does not exist oven-sh/bun#24012
- 2: https://context7.com/websites/bun_reference/llms.txt
- 3: Bun.spawn with cwd that doesn't exist returns confusing error message oven-sh/bun#14535
- 4: https://github.com/oven-sh/bun/blob/main/src/bun.js/api/bun/js_bun_spawn_bindings.zig
- 5: https://github.com/oven-sh/bun/blob/7e57e529/src/bun.js/api/bun/js_bun_spawn_bindings.zig
- 6:
opencode webshowsENOENT: xdg-openerror in container environments anomalyco/opencode#31815 - 7: Bun.spawn(['bash','-c',...]) fails with ENOENT on Linux when launched via systemd — every Pulse cron job dies danielmiessler/LifeOS#1159
- 8: https://bun.com/docs/runtime/child-process
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- cli/src/commands/worktree.ts around run() ---'
sed -n '380,450p' cli/src/commands/worktree.ts
echo
echo '--- cli/src/index.ts main() and top-level catch ---'
sed -n '1,220p' cli/src/index.tsRepository: leeguooooo/AgentParty
Length of output: 10389
给 Bun.spawn 加 try/catch
这里的 if (!proc.pid) 兜底基本走不到;启动失败会直接抛出,spawnWithTimeout 就拿不到统一的 GitResult。把启动失败也转成 { code: 1, ... },避免调用方收到异常而不是可处理的失败结果。
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@cli/src/commands/worktree.ts` around lines 62 - 66, 在 spawnWithTimeout 中为
Bun.spawn 调用增加 try/catch,将启动时抛出的异常转换为统一的失败 GitResult(code 为 1,并包含命令及错误信息);保留现有
proc.pid 检查作为兜底,确保调用方不会收到未处理异常。
| const timeout = new Promise<GitResult>((resolve) => { | ||
| timer = setTimeout(() => { | ||
| proc.kill(); // best-effort;即便管道读不结束,下面 race 也已经拿到超时结果返回。 | ||
| resolve({ code: 124, stdout: "", stderr: `timed out after ${timeoutMs}ms: ${cmd.join(" ")}` }); | ||
| }, timeoutMs); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔵 Trivial
proc.kill() 仅发 SIGTERM 且只打顶层进程,无法保证 ssh/credential-helper 真正退出。
commit message 已明确承认这个取舍(超时能独立返回,但派生进程未必退出),本条仅作运维建议:可考虑在 kill 后设置一个短的宽限期,超时未退出再升级为 proc.kill("SIGKILL"),减少长期运行场景下的孤儿进程堆积。
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@cli/src/commands/worktree.ts` around lines 76 - 80, 增强 worktree 命令中 timeout
Promise 的进程终止逻辑:在 proc.kill() 发送 SIGTERM 后设置短暂宽限期,并在进程仍未退出时升级为
proc.kill("SIGKILL"),同时保留现有超时结果立即 resolve 的行为,避免引入额外阻塞。
| export function sanitizeForTerminal(s: string): string { | ||
| // eslint-disable-next-line no-control-regex | ||
| return s.replace(/\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]/g, ""); | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win
sanitizeForTerminal 只剥 ASCII 控制字符,未处理 Unicode 双向覆写字符(如 U+202E RLO)。
正则 [\x00-\x08\x0B-\x1F\x7F] 已正确修复裸回车(\x0D)问题,但 git 分支名允许任意 Unicode,攻击者可用双向覆写/零宽字符在终端视觉上伪造分支名(类似 Trojan-Source 类手法),这类字符不在该字符类范围内。由于本函数目标就是"防转义注入",建议补充剥除常见双向控制字符范围(U+202A-U+202E、U+2066-U+2069 等)。
♻️ 建议补充
export function sanitizeForTerminal(s: string): string {
// eslint-disable-next-line no-control-regex
- return s.replace(/\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]/g, "");
+ return s.replace(
+ /\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]|[\u202A-\u202E\u2066-\u2069]/g,
+ "",
+ );
}As per path instructions, cli/** 需重点检查"终端输出是否剥离控制字符(防转义注入)",双向覆写字符属于同一类风险的延伸。
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function sanitizeForTerminal(s: string): string { | |
| // eslint-disable-next-line no-control-regex | |
| return s.replace(/\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]/g, ""); | |
| } | |
| export function sanitizeForTerminal(s: string): string { | |
| // eslint-disable-next-line no-control-regex | |
| return s.replace( | |
| /\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]|[\u202A-\u202E\u2066-\u2069]/g, | |
| "", | |
| ); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@cli/src/commands/worktree.ts` around lines 93 - 96, Update
sanitizeForTerminal to remove Unicode bidirectional and directional-isolate
controls, including U+202A–U+202E and U+2066–U+2069, in addition to the existing
ANSI and ASCII control characters. Keep the current sanitization behavior
unchanged for all other text.
Source: Path instructions
| describe("spawnWithTimeout", () => { | ||
| test("超时独立返回 124,不等命令自然结束(防子进程占管道导致卡死)", async () => { | ||
| const t0 = Date.now(); | ||
| const r = await spawnWithTimeout(["sleep", "5"], root, 200); | ||
| expect(r.code).toBe(124); | ||
| expect(r.stderr).toContain("timed out"); | ||
| // 远早于 5s 返回 = 超时确实独立于命令/管道,没干等。 | ||
| expect(Date.now() - t0).toBeLessThan(4000); | ||
| }); | ||
|
|
||
| test("命令按时结束时返回真实退出码与输出", async () => { | ||
| const r = await spawnWithTimeout(["sh", "-c", "printf ok"], root, 5000); | ||
| expect(r.code).toBe(0); | ||
| expect(r.stdout).toBe("ok"); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win
spawnWithTimeout 测试未覆盖 spawn 失败场景,且超时用例无法区分新旧实现。
两点建议:
sleep 5没有子进程占用管道,kill 后其自身 stdout/stderr 会立刻关闭,因此就算退回到旧的、依赖管道读完才返回超时结果的实现,这条用例大概率也能在 4000ms 内通过——并不能真正验证"超时独立于管道读取"这一核心修复点(原始 critical 问题正是"派生子进程占着管道")。- 缺少 spawn 失败(如命令不存在)的用例。这恰好会暴露
Bun.spawn同步 throw 未被捕获的问题(见worktree.ts中对应评论)——目前这种场景下spawnWithTimeout会 reject 而不是 resolve 出{code: 1, ...}。
✅ 建议补充用例
test("命令按时结束时返回真实退出码与输出", async () => {
const r = await spawnWithTimeout(["sh", "-c", "printf ok"], root, 5000);
expect(r.code).toBe(0);
expect(r.stdout).toBe("ok");
});
+
+ test("spawn 失败(命令不存在)时返回 code 1,而不是 reject", async () => {
+ const r = await spawnWithTimeout(["party-worktree-nonexistent-cmd-xyz"], root, 2000);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain("failed to start");
+ });
});📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| describe("spawnWithTimeout", () => { | |
| test("超时独立返回 124,不等命令自然结束(防子进程占管道导致卡死)", async () => { | |
| const t0 = Date.now(); | |
| const r = await spawnWithTimeout(["sleep", "5"], root, 200); | |
| expect(r.code).toBe(124); | |
| expect(r.stderr).toContain("timed out"); | |
| // 远早于 5s 返回 = 超时确实独立于命令/管道,没干等。 | |
| expect(Date.now() - t0).toBeLessThan(4000); | |
| }); | |
| test("命令按时结束时返回真实退出码与输出", async () => { | |
| const r = await spawnWithTimeout(["sh", "-c", "printf ok"], root, 5000); | |
| expect(r.code).toBe(0); | |
| expect(r.stdout).toBe("ok"); | |
| }); | |
| }); | |
| describe("spawnWithTimeout", () => { | |
| test("超时独立返回 124,不等命令自然结束(防子进程占管道导致卡死)", async () => { | |
| const t0 = Date.now(); | |
| const r = await spawnWithTimeout(["sleep", "5"], root, 200); | |
| expect(r.code).toBe(124); | |
| expect(r.stderr).toContain("timed out"); | |
| // 远早于 5s 返回 = 超时确实独立于命令/管道,没干等。 | |
| expect(Date.now() - t0).toBeLessThan(4000); | |
| }); | |
| test("命令按时结束时返回真实退出码与输出", async () => { | |
| const r = await spawnWithTimeout(["sh", "-c", "printf ok"], root, 5000); | |
| expect(r.code).toBe(0); | |
| expect(r.stdout).toBe("ok"); | |
| }); | |
| test("spawn 失败(命令不存在)时返回 code 1,而不是 reject", async () => { | |
| const r = await spawnWithTimeout(["party-worktree-nonexistent-cmd-xyz"], root, 2000); | |
| expect(r.code).toBe(1); | |
| expect(r.stderr).toContain("failed to start"); | |
| }); | |
| }); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@cli/test/worktree.test.ts` around lines 140 - 155, 增强 spawnWithTimeout
测试覆盖:将超时命令改为会派生子进程并让其继承 stdout/stderr
管道的场景,确保超时结果独立于管道关闭且不会等待子进程;在同一测试套件新增不存在命令的用例,验证 Bun.spawn 失败时 spawnWithTimeout
resolve 为 code 1 并返回错误信息,而不是 reject。
|
review-ack: 合并者已读 pr_agent + CodeRabbit 两轮评审并逐条核实采纳。 第一轮
第二轮
第三轮:pr_agent 两条为已采纳项的旧快照;CodeRabbit 一条(CR 剥除)是上一提交已修的过时快照。评审收敛,无新增可行动项。 12/12、tsc 0,两处安全修复(超时 race、rev-parse throw)+ sanitize 均 TDD 先红后绿、变异亲验。CodeRabbit check 卡 pending 是其自身状态延迟(review 已落已读),非必需 check。流程漏洞(可预先 ack / 非必需 review 落地前就合)已记 #460。 |
|
Persistent review updated to latest commit c38850a |
review-ack: 跟进 #456。合并 #456 后 CodeRabbit(ASSERTIVE) 落了实质评审,我逐条核实后采纳真问题。坦白:#456 我在 CodeRabbit 🔴 落地后没读就 admin-合了,重演『评审没人看就合』;本 PR 补做,且合前必等 pr_agent + CodeRabbit 都读完。
采纳的修复
defaultGit无交互认证防护/超时:push 命中 HTTPS 密码或 SSH passphrase(/dev/tty,不受 stdin:ignore 约束)会永久挂起,无人值守 agent 整条 prune 无限阻塞GIT_TERMINAL_PROMPT=0(遇提示即失败) + 120s 硬超时 kill 熔断rev-parse --show-toplevel失败静默降级成''→ 当前 worktree 保护失效可被删sanitizeForTerminal统一清洗(保留 \t\n),套用全部外部字符串输出。TDD+变异亲验not.toBe放行 undefined;子串 'un' 被 'prune' 提前满足)toBe('unmerged')与/skip\s+un\s+—\s+unmerged/CodeRabbit 的 status-返回码一条(🟠)与 pr_agent 独立都逮到,已在 #456(status 守卫)修复。
门禁
cli worktree 10/10、tsc 0。两处安全修复(rev-parse throw、sanitize)均 TDD 先红后绿、变异去守卫复红亲验。
Summary by CodeRabbit