* fix(core,cli): replace full-history structuredClone with shallow/tail variants to prevent OOM on resume
Several UI and service call sites clone the entire chat history via
structuredClone(getHistory()) every turn. On a resumed session with
thousands of entries, each clone allocates 150-200 MB transiently.
When multiple async side-requests overlap (suggestion generation,
auto-title, checkpointing), multiple clones coexist on the heap,
pushing V8 past its limit within 10 turns (2 GB heap cap).
Changes:
- AppContainer.tsx: use getHistoryTail(40, true) instead of
getHistory(true) + slice(-40)
- btwCommand.ts: same pattern, use getHistoryTail(40, true)
- sessionTitle.ts: use getHistoryShallow() (read-only filtering)
- sessionRecap.ts: use getHistoryShallow() (read-only filtering)
- useGeminiStream.ts: use getHistoryShallow() for checkpoint
serialization (only needs to survive JSON.stringify)
Closes#4624
* fix(test): update mocks for getHistoryShallow/getHistoryTail in sessionTitle and btwCommand tests
* fix(cli): migrate remaining getHistory() clone sites to shallow/tail variants
- AppContainer.tsx rewind path: getHistory() → getHistoryShallow()
(only used read-only by computeApiTruncationIndex)
- Session.ts ACP rewind: getHistory() → getHistoryShallow()
(only walks entries to compute truncation index)
- Session.ts stop-hook: getHistory() + filter(.model).pop() →
getLastModelMessageText() (O(1) backward scan, no clone)
* fix(core): use client-level getHistoryShallow with fallback
sessionTitle.ts and sessionRecap.ts were calling
chat.getHistoryShallow() directly, bypassing the client-level
wrapper that provides a getHistory() fallback when the chat
implementation doesn't support shallow reads. Use
geminiClient.getHistoryShallow() instead.
Update test mocks to match the new call site.
* fix(test): add getHistoryShallow and getLastModelMessageText to Session test mocks
Session.ts now calls chat.getHistoryShallow() in rewindToTurn and
chat.getLastModelMessageText() in the Stop hook. Update all mockChat
instances in Session.test.ts to provide these methods.
Detach closeSession/killSession from the session entry's owning channel instead of the current attach target, so the correct channel is decremented and killed during channel overlap (old channel dying while a fresh channel is current). Extracts findChannelInfoForEntry/detachSessionIdFromEntryChannel helpers with unit + integration coverage. Fixes#4325.
* fix(core): preserve uid/gid in atomicWriteFile to avoid breaking shared-write files
atomicWriteFile uses write-to-tmp + rename for crash atomicity. POSIX
rename creates a new inode owned by the calling process's euid/egid, so
the rename silently strips the original uid/gid. On shared-write setups
(e.g. a group-writable file owned by another user in a shared workspace
where the current user has group-write access), every Write/Edit/
NotebookEdit through qwen-code would reset ownership to the running
user and effectively revoke write access for the original collaborators.
The fix:
1. If the target exists and is owned by a different uid/gid than the
process's effective uid/gid (and we are not root), fall back to
in-place writeFile. This truncates the existing inode in place,
preserving uid/gid. The trade-off is loss of crash atomicity for
this specific case — an acceptable trade for not silently breaking
shared-write file ownership.
2. If running as root, atomic rename is still used, and ownership is
restored via chown(uid, gid) after the rename. Root can chown back;
non-root cannot, hence the in-place fallback for non-root.
3. Windows is unaffected (no POSIX ownership semantics).
Tests:
- New: in-place fallback on uid mismatch — verify content updates, mode
preserved, and inode unchanged (the inode is the signal that the
fallback path ran rather than rename).
- New: same scenario triggered via gid mismatch.
- New: positive case — ownership matches → atomic rename → inode changes.
Regression: a v0.16.0 user reported "every write turns a world-writable
file into one other users can no longer write." Bisected to #4096 which
introduced atomicWriteFile + write-to-tmp + rename.
* fix(core): route root through in-place fallback + doc/test follow-ups
Review follow-ups on the atomic-write ownership fix:
1. Remove the root-special-case (rename + post-rename chown). chown
silently fails inside user-namespaced or CAP_CHOWN-stripped Docker
containers, which re-triggers the original bug for root-in-Docker
users — exactly the scenario this fix was reported against. Routing
root through the same in-place fallback as non-root eliminates this
failure mode and drops an untestable branch (chown-back can't be
exercised under non-root CI).
2. Document the three properties traded away by the in-place fallback:
crash atomicity, concurrent-reader isolation, inotify watcher
semantics (MODIFY vs MOVED_TO).
3. Document that the in-place fallback surfaces EACCES when the file's
mode forbids the current user from writing — this is correct
behavior (atomic rename used to silently replace files the user had
no permission on, which was arguably a privilege issue).
4. Replace the brittle "see step 6 in the function doc" comment with a
step-number-independent reference.
5. New test covering the EACCES path: chmod 0o444 + mocked geteuid
triggers the fallback, fallback hits the read-only file, EACCES
propagates cleanly, original content is preserved.
* fix(core): harden in-place fallback against symlink/unlink/inode races + doc/test follow-ups
Review follow-ups on #4431 ownership-preservation fix:
CRITICAL — in-place fallback security hardening (wenshao review):
The path-based `fs.writeFile(targetPath, ...)` fallback introduced
three races that the prior `rename(tmp, target)` form did not have:
1. Non-regular files (FIFO/socket/device): fs.writeFile calls
open(O_WRONLY|O_CREAT|O_TRUNC). On a FIFO this blocks forever
waiting for a reader. On a character/block device it writes to
the actual device. The rename path replaced these with a
regular file.
2. Symlink-swap TOCTOU: an attacker with parent-dir write can swap
targetPath for a symlink between our stat and our writeFile.
fs.writeFile follows symlinks at the destination; POSIX rename
does not. In the very "shared-write workspace / Docker bind-mount"
scenarios this PR targets, this lets a directory-writable
attacker redirect agent writes elsewhere (e.g. /etc/passwd if
the agent runs as root).
3. Unlink race: if targetPath is unlinked between stat and write,
O_CREAT silently recreates it owned by the calling user — the
exact ownership change the fallback was designed to prevent.
Silent regression to the pre-fix bug under this race.
Fix: extract the fallback into writeInPlaceWithFdGuards():
- open(target, O_WRONLY | O_TRUNC | O_NOFOLLOW) — no O_CREAT, so
unlink-race surfaces ENOENT instead of silently recreating; and
O_NOFOLLOW rejects symlink-swaps with ELOOP.
- fstat(fd) verifies the bound inode's uid/gid still match
existingStat — refuses the write if an inode-swap happened
between stat and open.
- Write through the fd (locked to the verified inode), chmod
through the fd, close.
Caller now gates the fallback on existingStat.isFile() — non-regular
targets fall through to the atomic path which has well-defined
"replace special-file with regular-file" semantics.
DOC / TEST follow-ups:
- Add hardlink-propagation as a 4th trade-off in the in-place
fallback JSDoc (review comment #4): rename creates a new inode so
sibling hardlinks keep old content; in-place truncate+write keeps
the inode so all hardlinks see new content.
- Update atomicWriteJSON JSDoc to note the write is now
*conditionally* atomic (review comment #5): atomic when uid/gid
matches the process, in-place when ownership differs. Previously
the JSDoc still claimed unconditional atomicity.
- Update caller comments at runtimeStatus.ts and
worktreeSessionService.ts that advertised crash-atomic writes via
tmp+rename — those guarantees are now conditional (review
comment #6).
- Add mode + tmp-leftover assertions to the gid-mismatch test to
match the uid-mismatch test (review comment #2 — test
consistency). Without these, a gid-fallback regression that
silently dropped permissions or left a tmp file would not be
caught.
- New test: FIFO + ownership mismatch must take the atomic path,
not in-place (verifies the existingStat.isFile() guard works;
hang on in-place would trip vitest timeout).
- New test: writing through a symlink with ownership mismatch
exercises the resolve-then-stat-then-open flow and verifies the
symlink itself is preserved.
Tests: 192/192 pass (atomicFileWrite + write-file + edit +
fileSystemService).
* fix(core): defer O_TRUNC and verify dev+ino in writeInPlaceWithFdGuards
PR #4431 review follow-up (wenshao critical):
The previous form opened with `O_WRONLY | O_TRUNC | O_NOFOLLOW`, which
truncated the bound file *before* the fd-bound fstat verification ran.
If an attacker swapped the path between the caller's stat and our
open, we would truncate the attacker's substituted inode (destroying
unrelated content) before detecting the swap.
Two fixes:
1. Open without O_TRUNC. Verify dev+ino+uid+gid+isFile match
expectedStat through fh.stat(). Only then call fh.truncate(0)
through the validated fd.
2. Expand the verification beyond uid+gid to include dev+ino+isFile.
uid+gid alone misses a same-owner inode swap (attacker replaces
the path with a different inode they own). dev+ino is the strong
identity check; isFile catches a swap to FIFO/socket/device after
the caller's existingStat.isFile() gate.
JSDoc updated to enumerate the four guards (NOFOLLOW, no CREAT, no
TRUNC at open, dev+ino+uid+gid+isFile via fstat) and explain why
truncation must wait until after verification.
192/192 tests pass.
* fix(core): close FIFO swap race with O_NONBLOCK + cover EOWNERSHIP_CHANGED path
PR #4431 review follow-up (deepseek-v4-pro via /review):
CRITICAL — FIFO swap TOCTOU:
The caller's `existingStat.isFile()` gate uses stat data captured
earlier. An attacker with parent-dir write can swap the regular file
for a FIFO between the caller's stat and our open inside
`writeInPlaceWithFdGuards`. The previous `O_WRONLY | O_NOFOLLOW` open
would then block indefinitely waiting for a FIFO reader; O_NOFOLLOW
only catches symlinks.
Fix: add O_NONBLOCK to the open flags. Defense in depth:
- On a reader-less FIFO, `open(O_WRONLY | O_NONBLOCK)` returns ENXIO
immediately — no hang.
- If the FIFO has a reader (open succeeds), the subsequent fstat
isFile() check still refuses the write via EOWNERSHIP_CHANGED.
- For regular files, O_NONBLOCK is a no-op.
CRITICAL test gap — EOWNERSHIP_CHANGED branch untested:
The primary TOCTOU defense (fdStat dev/ino/uid/gid/isFile vs
expectedStat) had no coverage. Exported `writeInPlaceWithFdGuards` so
it can be unit-tested directly:
- New test: simulate post-stat inode swap (unlink + recreate at same
path), call helper with stale stat, assert EOWNERSHIP_CHANGED and
that the attacker's content survives.
- New test: simulate post-stat regular→FIFO swap, assert open fails
fast (ENXIO) or fstat catches it — either way no hang, no write.
DOC fix:
JSDoc said "we open read-write without truncating" but the code uses
O_WRONLY. Wording corrected to "write-only".
194/194 tests pass.
* fix(core): fix flaky inode-swap test + apply review follow-ups
PR #4431 review follow-up (glm-5.1 via /review) — 7 suggestions adopted,
1 partially adopted, 0 rejected:
CI FIX (Ubuntu test failure on tmpfs inode reuse):
The EOWNERSHIP_CHANGED inode-swap test used unlink+create to simulate
a post-stat swap. On Linux tmpfs the freshly-freed inode number is
often reused by the immediately-following create, so dev+ino remained
identical and the guard didn't trip (intermittent on Ubuntu CI; macOS
APFS happened to allocate different inodes). Switched to rename(decoy,
target) which moves an existing distinct inode into place, guaranteed
to differ from the original.
CODE:
- Wrap fh.writeFile failure after fh.truncate(0) with
EINPLACE_WRITE_FAILED + cause, so callers see explicitly that the
file was truncated and the write didn't complete (otherwise they
see raw ENOSPC/EIO and may wrongly assume the original is intact
given this lives in atomicFileWrite.ts).
- Skip fh.chmod when euid is neither root nor expectedStat.uid —
chmod is guaranteed to fail with EPERM in that case (POSIX requires
owner or root). Avoids a guaranteed-failing syscall on every call.
- Caller catches ENOENT from writeInPlaceWithFdGuards and falls
through to atomic rename path. If the file was deleted between
caller's stat and our open there is no ownership to preserve; the
rename path correctly creates a new file at targetPath.
DOC:
- Replaced "defends against four races" with "hardened against
post-stat races" (the bullet list has 5 items, the count was wrong).
- Reworded "non-regular targets must not reach this function" to
describe defense-in-depth — O_NONBLOCK + !fdStat.isFile() reject
post-stat regular→FIFO/socket/device swaps. The old wording made
it look like O_NONBLOCK was redundant.
- Documented the dual chmod behavior (root vs non-root with foreign
uid) inline.
TESTS:
- Added happy-path test for writeInPlaceWithFdGuards (write succeeds,
inode preserved, mode preserved).
- Added ENOENT regression test (verifies the missing-O_CREAT
property — if file unlinked between stat and open, no silent
recreate with caller's uid).
- Renamed the misleading "O_NOFOLLOW guard" test (it actually tests
resolve-through-symlink, not O_NOFOLLOW) to reflect what it does,
and added a direct ELOOP test that drives writeInPlaceWithFdGuards
with a path whose final component is a symlink — that's the real
O_NOFOLLOW exercise.
- Fixed the FIFO test to pass a stat captured from the FIFO itself
(not a stale regular-file stat) so only the FIFO-specific defense
fires, not the inode/dev mismatch from a different file.
NOT ADOPTED:
- Skip-when-non-root chmod optimization adopted (small, useful), but
the larger "structured chmod error model" deferred — best-effort
matches the existing tryChmod pattern at file scope.
197/197 tests pass.
* fix(core): wrap truncate err + post-write nlink check + guard close + chmod sync
PR #4431 review follow-up (qwen-latest-series-invite-beta-v34 via /review)
— 7 of 10 suggestions adopted, 3 deferred:
CODE:
- **EINPLACE_TRUNCATE_FAILED wrap** (review #3291863048): symmetric to
the existing EINPLACE_WRITE_FAILED — distinguishes "truncate failed,
original intact" from "write failed post-truncate, original lost".
- **Post-write nlink === 0 check** (review #3291863059):
EINODE_UNLINKED_DURING_WRITE detects the fstat-to-close window where
a concurrent rename-over drops our bound inode's link count to zero
and our write goes to an anonymous inode close will free. Silent
data loss path now surfaces.
- **fh.close() guarded in finally** (review #3291863044): close failure
on NFS/FUSE was masking the original try-body exception (including
the meaningful EOWNERSHIP_CHANGED, EINPLACE_*, EINODE_*). flush:true
already fsync'd, so close-after-flush is best-effort.
- **fdStat.uid in canChmod** (review #3291863055 part 1): use the
fd-bound verified value instead of expectedStat.uid. Defense in depth
— a future weakening of the fstat guard won't silently widen chmod
privilege.
- **fh.sync() after chmod** (review #3291863053): chmod is metadata,
not covered by writeFile({ flush: true }). A crash before lazy
metadata flush would lose the mode restoration (matters for
setuid/setgid). One extra syscall, best-effort.
- **@remarks freshness contract** (review #3291863051 partial): JSDoc
now spells out that expectedStat MUST be a fresh stat captured
immediately before the call. Stale stats nullify every guard.
- **Concurrent-writer limitation noted** (review #3291863061 partial):
added a "Known limitation — no advisory locking" paragraph to JSDoc
rather than adopting flock (Linux-specific, NFS issues, scope
expansion). Callers needing multi-process coordination should layer
their own lockfile.
- **@throws documentation** (review #3291863051 partial): four
documented error codes (EOWNERSHIP_CHANGED, EINODE_UNLINKED_DURING_WRITE,
EINPLACE_TRUNCATE_FAILED, EINPLACE_WRITE_FAILED).
TESTS:
- **EINPLACE_WRITE_FAILED via FileHandle.prototype.writeFile monkey-patch**
(review #3291863040): triggers the data-loss path, asserts the wrapped
code + message + cause, and verifies the file is empty (truncate ran).
- **canChmod=false actually skips chmod** (review #3291863055 part 2):
prior uid-mismatch test had desiredMode === current mode, couldn't
distinguish "skipped" from "no-op". New test uses desiredMode=0o755
on a 0o644 file under canChmod=false → asserts mode stays 0o644.
NOT ADOPTED:
- ENOENT/ELOOP/ENXIO catch extension (review #3291863043): keeping the
strict refusal for swap-to-special-file. Silent fallthrough-to-replace
was pre-PR atomic-rename behavior, but in shared-write workspaces
(this PR's target users) a special-file appearing at the target path
is a signal worth surfacing, not papering over.
- Diagnostic logging (review #3291863049): the function has no logger
dependency today; adding one is an architecture decision outside
this PR's scope. The path taken is implied by the side effects
(inode preserved vs new) but agreed: out-of-band telemetry would
help ops. Defer to follow-up.
- flock advisory locking (review #3291863061 main): scope expansion;
Linux-specific semantics, NFS edge cases. Documented as known
limitation instead.
- Integration test for ENOENT fallthrough at atomicWriteFile level
(review #3291863043 part 1): ESM module bindings prevent monkey-
patching writeInPlaceWithFdGuards from outside. The unit test for
the helper's ENOENT path covers the throwing behavior; the catch is
3 lines and review-visible. Defer until a refactor opens an
injection seam.
- Error code string constants export (review #3291863051 part 3): two
codes don't merit a constant module. Magic strings are fine at this
size.
199/199 tests pass.
* docs(core): sync writeRuntimeStatus JSDoc with conditional-atomic contract
PR #4431 review follow-up: function-level JSDoc still claimed
unconditional "Atomically write" and "never sees a partially written
file", inconsistent with the module-level docblock updated in earlier
commits. Updated to describe the conditional-atomic behavior (atomic
when uid/gid matches, in-place fallback when ownership differs) and
explicitly note the concurrent-reader visibility trade-off in the
fallback path. Links to atomicWriteJSON for the full contract.
Doc-only change. 199/199 tests pass.
* fix(core): add explicit fh.sync() — FileHandle.writeFile ignores flush option
PR #4431 review follow-up (qwen3.7-max via /review):
CRITICAL — FileHandle.writeFile silently ignores flush:
Node.js FileHandle.writeFile takes an early-return path that bypasses
the flush option entirely (the option is only honored on the
path-based fs.writeFile form). Our previous code passed
{ flush: true } to fh.writeFile and relied on the implicit fsync.
The only explicit fh.sync() was nested in the chmod block guarded by
canChmod — which is FALSE precisely when a non-root group member
writes to a group-writable file they don't own (the exact shared-write
scenario this PR targets). Net effect: in that branch, zero fsync.
Data sits in the kernel page cache; a crash before lazy flush leaves
the file empty (truncate succeeded) or partially written.
Fix:
- Drop flush from the fhWriteOptions object (silently ignored anyway).
- Add an explicit `fh.sync()` after writeFile succeeds, gated on
options.flush. Runs BEFORE the chmod block so the canChmod=false
branch also fsyncs.
- The chmod-block fh.sync() becomes metadata-only (covers the mode
change), as the data is already on disk.
Updated comments to reflect the actual semantics rather than the
incorrect "writeFile({ flush: true }) fsyncs" assumption.
TESTS (partial adoption of review #3293252349):
- EINPLACE_TRUNCATE_FAILED: sibling test to EINPLACE_WRITE_FAILED.
Monkey-patches FileHandle.prototype.truncate to throw EIO; asserts
err.code + cause + "original content is intact" message, and
verifies the file's original bytes are unchanged (truncate didn't
run).
- Buffer in in-place fallback: locks in binary fidelity (byte-exact
comparison) so a future encoding-passthrough regression for Buffer
data would be caught.
NOT ADOPTED in this commit:
- EINODE_UNLINKED_DURING_WRITE test: requires post-write fh.stat()
mocking with call-count discrimination (first call: real stat for
verification; second call: nlink=0). The monkey-patch pattern works
but is fragile; deferred to a follow-up that may also refactor the
helper to accept an injectable stat fn for cleaner testability.
201/201 tests pass.
* fix: correct stale flush comment + add fh.sync() regression test
- Fix misleading close() comment that said "flush:true already
fsync'd" — the explicit fh.sync() does the actual fsync, not the
flush option (which is silently ignored on FileHandle.writeFile).
- Add regression test verifying fh.sync() is called when flush:true
and skipped when flush is absent, preventing silent removal of the
core durability fix.
Addresses wenshao review threads from 2026-05-23.
* test: add EINODE_UNLINKED_DURING_WRITE regression test
Monkey-patches FileHandle.stat to return nlink:0 on the post-write
check, verifying the nlink guard throws with the correct error code.
Addresses wenshao review from 2026-05-28.
* simplify: replace writeInPlaceWithFdGuards with plain fs.writeFile
Address yiliang114's review (CHANGES_REQUESTED):
1. [Critical] Remove ~120 lines of fd-level TOCTOU hardening
(writeInPlaceWithFdGuards) — over-engineering for a local CLI.
The in-place fallback now uses plain fs.writeFile + tryChmod,
matching the EXDEV fallback pattern.
2. [Suggestion] Fix macOS GID false-positive: only compare uid in
ownershipWouldChange(). macOS inherits parent dir GID for new
files, so egid !== file.gid was a false positive that needlessly
dropped crash atomicity.
3. [Suggestion] Trim 60+ lines of JSDoc to project style (AGENTS.md:
"default to none, add only when WHY is non-obvious").
Net: -748 lines. 24 tests pass.
* fix: restore Stats type import (TS2304 build failure)
* docs: narrow scope from uid/gid to uid-only preservation
The gid check is intentionally skipped because macOS inherits the
parent directory's GID for new files, making egid !== file.gid a
false positive. Update comments and PR description to match the
actual implementation scope.
* test: add inode assertion to symlink ownership-mismatch test
Proves the in-place fallback actually ran instead of atomic rename.
The Auto-memory / Auto-dream / Auto-skill rows initialized their state
from Config getters, which are frozen at startup and never reflect a
setValue() write. Each /memory reopen re-mounts the dialog and re-reads
that stale snapshot, so a just-flipped toggle appeared to revert. Read the
initial state from the live merged settings instead, matching the existing
write path (bareMode semantics preserved).
Also switch the test's `act` import to `react` — the previously used
@testing-library/react is declared in package.json but not installed, so
the suite could not run — and add a mount/unmount/remount regression test.
* feat(cli): add settings corruption recovery dialog
* fix(cli): address review1 comments – copy instead of rename, clean DEBUG logs & lint
* test(cli): add SettingsCorruptedDialog keyboard navigation & callback coverage
* Update packages/cli/src/config/settings.test.ts
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* Update packages/cli/src/config/settings.ts
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* fix(cli): drop corrupted-path filter, use corruptedPath as sole signal
* fix(test): add missing truncateToItem to mockUIState
* fix(cli): prevent env var stale state and unnecessary normalization writes
* Apply suggestions from code review
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* fix(cli): resolve merge conflict and fix formatting errors from PR review update
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* fix(cli): prevent validateAuthMethod from consuming corruption env vars
* test(settings): fix scope guard test to actually set env vars
* fix(cli): separate corruption warning from migrationWarnings
* fix(ui): extract CORRUPTED_SUFFIX constant to avoid magic string
* fix(ui): emit error on restore failure in onExit handler
* test(ui): strengthen up/down arrow test to assert selection on target line
* test(settings): strengthen double-corruption and scope guard assertions
* test(ui): assert selection moves in onContinue test before pressing Enter
* fix(ui): include corruption dialog in dialogsVisible to suppress global keypress
* fix(ui): resolve type incompatibility in dialogsVisible and test helpers
* fix(cli): block corruption env var injection and harden error handling
Co-Authored-By: wenshao <shaojin.wensj@alibaba-inc.com>
* fix(cli): harden corruption env var guard with helper, comment, and regression test
* fix(cli): add afterSpawn callback to clear corruption env vars after spawn
Co-Authored-By: qwen3.7-max <noreply@qwen-code.ai>
* fix(cli): share mockSpawn instance between default and named exports in relaunch test
* Update packages/cli/src/utils/relaunch.ts
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
---------
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
Co-authored-by: qwen3.7-max <noreply@qwen-code.ai>
* fix(config): load home .env vars before settings ${VAR} resolution (#4466)
${VAR} placeholders in settings.json (e.g. MCP server headers) could not
reference variables defined in ~/.qwen/.env because resolveEnvVarsInObject()
ran before loadEnvironment() loaded the .env file into process.env.
Add preLoadHomeEnvVars() that loads all variables from home-level .env files
(~/.qwen/.env, ~/.env) into process.env in no-override mode before settings
env var resolution. Workspace .env files and settings.env are still handled
by the existing loadEnvironment() call after settings merge.
Fixes#4466
* test: add env var resolution from .env file test (#4466)
* fix(config): use customEnv fallback for home .env resolution (#4466)
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
Signed-off-by: kagura-agent <kagura.agent.ai@gmail.com>
* fix: align .env precedence and fix test mock
- Use ??= in getHomeEnvFallbackVars() so the more-specific file
(~/.qwen/.env) wins over ~/.env, matching dotenv first-occurrence-wins
- Fix test 'QWEN_HOME is set': use customSettingsPath matching the
runtime QWEN_HOME instead of the module-level USER_SETTINGS_PATH
constant (fixes mock mismatch that cascaded into 7 test failures)
- Remove unused homeEnvPath variable (tsc/eslint warning)
- Add debugLogger.warn in catch block for I/O errors
- Document that the dict intentionally skips
PROJECT_ENV_HARDCODED_EXCLUSIONS (substitution scope is narrower
than process.env population)
Signed-off-by: kagura-agent <kagura.agent.ai@gmail.com>
* test: add .env fallback, precedence, and error path tests
Address R2 reviewer suggestions:
- Add ~/.env fallback positive path test (no QWEN_HOME)
- Add precedence test: ~/.qwen/.env wins over ~/.env (first-write-wins)
- Add error path test: readFileSync throws, loadSettings still succeeds
- Add code comment explaining intentional path discrepancy between
getHomeEnvFallbackVars() and getUserLevelEnvPaths()
* docs: clarify customEnv precedence comment per reviewer suggestion
---------
Signed-off-by: kagura-agent <kagura.agent.ai@gmail.com>
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
* fix(cli): stabilize statusline preset ordering
* test(cli): make statusline helper contracts explicit
Add direct coverage for exported statusline preset helper behavior requested during PR review.
Constraint: Address PR #4634 review feedback for direct exported helper tests.
Rejected: Relying on existing integration coverage | Direct tests were requested for exported helper contracts.
Confidence: high
Scope-risk: narrow
Directive: Keep preset item ordering and reasoning formatting contracts directly covered when these helpers change.
Tested: cd packages/cli && npx vitest run src/ui/statusLinePresets.test.ts; cd packages/cli && npx vitest run src/ui/statusLinePresets.test.ts src/ui/components/StatusLineDialog.test.tsx src/ui/hooks/useStatusLine.test.ts; cd packages/cli && npx eslint src/ui/statusLinePresets.ts src/ui/statusLinePresets.test.ts; git diff --check
Not-tested: Full repository test suite.
* fix(core): surface Anthropic empty stream provider errors
* fix(core): address PR #4540 review feedback
- Move convertAnthropicResponseToGemini inside try/catch so converter
errors are redacted the same way as API errors (Critical fix)
- Add regression guard: assert createImpl called once on normal streams
to catch accidental double-request regressions
- Replace provider-specific Chinese mock error with generic '400 quota
exceeded' for portability
- Add comment explaining why test uses message_delta instead of bare
message_stop
Mid-turn user messages (typed during tool execution) were added to UI
history as type 'user', causing isRealUserTurn to count them. But in
the API history, they are merged into the preceding tool_result Content
(alongside functionResponse), making them invisible to isUserTextContent.
This UI/API count mismatch caused computeApiTruncationIndex to return -1,
producing a false "Cannot rewind to a compressed turn" error.
Fix: change mid-turn messages from type 'user' to type 'notification'
in both live and resume paths so isRealUserTurn no longer counts them.
Closes#4579
The auto-compaction notice hardcoded "approached the input token limit"
even when the screenshot-overflow trigger fired. In computer-use sessions
that's misleading: compaction can fire on accumulated tool screenshots
while token usage is far below the window limit (observed: the notice
claimed "approached the input token limit" at ~116K/1M tokens when it was
actually the image-count trigger).
Add ChatCompressionInfo.triggerReason ('token_limit' | 'image_overflow' |
'manual'); compress() sets it to 'image_overflow' when the screenshot
trigger is what let it through the cheap gate. Both the TUI
(useGeminiStream) and ACP (Session) notices now show an accurate clause.
* refactor(core): rewrite compression prompt to 9-section claude-code-style format
Replaces the <state_snapshot> XML template with a numbered 9-section
structure that mandates verbatim preservation of user messages, including
the historical chronological list (section 6). The new format is
designed to pair with post-compact file/image restoration (separate work)
so the agent can resume long single-turn tasks without losing intent.
* refactor(core): align compaction trigger string with new 9-section prompt
The user-turn trigger injected after the system prompt still said
'generate the <state_snapshot>' from the old XML prompt era. Updated to
'produce the 9-section summary' to match Task 1's new prompt format.
Also tightens the prompt test to assert the specific user-message
verbatim mandate (not just the word 'verbatim' anywhere) so a future
regression that drops the mandate won't silently pass.
* feat(core): add postCompactAttachments module with file path extractor
extractRecentFilePaths walks history newest-first and returns the top N
unique file paths touched by read_file/write_file/edit/replace tool calls.
Pure function, no side effects, no state cache — readiness for the next
compaction-rewrite tasks.
* refactor(core): simplify extractRecentFilePaths internals
Three small cleanups from code review:
- Map<string, number> -> Set<string> (the index value was never read)
- Guard against maxFiles <= 0 explicitly (avoids returning 1 result
when caller passes 0 as a 'disable' sentinel)
- Document 'replace' as a legacy alias for 'edit' so a future cleanup
pass does not delete it as apparent dead code
Adds one test covering the maxFiles=0 path.
* feat(core): add image extractor with source-tool metadata
extractRecentImages walks history newest-first, collects up to N image
inlineData parts, and attributes each one to the model+functionCall that
preceded it (when one exists). Returns chronological order so callers
can render a meaningful 'last visual state ends here' strip.
* feat(core): add size-adaptive file reader for post-compact restore
readFileSizeAdaptive reads a file and returns one of: embed (full content
for files ≤ maxTokens × 4 chars), reference (path-only for large files),
missing (deleted since last touch), or binary (non-text content). The
embed/reference distinction mirrors claude-code's compact_file_reference
vs file attachment behavior, but without introducing new message types.
* refactor(core): harden readFileSizeAdaptive size accounting
Three corrections from code review:
- Import CHARS_PER_TOKEN from tokenEstimation.ts (canonical) instead of
redeclaring locally, preventing silent drift between modules.
- Compare decoded character length, not raw byte length, against the
cap. Otherwise a 10k-char Chinese file would be ~30k bytes and would
be mis-classified as 'reference' despite fitting the budget.
- Rename FileReadResult -> FileEmbedResult to avoid a name collision
with the unrelated FileReadResult interface in fileUtils.ts.
Adds a CJK-text test that catches the byte/char regression.
* feat(core): add file restoration block composer
buildFileRestorationBlocks reads each candidate file, classifies it as
embed/reference/missing/binary, and emits one consolidated reference
block (path-only list) plus one user message per embedded small file.
Total embed size is capped at POST_COMPACT_TOKEN_BUDGET; over-budget
files downgrade to reference.
* test(core): make budget test actually exercise the downgrade path
The previous version of this test wrote 3 files totalling 9k chars
against a 200k char budget. The assertions trivially passed regardless
of whether the budget check existed in the implementation.
The new version writes 11 files of 20k chars (each at the per-file cap)
so the budget is exhausted by the 10th and the 11th must downgrade
from embed to reference. Asserts both: file 11 appears in the reference
block, and file 11's content does NOT appear in any embed block.
* feat(core): add image restoration block composer
buildImageRestorationBlock emits a single user message whose first part
is a metadata header (turn index + source tool name + args per image),
followed by the inlineData parts themselves. Handles user-paste images
(no source tool) by labeling them as 'user-provided'.
* feat(core): add composePostCompactHistory orchestrator
Assembles the full post-compact history in order:
summary → model ack → file references → file embeds → image block.
Each section is built by the per-concern extractors and builders added
in previous tasks. This is the single integration point that
chatCompressionService.compress() will call once the wire-up task lands.
* feat(core)!: rewrite compress() to claude-code-style full-history model
Replaces the split-point + tail-preservation model with full-history
compression + composePostCompactHistory. The entire curated history is
sent to the summary side-query, and the post-compact history is
assembled by the new composer (summary + ack + file restores + image
restore).
BREAKING: the previously-exported findCompressSplitPoint,
splitPointRetainingTrailingPairs, COMPRESSION_PRESERVE_THRESHOLD, and
TOOL_ROUND_RETAIN_COUNT will be removed in the next commit. Tests that
exercise them remain failing temporarily.
* chore(core): remove obsolete split-point compression infrastructure
Deletes findCompressSplitPoint, splitPointRetainingTrailingPairs,
COMPRESSION_PRESERVE_THRESHOLD, MIN_COMPRESSION_FRACTION, and
TOOL_ROUND_RETAIN_COUNT, plus the tests that exercised them. The new
behavior is covered by composePostCompactHistory and its unit tests.
Also cleans up:
- Stale orphan-strip comment in compress() that described the deleted
manual-trigger orphan-funcCall handling.
- TEST_ONLY.COMPRESSION_PRESERVE_THRESHOLD hatch in client.ts.
- Docstring references in config.ts and compactionInputSlimming.ts.
* test(core): add single-turn computer-use compaction regression
Reproduces the scenario the rewrite targets: one user prompt kicks off
many screenshot tool calls. Asserts that (a) the user prompt is carried
into the summary verbatim and (b) the 3 most recent screenshots are
restored as an image block with source-tool metadata. This is the canary
test for the computer-use UX claim made in the design discussion.
* docs(core): remove stale "split point" references in tokenEstimation comments
Aligns the docstrings with the new compose-based compression flow. The
"split point" and "splitter" concepts no longer exist after the rewrite.
* fix(core): iterate parts reverse so parallel tool calls keep the last N
Real-session E2E surfaced a bug: a model that issues N parallel ReadFile
calls puts all N functionCall parts in ONE model+fc content. The
extractor's outer history walk is newest-first, but the inner parts
walk was forward — so for a 6-parallel batch hitting the cap of 5,
the FIRST 5 parts won and the actually-most-recent (last-listed) file
was dropped.
Fix: walk parts in reverse within each content. Applied symmetrically
to extractRecentImages (same shape, even rarer trigger).
Adds a regression test that hits a 6-parallel batch.
* fix(core): code-review fixes — fence escape, path sanitize, alias removal
- CommonMark-safe fence in file embed blocks. The old 3-backtick fence
closed prematurely when a file's content contained a triple-backtick
run (Markdown, CLAUDE.md, JSDoc with code examples) — leaking the
remainder as unfenced text. Now uses a fence one longer than the
longest backtick run in the content.
- Strip control characters (\r, \n, \t) from file paths before
rendering into attachment markdown. Paths come from model-controlled
history; a \n could inject markdown structure. The actual path stays
intact for tool calls — only the displayed string is sanitized.
- Remove the historyForCompression alias for curatedHistory in
compress(). The alias was added as a comment anchor during the
rewrite but didn't carry semantic information.
* refactor(core): rewrite compression prompt to <state_snapshot> XML with 9 claude-aligned sections
Replaces the 9-section numbered-text prompt with qwen-code's original
<state_snapshot> XML envelope, but with the 9 inner section tags
content-aligned to claude-code:
<primary_request_and_intent>
<key_technical_concepts>
<files_and_code_sections>
<errors_and_fixes>
<problem_solving>
<all_user_messages>
<pending_tasks>
<current_work>
<next_step>
Also:
- <scratchpad> -> <analysis>, stripped by postProcessSummary (saves
~600-800 tokens of CoT noise per compaction).
- "Resume directly..." trailer moved out of the prompt body and into
postProcessSummary (no longer re-generated by the model every
compaction; lives once in code with our own wording).
- Section 6 verbatim-policed mandate relaxed to "chronological, include
short messages like 'ok' / 'continue'" — matches claude-code intent
without forcing the model to literally copy long user messages.
E2E (qwen3.6-plus, 6 substantial .ts files + thorough analysis):
raw history 6508 -> summary 1513 (after strip ~947), 38% history
compression. Overall context 24642 -> 20647 reported (-16%), with
another ~664 tokens actually saved by the post-strip but not
reflected in the conservative token-math heuristic.
* docs(core): code-review polish on XML prompt rewrite
Four small follow-ups from review of 641a0eadd:
- prompts.ts: rewrite getCompressionPrompt's stale JSDoc — it still
described the deleted 9-section numbered-text format and the
verbatim mandate that was relaxed.
- chatCompressionService.ts: clarify the token-math comment so it's
obvious the ~1000 token deduction covers the full compression
system prompt + kick-off user turn (not any single instruction)
and that newTokenCount slightly over-counts because <analysis>
gets stripped by postProcessSummary downstream.
- postCompactAttachments.ts: add a NOTE comment on the <analysis>
strip regex covering its strict-tag-match assumption and
multi-block / non-greedy semantics.
- postCompactAttachments.test.ts: replace the four lazy
`await import('./postCompactAttachments.js')` calls inside the
postProcessSummary describe block with one top-level static import
— consistent with how every other describe in the file imports.
* docs(core): drop stale duplicate sentence left in token-math comment
* fix(core): address wenshao review on PR #4599 (correctness + security + ergonomics)
Seven follow-ups from wenshao's review of the compaction rewrite.
Critical:
- newTokenCount now includes restoration-block tokens via
estimateContentChars over extraHistory[2..]. Previously the formula
only counted side-query output, so up to 5 × 5K (files) + 3 × image
tokens were missing — letting the inflation guard miss and the
cheap-gate under-estimate the next prompt size (Finding 1).
- composePostCompactHistory now merges every file restoration block
and the image block into a single user Content following the model
ack. The previous output had consecutive user roles, which
geminiChat.test.ts:6289 enforces against and Gemini providers
reject with 400 "consecutive same-role content" (Finding 2).
- Preserve a trailing model+functionCall through compaction so a
pending functionResponse (sitting in sendMessageStream's
pendingUserMessage) has a matching call. Without this, hard-rescue
auto-compaction mid tool-use loop produces a user+functionResponse
with no preceding model+functionCall → API 400. This restores the
protection the split-point in-flight fallback used to provide.
When the funcCall lands without attachments it folds into the
ack's own model Content to avoid model→model adjacency (Finding 3).
- composePostCompactHistory now takes an optional workspaceRoot and
silently skips file paths that resolve outside it.
extractRecentFilePaths picks up paths from model functionCall args
regardless of whether the tool execution succeeded; without a
boundary check, an adversarial model that issued
read_file('/etc/passwd') — denied by the permission system —
would still have its path extracted and re-read into the next
prompt. compress() passes config.getTargetDir() as the boundary
(Finding 4).
Suggestions:
- composePostCompactHistory + buildFileRestorationBlocks +
readFileSizeAdaptive all take optional AbortSignal and short-
circuit / pass it to readFile's { signal } option. Cancelled
compactions stop on the next file read (Finding 5).
- postProcessSummary fallback no longer re-injects the raw
<analysis> block when the strip leaves nothing. The new
stripAnalysisBlock helper runs the closed-tag strip AND an
unclosed-tag strip (handles 'model ran out of output tokens
before closing'). If both leave nothing, postProcessSummary
emits '[Summary unavailable]' rather than leaking scratchpad
(Finding 6).
- firePostCompactEvent now receives stripAnalysisBlock(summary) so
hook consumers see the same text that lands in history. The
resume trailer stays out of the hook payload — that's wrapper
decoration for the next agent turn, not state for consumers
(Finding 8a).
Docs:
- Update the geminiChat.ts comment around `trigger: 'auto'` to
describe what the trigger actually does post-refactor (hook event
categorization) rather than the deleted manual-only orphan-strip
it used to guard against (Finding 8b).
Regression tests cover all six fixable code-path changes
(role alternation, trailing funcCall preservation, workspace
boundary, abort propagation, closed-tag fallback strip, unclosed-tag
fallback strip).
* fix(core): add getTargetDir to geminiChat auto-compression test mock
The R3.4 end-to-end auto-compression test drives the real
ChatCompressionService, which reads config.getTargetDir() for the
post-compact file-restoration workspace boundary. The geminiChat mock
config lacked getTargetDir, so the test threw "config.getTargetDir is
not a function" on CI. Add the mock to unblock the failing Test jobs.
* feat(core): configurable compaction retention + computer-use screenshot trigger
Add four env-overridable chatCompression settings (priority env >
settings > default):
- maxRecentFilesToRetain (QWEN_COMPACT_MAX_RECENT_FILES, default 5)
- maxRecentImagesToRetain (QWEN_COMPACT_MAX_RECENT_IMAGES, default 3)
- enableScreenshotTrigger (QWEN_COMPACT_SCREENSHOT_TRIGGER, default true)
- screenshotTriggerThreshold(QWEN_COMPACT_SCREENSHOT_THRESHOLD, default 50)
The screenshot trigger fires auto-compaction once tool-returned images
accumulate to the threshold even when token usage is below the auto tier,
so computer-use sessions don't drown the model in stale screenshots. It
counts only images nested in functionResponse.parts (tool results), not
user pastes, and runs only in the would-be-NOOP path when enabled.
Fix a latent bug surfaced while wiring the trigger: extractRecentImages
only inspected top-level inlineData parts, but convertToFunctionResponse
nests tool media under functionResponse.parts — so post-compact
restoration recovered ZERO tool screenshots in real sessions, while unit
tests stayed green against a fabricated top-level shape. It now walks both
shapes; the image counter and tests use the real nested shape.
Remove the now-defunct contextPercentageThreshold deprecation warning (the
field was already dropped from ChatCompressionSettings) and its tests, and
document the four new settings.
* test(core): assert screenshot trigger can't re-fire post-compaction; fix misleading docs
Code-review follow-up. The screenshot trigger counts only images nested in
functionResponse.parts. Compaction replaces those with the summary and
re-embeds survivors as TOP-LEVEL parts in the restoration block, which the
counter ignores — so the tool-image count always resets to ~0 and the
trigger cannot immediately re-fire, independent of maxRecentImages.
The resolveCompactionTuning JSDoc and the settings.md note previously warned
of a non-existent "maxRecentImages near threshold => compact every turn"
loop. Correct both, and add a regression test asserting
countToolResponseImages() is 0 on composePostCompactHistory output.
* fix(core): guard readFileSizeAdaptive against multi-GB reads; cover composer 4-entry branch
wenshao review round 2 on PR #4599.
- readFileSizeAdaptive now stats the file first and short-circuits to a
reference when its byte size exceeds maxChars*4 (the safe UTF-8 upper
bound — a file larger than that cannot fit within maxChars chars). This
stops a multi-GB file the agent previously touched from being slurped
into a Buffer and exhausting the heap mid-compaction, exactly when we're
trying to reduce memory. A large binary file now references rather than
reading to binary-detect.
- Add a test for composePostCompactHistory's 4-entry branch (attachments +
trailing model+functionCall) producing [user(summary), model(ack),
user(attachments), model(fc)]. This is the common mid-tool-loop
compaction case; a model->model adjacency here is a provider 400. Prior
tests only covered the 2-entry fold (no attachments) and 3-entry (no
trailing fc) shapes.
* fix(core): resolve symlinks in workspace boundary; guard compose against throws
wenshao review round 3 on PR #4599 (two Criticals).
- isInsideWorkspace now resolves symlinks via realpathSync (safeRealpath,
with a lexical fallback for non-existent paths). A symlink living inside
the workspace but pointing outside (e.g. workspace/.env -> ~/.ssh/id_rsa)
previously passed the lexical boundary check and had its target read and
embedded into the post-compact history sent to the provider. Added a
RED-verified security regression test (secret embedded under the old
lexical check; rejected under realpath).
- Wrap composePostCompactHistory in try/catch inside compress(). The
summary side-query has already succeeded at that point, so a
restoration-assembly throw (disk I/O / malformed history) previously
escaped to sendMessageStream, crashing the active turn AND bypassing the
COMPRESSION_FAILED breaker. It now degrades to summary + ack.
* fix(core): close 4 compaction Criticals from review round 4
wenshao review round 4 on PR #4599.
- isSummaryEmpty now checks the STRIPPED summary: a response that is only an
<analysis> block (no <state_snapshot>) strips to empty, so it takes the
COMPRESSION_FAILED_EMPTY_SUMMARY path instead of "succeeding" with
`[Summary unavailable]` as the agent's only context (silent amnesia).
- Manual /compress strips a trailing ORPHANED model+functionCall before
composing — it has no pending functionResponse, so preserving it would
emit model[fc] then the next user text turn -> API 400. Auto-compaction
still keeps it (the pending response pairs with it).
- The restoration-failure catch fallback now folds a trailing
model+functionCall into the ack turn, so a pending functionResponse
(auto mid-tool-loop) keeps its matching call even on the degraded path.
- extractRecentFilePaths skips file paths whose tool call FAILED (an error
functionResponse), so a denied read_file is never re-read off disk during
compaction — closing a permission-bypass side channel.
RED-verified regression tests for the empty-summary, orphan-strip, and
permission-bypass fixes. Corrected the postProcessSummary comment.
* test(core): cover composePostCompactHistory catch-fallback; document fold text drop
wenshao review round 5 on PR #4599.
- Regression test for the restoration-failure catch fallback: mock
composePostCompactHistory to reject and assert compaction still returns
COMPRESSED (no escape to sendMessageStream / breaker bypass) with the
trailing functionCall folded into the ack and the trailing text dropped.
- Document that the fold branch intentionally keeps only functionCall parts
(the trailing turn's text is already captured in the summary); the
asymmetry with the with-attachments branch is deliberate.
* feat(computer-use): add tool name constants
* feat(computer-use): hardcode upstream tool schemas
* feat(computer-use): add enableComputerUse setting (default true)
* chore(vscode-ide-companion): sync settings schema for computerUse
* feat(computer-use): MCP stdio client for upstream binary
* feat(computer-use): ComputerUseTool wrapper + bootstrap stub
* feat(computer-use): register 9 deferred tools when enabled
* feat(computer-use): persist install approval state under ~/.qwen
* feat(computer-use): detect upstream permission errors
* feat(computer-use): bootstrap state machine (install + permissions)
* feat(computer-use): wire install approval to qwen-code confirm UX
* chore(computer-use): script to sync schemas from upstream
* fix(computer-use): consolidate package spec, surface download progress, correct version comment
* docs(computer-use): implementation plan
* fix(computer-use): forward image content parts to the model
* fix(computer-use): coerce string numbers to integers + clarify required fields
* fix(computer-use): detect missing Screen Recording + re-spawn doctor across permission transitions
* fix(computer-use): auto-reconnect on transport-closed errors
* fix(computer-use): sync schemas with upstream canonical contract
Regenerated schemas.ts from upstream open-computer-use@latest via
scripts/sync-computer-use-schemas.ts. Key contract fixes:
- element_index: type integer → string (upstream reads via optionalString)
- x/y/from_x/from_y/to_x/to_y: type integer → number (upstream uses optionalDouble)
- scroll: adds required direction enum + requires element_index (not pages)
- click: adds optional mouse_button string enum (left/right/middle)
- Descriptions updated to upstream verbatim text (no "REQUIRED:" prefix)
* fix(computer-use): bidirectional type coercion for string element_index
Rename coerceNumericStrings → coerceTypes and add Direction 2:
when schema declares type: "string" and model sends a number,
stringify it (e.g. element_index: 2 → "2"). This fixes the upstream
runtime error where optionalString returns nil for numeric element_index.
Direction 1 (string → number for integer/number fields) is preserved
unchanged for x/y coordinate fields.
Update tests: element_index coercion tests now reflect string schema
type; add new "coerces integer element_index to string" test cases.
* feat(prompts): strengthen deferred-tools guidance to prevent param guessing
* fix(computer-use): clearer wording for permission-transition onboarding message
* fix(computer-use): only probe permissions on fresh client start, not every tool call
* docs(computer-use): correct comment about permission-revocation recovery behavior
* fix(computer-use): pin upstream version exactly to prevent schema drift
* fix(computer-use): use pinned package spec in client singleton to prevent schema drift
* fix(computer-use): decouple install gate from per-action permission grant
* fix(computer-use): route registration through PermissionManager-aware registerLazy
* fix(computer-use): probe via upstream doctor instead of get_app_state on Finder
The previous probe called get_app_state on Finder, which has the side
effect of activating the target app via upstream's unhide / open -b /
AXRaise logic. Result: Finder popped to the foreground once per fresh
session even when the user's task had nothing to do with it.
The doctor CLI reads TCC + runtime preflight and prints a summary to
stdout, exiting silently when permissions are granted. When any
permission is missing, doctor launches the onboarding window via
LaunchServices (which dedups so repeated invocations focus the
existing window). We parse the stdout summary and rely on doctor's
own window-launching for the UX trigger — no separate spawnDoctor
call needed.
Side effect for steady-state sessions (permissions already granted):
ZERO Finder activation. The probe spawns npx -y doctor once per fresh
client start (~200-500ms), and that's it.
Also bumped pollIntervalMs default from 2s to 5s to amortize the
npx-spawn overhead during the rare permission-grant flow.
* fix(cli): prevent file paths from being treated as slash commands (#1804)
When users input file paths starting with '/' (e.g. '/api/apiFunction/...',
'/Users/name/path'), they were incorrectly parsed as slash commands, resulting
in "Unknown command" errors. The input was discarded instead of being sent to
the model for processing.
Root cause: isSlashCommand() only checked for a '/' prefix without validating
whether the first token actually looks like a command name. Any '/' prefix
triggered the slash command flow, and when no matching command was found, the
error was shown with no fallback.
Fix: Add looksLikeCommandName() that validates command names contain only
[a-zA-Z0-9:_-]. Both isSlashCommand() and handleSlashCommand() now check the
first token — if it contains path separators, dots, or non-ASCII characters,
the input falls through to normal model processing instead of the command
dispatcher.
Closes#1804
* fix(cli): allow dots in command names and fix prettier formatting
Address review feedback:
- Allow '.' in looksLikeCommandName() regex to support extension-qualified
commands like gcp.deploy (CommandService renames conflicts as ext.cmd)
- Add regression tests for dot-named commands in both commandUtils and
slashCommandProcessor
- Fix prettier formatting in slashCommandProcessor test file
* fix(cli): handle slash command review edge cases
* docs(cli): align slash command validation comment
* fix(cli): preserve slash prompt ordering
* fix(cli): reject shell-metacharacter slash tokens
* test(cli): align slash command action mocks
* fix(cli): track model-sent user turns
* fix(cli): narrow slash path handling scope
* fix(cli): split slash routing follow-up
* fix(cli): tighten slash routing follow-up scope
* fix(cli): address slash routing review gaps
* fix(cli): keep slash history follow-up focused
* fix(cli): align resume history item typing
* fix(cli): address slash history review suggestions
* test(cli): harden slash command history item ids
* chore(cli): use HistoryItemWithoutId in useEditorSettings.test
* refactor(cli): keep setSessionName optional in useSlashCommandProcessor
main currently exposes setSessionName as an optional trailing parameter.
The earlier addition of updateItem pushed it before updateItem and
forced every caller — including AppContainer and all tests — to pass an
explicit undefined. Reorder so updateItem stays required and
setSessionName remains optional, preserving the prior ergonomic.
* test(cli): fix slash command processor hook args
* fix(cli): harden slash command history metadata
* docs(design): add RT optimization design doc
Two-round review trail documenting the analysis path: original D1-D4
proposal, code-level verification in §6 that recanted the cost estimates,
and §7 ROI reordering after DashScope ephemeral cache implementation was
confirmed already in place — which collapsed D2's net benefit and led to
deferring D2 and D4 as won't-fix.
The doc is preserved as the canonical record of why the obvious-looking
directions (fast-model routing, prevalidate scheduling) turn out to be
dead ends, so future work doesn't relitigate the same conclusions.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(design): add reduce-rounds-via-skill-design with spec-first gating
Companion design to rt-optimization-design.md. The core argument:
the real lever for reducing agent loop rounds is at the skill/tool
design layer, not the agent framework. Round 2 in §1.2's baseline
exists because Round 1's skill didn't return a complete answer —
fixing that per-skill collapses 3 rounds into 2, an angle the
original framework-centric proposal completely missed.
Layout:
- §0 acceptance spec is the front-loaded gate: engineering specs
lock at P-1, statistical thresholds lock at P1.5 (after baseline),
per-skill specs are data-driven and live in PR descriptions
- §3-§4 three-layer plan: telemetry → per-skill rewrites → prompt
guidance for concurrent tool calls; each layer is independently
measurable and reversible
- §5.3 stop-loss lines split into result + process metrics to catch
the "looks like progress, no actual ROI" failure mode early
The doc was reviewed by codex twice — once on initial draft (caught
qwen-logger dead-code path, batch_size state-passing cost, prompts.ts
line drift) and once after §0 was added (caught spec rigidity, missing
per-skill template, framework boundary case). Both rounds' findings
were either applied or explicitly recorded as not-adopted with reasons
inline.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(telemetry): connect logSkillLaunch to QwenLogger
logSkillLaunch in loggers.ts went only through the OTLP path, while
QwenLogger.logSkillLaunchEvent in qwen-logger.ts had no callers anywhere
in the repo — leaving the skill_launch event invisible to any backend
that consumes from the qwen-logger pipeline rather than OTLP.
Mirror the logToolCall pattern at loggers.ts:230: forward the event to
QwenLogger before the OTLP path so the call still reaches QwenLogger when
the OTEL SDK is not initialized.
This is P0 of docs/design/rt-optimization/reduce-rounds-via-skill-design.md
§4.1.1b — a prerequisite for the prompt_id propagation in P1 so the
SkillLaunchEvent / ToolCallEvent join in §4.1.2 has data to query against.
Tests: 2 new cases under describe('logSkillLaunch') covering forwarding
to QwenLogger plus the OTLP-uninitialized branch; loggers.test.ts now
47/47 pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(telemetry): thread prompt_id through SkillLaunchEvent
To join skill_launch events with the subsequent tool_call events they
trigger, SkillLaunchEvent now carries the prompt_id of the user turn
that fired the skill. The scheduler already holds the request and its
prompt_id; the missing piece was getting that id into the invocation
that does the actual logSkillLaunch call.
Wiring:
- SkillLaunchEvent constructor adds a required prompt_id parameter so
the field can never be silently undefined in a backend join.
- SkillToolInvocation exposes setPromptId(id) and stores the value;
the four logSkillLaunch sites in execute() pass this.promptId through.
- CoreToolScheduler.buildInvocation grew an optional fourth promptId
argument and duck-types setPromptId on the freshly-built invocation,
mirroring the existing setCallId hook. The two callers (setArgs path
at L1036 and the main schedule path at L1497) pass
request.prompt_id / reqInfo.prompt_id.
- qwen-logger.logSkillLaunchEvent forwards prompt_id in the RUM event
properties so the join works on the qwen-logger pipeline too.
The empty-string default on SkillToolInvocation.promptId is deliberate:
direct invocations (e.g. buildAndExecute in tests) that skip the
scheduler still log a valid event, and downstream queries can filter
prompt_id != '' to exclude non-scheduled launches from joins.
Implements P1 of docs/design/rt-optimization/reduce-rounds-via-skill-design.md
§4.1.1 — required prerequisite for the SkillFollowupRecord SQL in §4.1.2.
Tests: 2 new cases in skill.test.ts cover the setPromptId path and the
empty-default path; loggers.test.ts updated for the new 3-arg signature.
256 tests pass across loggers / skill / coreToolScheduler suites.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(scheduler): cover prompt_id propagation through buildInvocation
The duck-typed setPromptId hook added in the previous commit went
through unit tests on each side independently — SkillToolInvocation
tests verified that setting the field changes the logged event, and
the loggers tests verified the SkillLaunchEvent shape — but the
integration point in CoreToolScheduler.buildInvocation that wires the
two together was only exercised indirectly. Same is true of the older
setCallId hook it mirrors, which had no test at all.
Two cases here close that gap on the scheduler side:
- A purpose-built PromptIdAwareTool whose invocation records every
setPromptId call; the test schedules a request with a known
prompt_id and asserts the invocation captured it. This is the
positive contract.
- The existing TestApprovalTool (no setPromptId) scheduled through
the same path to confirm the duck-type guard does not throw when
the method is absent. This is the backward-compatibility contract
that lets every existing tool keep working unchanged.
The two cases together pin both branches of the typeof check in
buildInvocation, so future refactors of that hook cannot regress
silently. 165 tests in the suite still pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(telemetry,scheduler,skill): close P0/P1 coverage gaps
Three blind spots remained after the initial P0+P1 work — each one
was a path that the production code change had already touched
mechanically but no test was pinning it against future regressions.
qwen-logger.ts logSkillLaunchEvent now has two cases asserting that
prompt_id reaches the RUM event properties, on both the success and
failure branch. Previously the loggers.test.ts spy stopped at "method
was called" and never inspected the payload qwen-logger built.
skill.ts had four logSkillLaunch sites, but only the happy path and
the empty-default path were tested. The commandExecutor-success
branch (L386), not-found branch (L399), and thrown-exception branch
(L482) now each have a test that sets promptId, drives execute()
through that specific path, and asserts the emitted event carries
both the right success flag and the right prompt_id. This catches
the failure mode where someone later edits one of those branches
and forgets the promptId argument — replace_all guaranteed today's
correctness but no test would catch a regression tomorrow.
CoreToolScheduler.buildInvocation now has two direct unit tests
that exercise the method through a type-assertion cast. Reaching
the L1036 setArgs path through the public API would require mocking
modifyWithEditor + the filesystem + an editor type, which would
dwarf the change under test. The direct call covers both L1036 and
L1497 simultaneously: when promptId is supplied the duck-typed
setPromptId is invoked; when it is omitted, the captured field
stays undefined and no throw happens.
298 tests pass across loggers / qwen-logger / skill / scheduler suites.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* review(PR #4565): address Copilot + github-actions feedback
Five spots flagged by the automated review on #4565. Three were real
and worth fixing; two were comment-quality touch-ups that traveled
along with the same patch.
- SkillLaunchEvent.prompt_id is now optional with a default of '',
removing the breaking-change footprint on the exported telemetry API.
All current internal callers still pass the value explicitly through
the SkillToolInvocation.promptId field, so the §0.1 spec ("prompt_id
串联") is still enforced in production paths — type-level enforcement
just steps aside in favor of API stability, with §0.5 治理 covering
the discipline at the process layer.
- The skill-design doc §4.1.1 used to claim "BaseToolInvocation 已有
request.prompt_id" which is wrong: BaseToolInvocation only holds
params, and the prompt_id flows through CoreToolScheduler's duck-typed
setPromptId hook (mirroring setCallId). The doc now reflects the
actual implementation and notes that the earlier text was the bug.
- CoreToolScheduler.buildInvocation gained a short JSDoc explaining
why the two extra args (callId, promptId) are optional — they
match the existing duck-type pattern that lets older tools and
non-scheduler call sites work without implementing the setters.
- skill.test.ts adds a one-comment note next to the first setPromptId
cast explaining that setPromptId is a scheduler-only hook, not part
of the public ToolInvocation interface.
- SkillToolInvocation.promptId field comment shrank from 8 lines to 2
with a pointer to the design doc so the inline noise drops without
losing the empty-string semantics.
Pre-existing scope-creep findings (Chinese-only doc, mock-config
duplication in scheduler tests, redundant optional-chain comment,
prompt_id sanitization for an internally-generated UUID) are
deliberately not addressed here — see the reply on PR #4565 for
disposition per item.
298 tests still pass across loggers / qwen-logger / skill / scheduler.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(channels): add Feishu (Lark) channel adapter
* fix(channels/feishu): fix webhook stop button, memory leak, spin-wait timeout, and reaction cleanup
* fix(channels/feishu): fix security, stability and build issues from PR review
* fix(channels/feishu): fix card lifecycle, streaming limits, and download safety from CR round 2
* fix(channels/feishu): harden webhook, card lifecycle, and disconnect cleanup from CR round 3
* fix(feishu): clarify stoppedMessages JSDoc to match actual cleanup behavior
* fix(channels/feishu): handle post messages without language key wrapper in quote context
* fix(channels/feishu): fix webhook signature bypass, stop-button double-send, and blockStreaming duplicates from CR round 4
* fix(channels/feishu): harden card lifecycle, markdown splitting, and defensive guards from CR round 5
* fix(channels/feishu): harden card lifecycle, markdown splitting, and defensive guards from CR round 5
- Set cardCreationFailed on onPromptStart failure to prevent retry spiral
- Skip throttle updates when card creation permanently failed
- Handle code fences in hard-split and table-stripping fallbacks
- Use parity-based fence detection in splitByTables (align with splitChunks)
- Add cs.stopped and else branch in onPromptEnd to prevent timer race and state leak
- Mark cardState.stopped after busy-wait timeout to abandon orphaned in-flight creation
- Apply MAX_CARD_CHARS truncation with fence parity in onResponseComplete
- Sanitize senderId before <at> tag interpolation
- Use replaceAll + callback form for mention replacement
- Floor token expiry to prevent thundering herd on expire:0
- Add log for stop-button auth rejection
- Fix stoppedMessages JSDoc to match actual cleanup lifecycle
- Fix test fixture to match "still creating" scenario
- Fix typecheck errors in test file (TS2571, TS4111)
- Add stop-button auth negative path tests (operator mismatch, missing operator, missing sender)
- Replace spanning regex in table-stripping with line-by-line stripTables() to resolve CodeQL ReDoS warning
* fix(channels/feishu): fix HMAC bypass, prompt injection, SSRF, and card lifecycle from CR round 5-6
Security:
- Fix webhook HMAC bypass: use defineProperty(non-enumerable) for headers instead of prototype shadowing
- Fix cross-user prompt injection: mark quoted content as untrusted with explicit marker
- Fix SSRF: validate all Feishu IDs with FEISHU_ID_RE before URL interpolation in 6 endpoints
- Fix safeSenderId regex: add hyphen to character class so ou_abc-def-123 is not rejected
Card lifecycle:
- Set cardCreationFailed on onPromptStart failure to prevent retry spiral
- Skip throttle updates when card creation permanently failed
- Fallback to plain message delivery when cardCreationFailed with accumulated text
- Track creationTimer in CardSessionState so cleanupCard/disconnect can cancel orphaned card creation
- Add cs.stopped and else branch in onPromptEnd to prevent timer race and state leak
- Mark cardState.stopped after busy-wait timeout to abandon orphaned in-flight creation
- Apply MAX_CARD_CHARS truncation with fence parity in onResponseComplete
- Preserve atPrefix in streaming truncation to prevent @mention visual snap
- Account for suffix and fence reserve in truncation maxBody calculation
- Clean up auxiliary maps after handleInbound when gate rejects the message
- Clean up blockStreaming mode Map entries in onPromptEnd
- Skip bare @mention without question text
Markdown:
- Handle code fences in hard-split and table-stripping fallbacks
- Use parity-based fence detection in splitByTables (align with splitChunks)
- Replace spanning regex in table-stripping with line-by-line stripTables() to resolve CodeQL ReDoS warning
Defensive guards:
- Sanitize senderId before <at> tag interpolation
- Use replaceAll + callback form for mention replacement
- Floor token expiry to prevent thundering herd on expire:0
- Add log for stop-button auth rejection
Tests:
- Fix stoppedMessages JSDoc to match actual cleanup lifecycle
- Fix test fixture to match "still creating" scenario
- Fix typecheck errors in test file (TS2571, TS4111)
- Add stop-button auth negative path tests (operator mismatch, missing operator, missing sender)
- Assert cancelSession called in stop-button happy-path test
* fix(channels/feishu): add request timeouts, token dedup, and harden file/quote sanitization
* fix(channels/feishu): harden card lifecycle, webhook auth, and resource cleanup from CR round 7
* fix(channels/feishu): harden card lifecycle, mention handling, and error recovery
* fix(telemetry): improve LogToSpan bridge error info and TUI handling
The OTel `LogToSpanProcessor` bridge (used when traces+metrics are over
OTLP but logs aren't, e.g. Alibaba Cloud ARMS) had two diagnostic issues:
1. Empty error messages. When the OTLP HTTP exporter callback returned
`{ code: FAILED, error }`, `error.message` is the HTTP reason-phrase —
always empty on HTTP/2. The bridge printed literally
`[LogToSpan] export failed: code=1 error=` with zero actionable info.
Now we surface `name`, `httpCode` (only when numeric), and a 200-byte
`data` snippet from the underlying OTLPExporterError, with JSON-escape
on user content so embedded newlines can't tear the log line.
2. TUI pollution. The processor wrote diagnostics to `process.stderr`
directly. Ink only manages stdout, so those writes punched through
into the rendered terminal area. The processor now accepts an
injectable `diagnosticsSink`; in interactive mode `sdk.ts` injects a
sink that routes through `debugLogger.warn` (file-backed). Non-
interactive runs (CI/scripts) keep the default stderr sink so export
failures remain visible on the canonical batch-diagnostic channel.
Backward compatibility is preserved: the legacy numeric-arg constructor
keeps stderr behavior; the options-object overload gains the new field.
Other raw `process.stderr.write` sites in the CLI (errors.ts,
startupProfiler.ts, useGeminiStream.ts, etc.) have the same TUI-leak
pattern but are intentionally left out of this PR.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): address PR #4482 review comments
- Fix TS2353 compile error in keeps-processing-after-sink-throw test:
the mock callback type was narrowed to `{ code: number }` and rejected
the `error?: Error` field that `ExportResult` actually carries. Widen
the type. (wenshao Critical — this was the root cause of CI lint/test
failures across all 3 OS.)
- JSON.stringify the payload of the `export threw` diagnostic so a
synchronously-thrown error with embedded newlines stays on one line,
same single-line invariant enforced by `formatExportError`. Add
coverage for both the newline case and the non-Error throw branch.
(wenshao Suggestion)
- Remove the dead `makeFailingProcessor(err)` call in the JSON-escape
test that was immediately overwritten — the orphaned processor
retained a live `setInterval` timer with no cleanup. (wenshao
Suggestion)
- Rename the "200 bytes" test name and comment to "200 characters" to
match the actual `string.slice(0, 200)` (UTF-16 code units) behavior;
add a note on the cap being a leak/noise budget, not a hard byte
limit. (Copilot 2x)
- Strengthen the non-interactive test to actually trigger a failed
export against the real `LogToSpanProcessor` and assert the default
sink writes to stderr, not just that `diagnosticsSink === undefined`.
(github-actions High #2)
- Reword the "shell-active bytes" comment to "characters that would
break log parsing" — the actual concern is log-line tearing, not
shell semantics. (github-actions Medium)
- Update class JSDoc to mention the diagnostics-sink responsibility
alongside the bridge purpose. (github-actions Low)
- Minor JSDoc wording fix on `LogToSpanDiagnosticsSink` type for
clarity around the no-trailing-newline contract. (github-actions Low)
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(telemetry): cover two unreachable formatExportError branches
Add coverage for two paths flagged by the DEEP-tier review on #4482:
- `err.message || err.name || 'unknown'` chain: the third branch (both
message and name empty) was never exercised. Scenario: minified
environments that strip `Error.name`. Test constructs
`Object.assign(new Error(''), { name: '' })` and asserts the output
contains `error="unknown"`.
- `typeof extra.data === 'string' && extra.data.length > 0` guard: the
empty-string case (HTTP response with empty body) was never tested,
so a future loosening to `!== undefined` would silently start
emitting `data=""`. Test asserts `data=` is absent.
Both branches are real and reachable in production failure modes; the
tests are guards for the documented intent.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): tighten LogToSpan diagnostics per wenshao review
- Quote `error="unknown"` in the err-missing early return so it matches
the JSON.stringify output produced when message+name fall back to
'unknown'. Two paths now emit identical greppable output for
semantically identical "unknown error" states.
- Widen the duck-typed cast to `code?: number | string` and add a
load-bearing comment on the `typeof === 'number'` guard. The type now
matches reality (Node networking errors surface string codes like
ECONNREFUSED), preventing a future simplification to `if (extra.code)`
that would mislabel networking errors as HTTP statuses.
- Reuse `formatExportError` in the sync-throw path so a synchronously-
thrown OTLPExporterError surfaces its httpCode and data, matching the
callback-failure path. Non-Error throws still fall back to
JSON.stringify on String(err) to preserve the single-line invariant.
- Include batch span count in the timeout diagnostic
("(N span(s))") — lets an operator distinguish slow network from
oversized batch when troubleshooting timeouts.
- Add a test for non-string truthy err.data (Buffer) — the `typeof ===
'string'` guard's false branch was only covered for undefined and
empty string, so a future refactor relaxing the guard would silently
start emitting binary garbage with no test to catch it.
- Document the QWEN_DEBUG_LOG_FILE=0 trade-off at the sink wiring site:
interactive mode plus disabled debug log = full diagnostic silence.
This is an accepted user opt-in trade-off; falling back to stderr
would re-introduce the TUI pollution this injection prevents.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(cli): surface startup warnings on stderr before TUI render (#4448)
When settings.json has invalid JSON, the file is renamed to
.corrupted.<timestamp> and a warning is added to startupWarnings.
Previously these warnings were only rendered inside the TUI's
Notifications component, which can be obscured by the onboarding
flow ('Connect a provider') — leaving users unaware their settings
were silently reset.
Now all startup warnings are written to stderr before the TUI takes
over. This ensures the message appears in the terminal scrollback
regardless of what the TUI shows. In non-interactive mode (--prompt,
piped stdin) this is the *only* output channel for these warnings,
closing a gap where they were collected but never emitted.
* fix(cli): emit settings warnings before relaunch to ensure parent surfaces them
Move getSettingsWarnings() stderr emission to right after loadSettings(),
before the sandbox/relaunch block. This ensures the parent process prints
corruption warnings before relaunchAppInChildProcess() spawns the child
and exits.
Add regression test verifying getSettingsWarnings returns non-empty,
human-readable warnings containing 'invalid JSON' when settings.json
has broken content.
Addresses review feedback from @wenshao on #4461.
Fixes#4448
Signed-off-by: kagura-agent <kagura@openclaw.dev>
---------
Signed-off-by: kagura-agent <kagura@openclaw.dev>
* feat(cli): default auto-dream/auto-skill to on and add /memory toggle
Bring the managed memory pipeline closer to its intended out-of-the-box
experience: auto-dream and auto-skill now default to enabled (matching
the existing auto-memory default), so users get summarized memories and
reusable project skills without having to opt in.
The /memory dialog previously only exposed Auto-memory and Auto-dream
toggles. With auto-skill now on by default, users need an equally
discoverable way to opt out, so this adds an Auto-skill row alongside
the existing two with the same focus/Enter toggle semantics and
workspace-scoped persistence (memory.enableAutoSkill).
Default-value updates are kept consistent across all three sources of
truth (settings schema, CLI loader, core Config), and the generated
vscode settings.schema.json is regenerated to match.
* test(cli): add getAutoSkillEnabled to MemoryDialog test mock
The new Auto-skill toggle row reads config.getAutoSkillEnabled() at
render time; without it on the mocked config the component throws and
the existing list-navigation tests assert against an empty frame.
* fix(cli): guard managed auto-dream in bare mode, sync tests and docs
- enableManagedAutoDream in loadCliConfig was missing the bareMode guard
that its two siblings already had; once the default flipped to true,
this caused a raw-field inconsistency in bare-mode sessions (the
getter still returned false via its own !getBareMode() guard, but the
Config.enableManagedAutoDream field itself was now true).
- docs/users/configuration/settings.md still listed
enableManagedAutoDream's default as false, and was missing the new
enableAutoSkill row entirely. Both fixed.
- MemoryDialog.test.tsx now covers the autoSkill row render, the new
focus chain (list ↑ autoSkill ↑ autoDream and back down), and the
Enter-toggle path that writes memory.enableAutoSkill to workspace
settings.
- config.test.ts gains a non-bare default test asserting all three
getManaged*Enabled() / getAutoSkillEnabled() return true, and the
bare-mode test now asserts auto-dream/auto-skill also resolve to
false in bare mode.
* fix(permissions): make command substitution ask, not deny (#4093)
`resolveDefaultPermission` hard-denied any shell command containing
$(), backticks, <(), or >(). Two problems:
1. The deny couldn't be overridden by YOLO mode — YOLO sees the
result only as `'ask'` or `'default'`, never `'deny'`.
2. It fired inconsistently: only when `hasRelevantRules()` happened
to be true. A compound command like
`echo hello && python3 -c "print($(echo hello))"` was hard-denied
because `echo hello` matched an unrelated allow rule and made
`hasRelevantRules()` true, while the same `python3` sub-command
in isolation kept its L3 `'ask'` (PM skipped) and was approvable.
Same substitution, opposite verdict — purely a function of which
unrelated rules were loaded.
This is the surviving half of a two-step migration. `fb7e30ad3
"fix(shell): remove command substitution deny check from
getDefaultPermission"` removed the equivalent L3 deny but missed
the L4 mirror — this commit completes that cleanup.
What changes:
- `resolveDefaultPermission` no longer special-cases substitution; the
AST read-only check already marks substitution-bearing commands as
non-read-only, so they fall through to `'ask'` with everything else.
- Return type narrowed from `'allow' | 'ask' | 'deny'` to `'allow' | 'ask'`.
- `ToolExecuteConfirmationDetails` gains an optional `warnings?: string[]`
field. `ShellToolInvocation.getConfirmationDetails` populates it with a
"Contains command substitution …" line when substitution is detected
on either the original or stripped command. The CLI confirmation
dialog renders these as ⚠-prefixed lines in the warning color,
mirroring Claude Code's UX (see issue thread for reference).
Out of scope: `checkCommandPermissions` in shell-utils.ts still hard-
denies substitution. That path is exercised by user-authored `!{...}`
shell injections in slash commands (shellProcessor.ts) and is a
prompt-injection defense, not the agent-tool path #4093 describes.
Regression coverage:
- permission-manager.test.ts: new `command substitution (issue #4093)`
describe with 5 cases — standalone $(), the exact compound from the
issue, backticks, <(), and deny-rule precedence.
- shell.test.ts: new `command substitution warning (issue #4093)`
describe with 4 cases — $()/backticks/<() each surface a warning,
plain commands do not.
- ToolConfirmationMessage.test.tsx: 2 new render tests.
Fixes#4093
* fix(cli): reserve warnings height in exec confirmation layout (#4386 review)
Addresses two round-1 findings from Copilot on PR #4386:
1. ToolConfirmationMessage: the warnings block was rendered as a sibling
*below* the MaxSizedBox-capped command body (with marginTop=1), but
the height budget computed by availableBodyContentHeight() — and the
compactMode cap of COMPACT_BODY_MAX_LINES — didn't account for the
extra lines. On small terminals + compactMode this could push the
options list off-screen. Reserve the warnings footprint
(`warningsCount + 1` for marginTop) up-front so the overall exec
block respects availableTerminalHeight / COMPACT_BODY_MAX_LINES.
Added a regression test (`keeps options visible alongside the
warning on a tight compactMode layout`) that renders a substitution
command with `availableTerminalHeight=10` + `compactMode=true` and
asserts both the warning text and all three compactMode option
labels remain on-screen.
2. permission-manager.test.ts: the new `command substitution (issue
#4093)` describe had a misleading inline comment that conflated the
issue's original scenario (`echo hello && python3 ...` + `Bash(echo *)`)
with the test fixture (`git status && python3 ...` + `Bash(git *)`).
Rewrote it to describe what the test actually does (`git status`
matches `Bash(git *)`, making hasRelevantRules() true; the python3
sub-command then resolves via resolveDefaultPermission).
* fix(permissions): align monitor + propagate warnings to ACP/non-interactive (#4386 review)
Addresses round-2 review findings from wenshao on PR #4386. Four
related findings, all about sibling drift from the original #4093 fix:
either the same hard-deny-on-substitution pattern in a sibling tool, or
downstream consumers that don't propagate the new warnings field.
1. monitor.ts: `MonitorToolInvocation.getDefaultPermission()` had the
identical `detectCommandSubstitution → 'deny'` pattern that the
original PR removed from `PermissionManager.resolveDefaultPermission`
— sibling drift the original audit missed. Same UX problems apply
(YOLO unbypassable, opaque deny). Removed the deny branch, added
the substitution warning in `getConfirmationDetails` (mirroring
ShellToolInvocation), updated the 5 existing tests that asserted
the old 'deny' to assert 'ask', and added a confirmation-warning
test for the issue #4093 mirror case. Monitor still maintains its
separate permission boundary (Monitor(...) rules don't share with
Bash(...) — documented in the unchanged comment at the top of
getConfirmationDetails); only the substitution-deny half is removed.
2. ACP `buildPermissionRequestContent` (permissionUtils.ts): had no
`exec` branch, so the new `warnings` field never reached ACP
clients (IDE integrations etc.). Added an `exec` branch that emits
one `⚠ <warning>` text content per warning, alongside the existing
`edit` (diff) and `plan` (text) branches. Two regression tests
added: warning present → ⚠ content entry; no warnings → empty.
3. Non-interactive `permissionController.buildPermissionSuggestions`:
the `case 'exec'` description string didn't read `warnings`, so
daemon/API consumers that delegate the approval decision back to
a user lost the substitution context. Appended warnings as a
parenthesized `⚠ ...` suffix to the description string. (No test
file exists for this controller — change is small and verifiable
by inspection; adding test scaffolding is out of scope for this
round.)
4. Test coverage: the `command substitution (issue #4093)` describe
blocks in `shell.test.ts` and `permission-manager.test.ts` covered
`$()`, backticks, and `<()` but not `>()` — even though
`detectCommandSubstitution` and the warning text both list it.
Added a `>()` case to each block to close the regression gap.
* fix(cli): wrap-aware warnings reservation + load-bearing regression test (#4386 self-review)
Two related self-review findings from my pre-push review on PR #4386:
1. SR-1: the round-1 layout regression test
(`keeps options visible alongside the warning on a tight compactMode
layout`) used a single-line command at `contentWidth=80`. `MaxSizedBox`
clamps to `min(content_lines, maxHeight)`, so a 1-line command
renders as 1 line regardless of whether `bodyContentHeight -=
warningsHeight` is applied — the test would still pass if that line
were silently removed. Replaced with a 4-line command and an
assertion on the `... N lines hidden ...` truncation footer that
MaxSizedBox emits *only* when its cap is actually active. Confirmed
RED → fix → GREEN: the new test fails when the warnings
subtraction is removed and passes when restored.
2. SR-2: the warnings-height reservation reserved `warningsCount + 1`
lines (one per warning + one marginTop separator). On narrow
terminals the warning text wraps across multiple visual rows, so
the reservation under-counts. Replace the per-warning `+1` with
`ceil((warning.length + 2) / max(contentWidth, 1))` to account for
each warning's actual rendered row count. The `+ 2` accounts for
the `⚠ ` prefix; the `max(...,1)` keeps the math defined for
pathological inputs. Independently flagged by Codex during
self-review as `[P3] Account for wrapped warning lines`.
* fix(core): log substitution audit trail on YOLO/auto bypass (#4386 review)
Round-3 review caught a real observability gap: when `needsConfirmation`
returns false (YOLO mode at line 1791, or auto-approve at line 1740),
the scheduler skips `getConfirmationDetails()` entirely and the
substitution warning generated there never reaches the user. Pre-#4093
this didn't matter because substitution hard-denied before reaching
the bypass; post-#4093 it executes silently with no audit trail.
YOLO/auto by design execute arbitrary LLM-emitted commands without
warnings — bypassing the substitution warning isn't a new
vulnerability vs. e.g. an unwarned `rm -rf /tmp/x`. But operators
troubleshooting a prompt-injection incident need an audit trail.
Adds a module-level `maybeLogSubstitutionBypass()` helper that emits a
`debugLogger.warn` only when (a) the canonical tool name is in the
shell-like audit set (RUN_SHELL_COMMAND / MONITOR) AND (b) the command
arg contains substitution. Called from both bypass branches with a
`yolo` / `auto-approve` discriminator so the audit log identifies
which path bypassed.
DEBUG-only — silent at default verbosity, no noise for typical YOLO
users; forensic signal lives in `DEBUG=*` traces. No separate test
added: `debugLogger` is module-private (created at the top of
coreToolScheduler.ts), and mocking the createDebugLogger module is
disproportionate complexity for a DEBUG-only audit signal whose
logic is a 7-line guard chain.
* refactor(core): extract substitution warning constant + helper, plus permissionController test (#4386 review)
Round-3 review cleanup, bundling 4 small related findings:
1. **Extract `COMMAND_SUBSTITUTION_WARNING` constant** (`shell-utils.ts`).
The user-facing warning string was hardcoded identically in two
source files (`shell.ts`, `monitor.ts`); tests assert via regex so
the constant doesn't break them. Co-located with
`detectCommandSubstitution` since they share the same domain.
2. **Extract `buildShellExecWarnings()` helper** (`shell-utils.ts`).
The 6-line warnings-building pattern was duplicated between
`ShellToolInvocation.getConfirmationDetails` and
`MonitorToolInvocation.getConfirmationDetails` — same two-input
substitution check (stripped + raw command), same literal push,
same undefined-on-empty contract. Both call sites collapse to a
one-liner. This is a mechanism lift, not a boilerplate lift —
the helper captures non-trivial behavior. The
`checkCommandPermissions` path in `shell-utils.ts` intentionally
keeps its own deny-reason string (different code path, different
threat model — prompt-injection defense for `!{…}` slash commands).
3. **Drop unnecessary non-null assertion** in
`ToolConfirmationMessage.tsx`. Line 268 already defines
`const warnings = executionProps.warnings ?? []`; the JSX block was
using `executionProps.warnings!.map(...)` which (a) reaches past
the null-safe local and (b) misleads readers about whether the
field is actually guaranteed-defined.
4. **Add `permissionController.test.ts`** covering the
`buildPermissionSuggestions` exec branch added in commit 7bb420562.
Seven cases: warning-present (single + multiple), non-string
filtering, warning-absent (missing key + empty array + malformed
non-array), and the null-payload return for invalid input. No test
file existed for this controller before; the new file establishes
the pattern for the four sibling controllers, but stays scoped to
only the method under review.
* fix(core): close AST substitution gaps and log AST parser failures (#4386 R4)
Round-4 critical findings from wenshao:
1. **AST substitution blind spots in non-`command` node types** —
`evaluateStatementReadOnly` (shellAstParser.ts) only checked
`containsCommandSubstitutionAST` inside the `command` node branch.
Substitution living in OTHER node types slipped through as
read-only, causing `resolveDefaultPermission` to return `'allow'`
and `coreToolScheduler` to auto-approve silently. Verified blind
spots (tests added):
- `variable_assignment` / `variable_assignments`:
`FOO=$(curl evil)` and `FOO=$(cat /etc/shadow) ls` were read-only
- Backtick form: `FOO=\`cat /etc/shadow\`` was read-only
The pre-PR #4386 regex check in `resolveDefaultPermission` was a
safety net masking these AST gaps; removing it without patching
the AST was a real security regression.
Fix: hoist the `containsCommandSubstitutionAST` guard to the top
of `evaluateStatementReadOnly` so every node type inherits the
check in one place. Net behavior: substitution anywhere in the
statement subtree marks the whole statement as non-read-only,
matching the contract the function's docstring (and the comment
in `resolveDefaultPermission`) already claimed.
Tests follow Step 7.1 RED → fix → GREEN ordering: confirmed each
of the 3 affected shapes was misclassified as read-only before
the AST hoist, and all 4 cases pass after.
2. **Silent catch in `resolveDefaultPermission`** — the `try/catch`
around `isShellCommandReadOnlyAST` swallowed parser exceptions
without logging. With the regex safety net gone, the AST check is
now the sole gatekeeper, so a parser regression would silently
route every command to 'ask' with no trace. Added the same
`debugLogger.warn` already used by the equivalent catches in
`shell.ts` (line 1394) and `monitor.ts` (line 192).
3. **Misleading comment** in `resolveDefaultPermission` already
asserted "the AST walker marks any node with a substitution
expansion as non-read-only" — true post-fix, but false pre-fix.
Updated to reference the load-bearing top-level guard in
`shellAstParser.ts` so the claim is verifiable from one place.
Closes wenshao R4 findings: AST blind spots (`permission-manager.ts:417`
+ `shellAstParser.ts:884`), silent catch (`permission-manager.ts:415`).
* fix(core): extend substitution audit log + dual-check stripped form (#4386 R4)
Round-4 audit-log consistency fixes from wenshao:
1. **Dual-check stripped form in audit predicate** — round 3's
`maybeLogSubstitutionBypass` only ran `detectCommandSubstitution`
on the raw command, but `buildShellExecWarnings` (the
confirmation-dialog warning helper extracted in round 3) checks
BOTH the raw and the `stripShellWrapper`-stripped forms. For
wrappers like `bash -c 'echo $(cat secret)'` the `$(` sits inside
the outer single quotes, so raw-check returns false but the inner
shell still expands the substitution. Result: dialog showed the
warning, audit log silently dropped it — exactly the wrapper
pattern an exfiltration attack would use. Refactored the helper
to extract a pure predicate `shouldAuditSubstitutionBypass` that
does the dual-check, exported for unit testing.
2. **JSDoc correction** — round 3's JSDoc claimed "DEBUG-level log
here so the signal exists when `DEBUG=*` is set". Both clauses
were wrong: the call uses `debugLogger.warn` (WARN level), and
`debugLogger` is controlled by `QWEN_DEBUG_LOG_FILE` (active by
default) rather than the `DEBUG=*` convention of the `debug` npm
package. Rewrote the doc to match the real semantics.
3. **Audit log on three more auto-approve bypass paths** — round 3
only covered the YOLO and auto-mode-`approved` bypasses, missing
three other paths that auto-approve without invoking
`getConfirmationDetails()`:
- PM `'allow'` fast path (coreToolScheduler.ts:1664) — fires
when an allow rule matches a substitution-bearing command
(e.g. `allow Bash(python3 *)` + `python3 -c "$(...)"`).
- permission-request hook `shouldAllow` (line ~1896) — fires
when an external hook grants permission directly.
- `autoApproveCompatiblePendingTools` sibling-tool ProceedAlways
(line ~3300) — fires when one tool's user-issued ProceedAlways
outcome rolls up to a sister tool. Uses `canonicalToolName`
to normalise the legacy name in the audit log.
New `SubstitutionBypassReason` discriminator union surfaces the
bypass path in the log so operators can distinguish them.
4. **Unit test coverage** — added a `shouldAuditSubstitutionBypass`
describe block to `coreToolScheduler.test.ts` covering all 8
branches: non-shell tool, missing args, non-string command,
absent substitution, direct substitution (shell + monitor), the
load-bearing wrapper case (proves the dual-check works), backtick
substitution, and env-prefix substitution.
Out of scope: reviewer also suggested forcing `'ask'` whenever
substitution is detected with a matching allow rule. Declined —
would partially re-introduce #4093 (substitution can't be allowed
via rules even with explicit user intent), and overrides the
allow-rule "trust this pattern" semantics. The audit-log extension
above gives operators the visibility they asked for without
overriding user-configured permission policy.
Closes wenshao R4 findings: dual-check (cids 3293074365, 3293075616),
JSDoc level/envvar (cids 3293074371, 3293075619), audit on PM-allow
(cid 3293078740 — partial), audit on hook + sibling-auto (rid 4351040390
non-diff), and test coverage for the predicate (cid 3293078758 — partial).
* test(core): cover env-prefix substitution + buildShellExecWarnings dual-check (#4386 R4)
Round-4 test-coverage findings from wenshao:
1. **env-prefix integration test in `shell.test.ts`** (cid 3293075622) —
the `command substitution warning (issue #4093)` describe block in
`shell.test.ts` covered `$()`, backticks, `<()`, `>()`, and the
no-warning case, but had no test for the shape where
`stripShellWrapper` strips the env-prefix + `bash -c` wrapper to
yield a substitution-free inner command (`echo ok`) while the raw
command has substitution in the env assignment
(`FOO=$(cat secret.txt) bash -c 'echo ok'`). This is the exact
shape that exercises the `|| detectCommandSubstitution(rawCommand)`
branch of `buildShellExecWarnings` via integration through
`getConfirmationDetails`. Without this test, removing the `||`
clause wouldn't regress any case here.
2. **`buildShellExecWarnings` unit tests in `shell-utils.test.ts`**
(cid 3293078758 second half) — round 3 extracted
`buildShellExecWarnings` as an exported helper but added no direct
unit test. Added a 5-case describe block covering: no substitution,
stripped-form substitution, the env-prefix dual-check case (with
a sanity-check that the stripped form actually lacks `$(` to make
the dual-check load-bearing), backticks, and process substitution.
These complement the integration tests in shell.test.ts /
monitor.test.ts which exercise the helper through the tool
confirmation paths.
Closes wenshao R4 findings: env-prefix integration test
(cid 3293075622), `buildShellExecWarnings` direct unit coverage
(cid 3293078758 — second half).
* fix(test): drop duplicate ToolNames import in coreToolScheduler.test (#4386 R4 CI)
Round-4 commit a24485029 added `import { ToolNames }` without checking
the file already had `import { ToolNames, ToolNamesMigration }` at line
35. Vitest's esbuild was permissive about the duplicate (silently used
the latter) so the test file passed locally and `npx tsc --noEmit` on
the package didn't complain either — but CI's `tsc --build` is strict
and errored with TS2300 "Duplicate identifier 'ToolNames'", taking down
Lint + all three test platforms + Coverage in one go (run 26382523711).
Removed the duplicate import. Verified locally via `rm -rf
packages/core/dist && npx tsc --build` (clean) + `npx vitest run`
(171/171 pass).
* fix(core): close env-prefix wrapper substitution bypass at L3 (#4386 R6)
Round-6 review caught a real Critical security regression my R0 +
R4 audits both missed.
**The bug.** `ShellToolInvocation.getDefaultPermission()` calls
`stripShellWrapper(this.params.command)` BEFORE the AST check. For
`FOO=$(curl evil) bash -c 'echo ok'`, `stripShellWrapper` discards the
env-prefix AND unwraps the `bash -c` wrapper, yielding `echo ok` — a
substitution-free residual that the AST classifies as read-only.
Result: L3 returns `'allow'` → coreToolScheduler fast-allow at
line 1664 auto-approves silently with no confirmation dialog and no
user-visible warning.
The R4 top-level AST guard (`evaluateStatementReadOnly` ↳
`containsCommandSubstitutionAST`) only catches substitution that
survives `stripShellWrapper` to enter the parsed tree. The env-prefix
+ wrapper shape gets stripped to nothing visible, so the AST guard is
asked to inspect a clean tree and returns true. The pre-#4386 regex
`detectCommandSubstitution` in `resolveDefaultPermission` was a safety
net masking exactly this gap — R0 removed it without recognising the
strip-before-check pattern.
Probe (vitest harness, real `isShellCommandReadOnlyAST`):
```
{
raw: "FOO=`whoami` bash -c 'ls'",
stripped: "ls",
ast_on_stripped: true, // ← classifies as read-only
ast_on_raw: false // ← R4 guard works on raw
}
```
**The fix — `hasShellSubstitution` single source of truth.**
Extracted dual-check predicate (`detectCommandSubstitution(raw) ||
detectCommandSubstitution(stripShellWrapper(raw))`) into
`shell-utils.ts hasShellSubstitution(rawCommand)`. The raw arm catches
the env-prefix-wrapper shape; the stripped arm catches the inside-
single-quoted-wrapper-body shape that R3 already documented. Single
predicate keeps detection semantics in lockstep across all surfaces.
Gates added at:
- `ShellToolInvocation.getDefaultPermission` (shell.ts:1384) — primary
fix for the cited bug
- `shellReadOnlyChecker.ts evaluateShellSegment` (line 298) — regex
fallback path has the same strip-before-check pattern; only hit when
WASM parser fails, but same root cause
- `MonitorToolInvocation.getDefaultPermission` (monitor.ts:174) —
belt-and-suspenders; `normalizeMonitorShellCommand`'s `safetyCommand`
preserves env-prefix tokens so the AST already sees substitution
there, but the gate parallels shell.ts in case
`normalizeMonitorShellCommand`'s env-preservation ever regresses
- `PermissionManager.resolveDefaultPermission` (permission-manager.ts:413)
— belt-and-suspenders; the raw command reaches the AST already, but
the reviewer-requested gate makes the intent grep-discoverable
Refactor (Finding C, cid 3298521063): `buildShellExecWarnings` and
`shouldAuditSubstitutionBypass` both now delegate to
`hasShellSubstitution`, addressing the reviewer's concern that the
audit-log path and the UI-warning path were maintaining parallel
dual-check implementations that could silently diverge.
**Test-first per skill Step 7.1.** Two new tests in `shell.test.ts`
under `getDefaultPermission and getConfirmationDetails`:
- `asks (not allow) for env-prefix substitution inside a bash wrapper`
- `asks for backtick env-prefix substitution inside a bash wrapper`
Both confirmed RED pre-fix (`expected "ask" got "allow"`); GREEN
post-fix. Wider sweep (1262 tests across 19 files in permissions,
tools, utils, core, cli) all green; tsc --build clean (matching CI's
strict build).
Out of scope for this commit (deferred to follow-up #4509):
- R6 Finding B (dead catch blocks in resolveDefaultPermission / shell /
monitor) — appended to #4509
- R6 Finding D (Record<string, unknown> cast in permissionController
exec branch — could use discriminated-union narrow) — appended to #4509
- R6 Finding E (O(N×D) DFS in evaluateStatementReadOnly — could be
hoisted to isShellCommandReadOnlyAST as O(N) root-level check) —
appended to #4509
Closes wenshao R6 findings: env-prefix wrapper bypass (cid 3298521039 —
Critical, fixed) + dual-check DRY (cid 3298521063 — fixed as side
effect of A's refactor).
* revert: remove substitution audit-log infrastructure (#4386 cleanup)
Reverts:
- fd2cf080d "fix(core): log substitution audit trail on YOLO/auto bypass"
- a24485029 "fix(core): extend substitution audit log + dual-check stripped form"
The audit-log infrastructure was originally added in R3 as a self-Codex
suggestion (forensic visibility when YOLO bypasses the substitution
warning) and extended in R4 to PM-allow / hook / sibling-auto paths.
None of this is what issue #4093 asked for — #4093 is purely about
making substitution `'ask'` instead of `'deny'` so YOLO can override
and the behavior is consistent across rule configurations. The audit
log is debug-only forensic polish on a UX warning, not part of the
permission-decision fix.
Each subsequent review round (R4/R5/R6/R7) then surfaced sibling-drift
findings on this infrastructure — PM-allow audit, hook audit, ACP
audit-log parity, callId enrichment, dual-check asymmetry, integration
tests — all of which were tracking the same out-of-scope addition.
Removing the infrastructure removes the surface entirely.
`hasShellSubstitution` (added in 5a5cfb4fc) is kept — it's still used
by `shell.ts` L3 substitution gate and `buildShellExecWarnings`, both
of which ARE in scope for #4093.
* cleanup: remove out-of-scope additions from R2/R3/R6 review (#4386)
Surgical reverts that complement a5d9f087e (audit-log infrastructure
revert). These changes were accepted in earlier review rounds but were
out of scope for issue #4093 — a bug-fix PR whose stated goal is to
make command substitution `'ask'` instead of `'deny'` so YOLO can
override and the behavior is consistent across rule configurations.
Anything beyond that fix is unrelated to the bug and not this PR's
responsibility.
Removed:
1. **ACP `permissionUtils.ts`: `exec` branch in
`buildPermissionRequestContent`** (R2, commit 7bb420562). The new
`warnings` field propagation to ACP clients (VS Code extension,
daemon) was UX polish on a different surface. Not what #4093 asked
for. Plus the two regression tests in `permissionUtils.test.ts`.
2. **Non-interactive `permissionController.ts`: `case 'exec'`
warning-suffix on the suggestion description** (R2, commit 7bb420562).
Same pattern as above — warning propagation to daemon/API consumers
on a non-primary surface. Plus the entire
`buildPermissionSuggestions — exec warnings` describe block I added
to `permissionController.test.ts` (R3, commit baa1e9f78). Main's
#4491 timeout tests (which merged in via 6342d2810) are preserved.
3. **`monitor.ts` belt-and-suspenders `hasShellSubstitution` gate**
(R6, commit 5a5cfb4fc). I added this with an explicit "if
normalizeMonitorShellCommand's env-preservation ever regresses"
justification — i.e. defense-in-depth on a non-existent bug. Not
what #4093 asked for.
4. **`permission-manager.ts` belt-and-suspenders `hasShellSubstitution`
gate at `resolveDefaultPermission`** (R6, commit 5a5cfb4fc). Same
pattern — reviewer-requested gate on top of a code path the R4 AST
guard already covered. Not what #4093 asked for.
What's kept (in scope for #4093):
- L4 `deny → ask` in `resolveDefaultPermission` (the actual fix)
- `warnings?: string[]` field on `ToolExecuteConfirmationDetails` +
CLI rendering — #4093 explicitly asks for a user-visible reason
- `ShellToolInvocation.getDefaultPermission` env-prefix wrapper gate
(R6, 5a5cfb4fc) — closes a real `'allow'` regression on substitution
- `shellReadOnlyChecker.ts` regex-fallback raw-check (R6, 5a5cfb4fc)
— same root-cause bug on the WASM-fallback path
- AST top-level substitution guard in `evaluateStatementReadOnly`
(R4, 42debd13d) — closes real AST blind spots
- `hasShellSubstitution`, `buildShellExecWarnings`,
`COMMAND_SUBSTITUTION_WARNING` helpers — still used by the above
- Monitor tool's `'deny' → 'ask'` alignment for substitution (R2,
7bb420562) — same root-cause as the main fix
* feat(worktree): Phase D — startup --worktree flag + symlinkDirectories + PR refs
Three cross-cutting capabilities on top of the Phase A-C worktree
foundation (PRs #4073, #4174).
D-1: --worktree [name] CLI flag creates a worktree (or re-attaches to
one that already exists) before any model turn runs. Supports bare,
plain-slug, `=`, and PR-reference forms; --worktree + --acp rejected
with a clear error; --worktree + --resume overrides the resumed
session's saved sidecar and emits a stderr line.
D-2: worktree.symlinkDirectories: string[] settings key opts into
symlinking main-repo directories (e.g. node_modules) into every
newly-created general-purpose worktree. Applies to all three creation
paths: --worktree flag, EnterWorktreeTool, AgentTool isolation. Path
traversal, absolute paths, and existing destinations all guarded;
missing source dirs and EEXIST silently skipped (fail-open).
D-3: --worktree=#<N> / --worktree <github-url> resolves a PR number,
runs `git fetch origin pull/<N>/head` (30s timeout, no `gh` CLI
dependency, LANG=C for stable error-taxonomy matching), and creates
the worktree off FETCH_HEAD. URL regex tolerates /files, /commits,
/checks sub-paths so users can paste any GitHub PR URL.
Phase 6 verification fixes also included:
- Re-attach to an existing worktree instead of failing with "Worktree
already exists" — the common `qwen --resume <sid> --worktree foo`
workflow now succeeds. The session ownership marker is preserved on
re-attach so cross-session exit_worktree action="remove" still fails
for non-owners.
- Normalize path-taking argv fields (mcpConfig, jsonSchema @<path>,
openaiLoggingDir, jsonFile, inputFile, telemetryOutfile,
includeDirectories) to absolute paths against the launch cwd BEFORE
the worktree chdir. Otherwise downstream fs.existsSync('./mcp.json')
resolves into the worktree, where the file doesn't exist.
Phase 7 code-review fixes:
- buildStartupWorktreeNotice differentiates "Active worktree" (fresh
create) from "Re-attached to worktree" (re-attach path).
- Notice survives sidecar persist failure: set before the try block,
refreshed inside with override addendum if persist succeeded.
- getRegisteredWorktreeBranch verifies the candidate path's git
common-dir matches the source repo's — rejects sibling `git init`
directories that happen to be on a worktree-<slug> branch.
Three-mode parity for the startup notice: TUI consumes via
AppContainer effect, headless prepends a <system-reminder> + emits a
worktree_started JSON event. ACP path is mutually exclusive with
--worktree (ACP hosts supply per-session cwd separately).
Tests (66 + 15 new):
- 15 cli/src/startup/worktreeStartup.test.ts (slug forms, PR fetch
against local fake remote, re-attach happy + wrong-branch guard)
- 8 core/src/services/gitWorktreeService.test.ts (parsePRReference:
#N, URLs, malformed, traversal, leading zeros, non-string)
- 10 core/src/services/gitWorktreeService.symlinks.integ.test.ts
(symlink loop + fetchPullRequestRef error taxonomy)
Known limitations (documented in docs/users/features/worktree.md):
- Cross-slug --resume <sid> --worktree <different-new-slug> is
unsupported by design (sessions are bound to projectHash(cwd));
future Config refactor anchoring storage at repo root would lift this.
- Mid-session enter_worktree still does NOT switch cwd/targetDir
(Phase A's simplification); only the startup --worktree flag does.
- yargs ambiguity: `qwen --worktree "say hi"` consumes the prompt as
the slug. Quick Start shows the `=` form and reordering workarounds.
Docs:
- docs/users/features/worktree.md (new): Quick Start with --worktree
flag, CLI Reference table for all four input forms + error codes,
settings table, Limitations.
- docs/design/worktree.md: Phase D section expanded into D-1/D-2/D-3
with open questions resolved; capability table updated.
- docs/e2e-tests/worktree-phase-d.md (new): full E2E plan with Phase 4
dry-run baseline + Phase 6 post-impl reproduction tables.
Refs #4056
* refactor(worktree): apply self-review feedback on Phase D
Self-review pass over the Phase D commit (2636f59273) catching one real
typecheck regression plus a batch of small quality + efficiency
improvements. No user-visible behavior change beyond fixing the build.
Build fix:
- worktreeStartup.ts imports — pre-commit prettier had reorganized
`writeWorktreeSession` and `readWorktreeSession` under an
`import type { ... }` block, erasing them at compile time
(verbatimModuleSyntax). `tsc --noEmit` was failing with TS1361.
Bundle path still worked (esbuild is lenient) so this only surfaced
when running typecheck.
Startup-path efficiency (~10-25 ms saved per --worktree invocation on
macOS; more on Windows):
- Drop redundant `isGitRepository()` probe — `getRepoTopLevel()`
returns null on non-git paths and covers both gates in one
subprocess.
- Run `getCurrentBranch()` + `getCurrentCommitHash()` in parallel via
Promise.all (independent calls).
- Combine the two `git rev-parse` probes inside
`getRegisteredWorktreeBranch` into a single multi-arg call, and run
it in parallel with the source-repo common-dir lookup. Saves one
fork+exec on the re-attach path.
Quality:
- Extract `withReminder()` local helper in nonInteractiveCli.ts so the
startup-notice and resume-restore branches share the system-reminder
wrapping.
- Log `readWorktreeSession` failures in `persistStartupWorktreeSidecar`
with the sidecar path so operators can recover the previous slug
from a backup. Silent swallow was making "where did my worktree
binding go?" undebuggable.
- Drop the dead `Config.getWorktreeSettings()` accessor (only
`getWorktreeSymlinkDirectories()` has callers); keep the underlying
`WorktreeSettings` interface for future fields.
- Document the `pendingStartupWorktreeNotice` invariant: at most one
consumer per process; ACP path is gated out earlier so only TUI XOR
headless reads it.
- Add a maintainer note in the gemini.tsx path-normalization block:
the argv path-field allowlist is hand-maintained, register new
path-bearing flags there or `--worktree` silently breaks for them.
- Drop `Phase 6 fix (G1)/(G2)` parenthetical labels from inline
comments — internal review-cycle identifiers that decay to noise
post-merge. Substantive prose retained.
Tests: cli 15/15 (unchanged) + core 66/66 (unchanged); bundle smoke
verified fresh / re-attach / invalid slug / non-git cases.
Findings deliberately left for follow-up:
- Larger refactor extracting a shared `provisionUserWorktree` helper
for the EnterWorktreeTool / startup overlap (~80% duplicate).
- Splitting the re-attach branch out of `setupStartupWorktree` into
its own function.
- `isPathWithinRoot` / `isInsideManagedWorktree` shared utils.
- `symlinkConfiguredDirectories` loop concurrency (saves 5-15 ms on a
cold path that runs only when symlinkDirectories is configured).
* docs(worktree): refresh stale docstring in worktreeStartup
Top-of-file docstring still said `{adj}-{noun}-{4hex}` (actual format
is 6 hex chars) and described the PR form as "detected and rejected
with a clear 'coming in D-3' message" — but D-3 shipped in the same
PR. Tighten to reflect what the code actually does.
* fix(worktree): address findings from dual-reviewer self-check
Two real bugs surfaced by an independent dual-reviewer pass (Claude +
Codex) on the Phase D commits. Both correctness-affecting; both
escaped the earlier internal reviews.
P0 — re-attach captured the wrong baseline for the exit dialog
(Codex):
setupStartupWorktree captured `originalHeadCommit` from the launch
cwd (main checkout) before any chdir. On the re-attach path the
WorktreeExitDialog later runs `git rev-list <originalHeadCommit>..HEAD`
inside the worktree to count "new commits this session". With the
main-checkout baseline this counted every commit ever made in the
kept worktree as new work from the current session — misleading the
keep/remove prompt. Re-capture HEAD from inside the worktree after
chdir so the count means what the dialog text says it means.
P0 — getRegisteredWorktreeBranch mis-identified plain directories as
registered worktrees (Claude):
A plain directory at `<repo>/.qwen/worktrees/<slug>/` (e.g. a stale
artifact from a previous tool) had no `.git` file of its own, so
`git rev-parse --git-common-dir` walked up to the outer repo and
returned the outer common-dir — matching the source repo's
common-dir check and impersonating a registered worktree. If the
outer repo happened to be on `worktree-<slug>`, setupStartupWorktree
would silently chdir into the plain directory and treat it as
attached; subsequent `exit_worktree action="remove"` would then
delete a directory that was never registered.
Fix: also probe `--show-toplevel` and require it to equal the
candidate path (canonicalised via `realpath` so macOS /var → /private/var
doesn't break the equality check). A plain dir under the main repo
gets the outer repo's toplevel and is correctly rejected.
Smaller polish from the same review:
- Normalize the literal string `'HEAD'` returned by `getCurrentBranch`
on detached HEAD to `undefined`, so the `baseRef` handed to
`git worktree add -b … HEAD` does not implicitly anchor against
the loose commit when the launch cwd is detached.
- `symlinkConfiguredDirectories`: blocklist `.git` (any nested
ancestor) and `.qwen/worktrees` (any nested ancestor). Linking
`.git` would silently break commits inside the worktree; linking
`.qwen/worktrees` would create a worktrees-inside-worktrees loop
that confuses the startup sweep.
- `WorktreeSettings.symlinkDirectories` typed `readonly string[]` to
match the `createUserWorktree(options.symlinkDirectories)` contract
and the immutable-config convention elsewhere. `Config.getWorktreeSymlinkDirectories()`
return type updated to match.
Docs:
- design/worktree.md precedence table rewritten. The previous
`--worktree` 赢 row was unreachable in practice (sessions are bound
to `projectHash(cwd)`, and the chdir happens before session lookup).
New table reflects what actually happens for each combination of
`--resume` × `--worktree`, including the documented
cross-projectHash limitation. The `persistStartupWorktreeSidecar`
override branch is now annotated as dead-on-the-current-architecture
but kept so a future Config refactor (anchor storage at repo root)
picks it up for free.
Tests: cli 15/15 + core 66/66 unchanged. Bundle smoke confirms both
P0 fixes end-to-end (re-attach captures worktree HEAD = run-1 tip,
plain-dir attempt errors out without clobbering existing content).
* refactor(worktree): consolidate probe + name detached-HEAD sentinel
Second /simplify pass on the dual-reviewer fixes. Three convergent
findings; net effect is one fewer subprocess on the re-attach path
and clearer intent on string handling / blocklist guards.
Efficiency + quality:
- Fold the worktree HEAD SHA into `getRegisteredWorktreeBranch`'s
combined rev-parse. The probe already requests common-dir,
toplevel, and abbrev-ref HEAD in a single subprocess; adding a
leading `HEAD` positional (which must come BEFORE `--abbrev-ref` so
the flag doesn't apply to it) returns the SHA on its own line.
Return type widened to `{ branch, headCommit } | null`. Removes
the second `GitWorktreeService` instantiation and `getCurrentCommitHash`
call that `setupStartupWorktree`'s re-attach branch used to do.
Quality:
- Hoist `'HEAD'` to a module-level `DETACHED_HEAD` constant in
`worktreeStartup.ts`. Three uses, two meanings (input filter when
normalizing `getCurrentBranch` output, fallback metadata for the
sidecar's `originalBranch` field on detached state). Naming the
sentinel makes intent self-documenting and pre-empts the "why is
the value we just stripped re-appearing as a fallback?" reader stall
flagged by the round-3 quality review.
Reuse + quality:
- `symlinkConfiguredDirectories`: replace two hand-rolled containment
checks (`startsWith(prefix + sep)` for `.qwen/worktrees`; `path.relative(...).split(sep)[0]`
for `.git`) with `isWithinRoot` from `utils/fileUtils.ts`, which is
already imported in this file. Replace the hardcoded
`path.join(repoRootAbs, '.qwen', 'worktrees')` with `this.getUserWorktreesDir()`
so the layout lives in one place (the exported `WORKTREES_DIR`
constant). Split the misleading `sourceAbs === repoRootAbs` clause
out of the `.git` branch into its own dedicated "empty / repo-root
path" rejection with a clearer warn message.
Tests: cli 15/15 + core 66/66 unchanged. Bundle smoke verified the
folded probe still captures the worktree's HEAD on re-attach (not
the launch-cwd HEAD).
Skipped from this review pass:
- Moving `'HEAD'` normalization into `GitWorktreeService.getCurrentBranch()`
itself — would ripple through `enter-worktree.ts` and `agent.ts`
callers that hand the result verbatim to `git worktree add -b ...`.
Out of scope for a polish pass; the local const is enough.
* fix(worktree): broaden symlink blocklist from .qwen/worktrees to all of .qwen
Caught by a second pr-tracker dual-reviewer pass (Codex). The previous
guard at `symlinkConfiguredDirectories` only refused paths inside
`<repoRoot>/.qwen/worktrees/` — `.qwen` itself (the parent) sailed
through because `isWithinRoot` is a strict descendant check. A user
setting `symlinkDirectories: ['.qwen']` would therefore symlink the
entire CLI metadata tree into the new worktree, recursively pulling
in `.qwen/worktrees` and recreating the loop the guard was meant to
prevent. Other `.qwen/*` subtrees (`projects`, `tmp`, …) are CLI
state with no legitimate cross-worktree sharing use case either.
Fix: broaden the guard to reject the whole `<repoRoot>/.qwen` tree.
Both `.qwen` itself and any descendant fail closed.
Also synced the user-facing settings schema description (the in-IDE
help text and the published JSON schema) so it mentions the `.git`
and `.qwen` rejection rules. The `WorktreeSettings` interface JSDoc
already mentioned them; the schema description had not been updated.
Tests: cli 15/15 + core 66/66 unchanged. Smoke confirms `--worktree foo`
with `symlinkDirectories: ['.qwen']` configured leaves the worktree
free of any `.qwen` symlink (only the legitimate per-worktree
`.qwen-session` marker file appears).
* fix(worktree): guard fetchPullRequestRef against CodeQL command-injection alert
CodeQL flagged a "Second order command injection" finding (rule 235) on
the `git fetch origin pull/<N>/head` call in `fetchPullRequestRef`. The
taint analyzer doesn't see the type-narrowing at the function entry
(`Number.isSafeInteger(prNumber) && prNumber > 0 && prNumber <= 1e9`),
so it considers `prNumber` library input that could in principle reach
a `--upload-pack=…`-shaped flag and thereby execute an arbitrary
program. In practice the entry guard already prevents that, but the
alert blocks the CodeQL CI check.
Add `--end-of-options` between `origin` and the refspec — git's
canonical "stop parsing flags" marker (git ≥ 2.24). Tells git
definitively that every subsequent argv element is a positional, not
a flag, which (a) satisfies the analyzer, (b) adds defense-in-depth
against a future regression that might relax the entry guard, and
(c) has zero behavior change for any well-formed PR number.
Verified locally: `git fetch --end-of-options origin pull/<N>/head`
against a local bare-remote with a seeded `refs/pull/42/head` still
fetches the ref correctly; the `--worktree=#42` smoke test reads back
the PR content from the materialized worktree.
Tests: cli 15/15 + core 66/66 unchanged.
* fix(worktree): lexical sanitizer for CodeQL + missing test mock entry
Two fixes from the third CI round on PR #4381:
1. CodeQL re-fires (round 2 of the same finding).
`--end-of-options` is a git-runtime defense, not a lexical sanitizer
that CodeQL's `js/second-order-command-line-injection` taint tracker
recognises. The alert re-fired against the same call after the
previous fix.
Switch to a CodeQL-recognised sanitizer: validate the numeric
component against `/^[1-9][0-9]*$/` immediately at the sink. The
regex digit-only check is one of the documented sanitizer patterns
the rule looks for, and proves at the analyzer level that the
resulting argv element cannot resemble a flag (`--foo`). The entry
guard at the top of the function still establishes the same fact
at runtime; this layer makes the proof visible to static analysis.
Keep `--end-of-options` as a runtime fallback against any future
regression that loosens the entry guard.
2. `nonInteractiveCli.test.ts` mock was missing the new
`consumePendingStartupWorktreeNotice` Config method.
Phase D-1 added the method on `Config` and `nonInteractiveCli`
calls it on every prompt to pick up the one-shot startup-worktree
notice. The test file's `mockConfig` literal was not updated, so
all 19 `runNonInteractive` tests threw
`TypeError: config.consumePendingStartupWorktreeNotice is not a
function` on Ubuntu / macOS CI.
Add a stub returning `null` so the helper short-circuits, matching
the equivalent Phase C stub for `getResumedSessionData`.
Local: cli (worktreeStartup + nonInteractiveCli) 60 passed + 1
skipped; core (gitWorktreeService + symlinks + hooks +
enter-worktree) 66 passed.
* test(worktree): mock getWorktreeSymlinkDirectories in three more test files
Round 4 of the same Phase D-2 mock-drift class. CI surfaced 9 test
failures across three files whose `Config` mocks construct
`EnterWorktreeTool` for setup but lack the new
`getWorktreeSymlinkDirectories` method `createUserWorktree` now
calls:
- enter-worktree.session.integ.test.ts (2 tests)
- exit-worktree.session.integ.test.ts (3 tests) — provisions
worktrees via EnterWorktreeTool before exercising exit paths
- exit-worktree.test.ts (4 tests) — same provisioning pattern via
`provisionWorktree()` and the `makeMockConfig` helper
Add a `getWorktreeSymlinkDirectories: () => []` stub to each so
the symlink loop is a no-op in tests.
`enter-worktree.test.ts` and `agent/agent.test.ts` intentionally
skipped — they mock `GitWorktreeService.createUserWorktree` outright,
so the method call never fires in their code paths. Adding the stub
there would be defensive speculation. If a future test exercises
the real path, it'll surface there too and we'll add it then.
Local: core tools tests now 123 passed (was 9 failed / 114 passed
on CI run 26213122427 against commit 000c9f63).
* fix(worktree): normalize repoRoot path separators + disable autocrlf in tests
Round 5 of CI: Windows-only test failures on the latest HEAD. Two
unrelated Windows-specific bugs, both in / around worktreeStartup.
1. `setupStartupWorktree` stored the raw `getRepoTopLevel()` output
in `context.repoRoot`. git always emits POSIX paths via
`--show-toplevel` (`C:/Users/...`), so on Windows the value was
forward-slash where `fs.realpath` and `path.join` produce
backslash. The sidecar's `originalCwd` field got the
inconsistent format and a downstream `expect(...).toBe(tempRepo)`
in the round-trip test compared `C:/Users/.../tmp/...` against
`C:\Users\.../tmp/...`.
Wrap the value in `path.resolve()` to normalize to the
platform-native separator before storing. Downstream consumers
(`path.join(session.originalCwd, '.qwen', 'worktrees')` in
`restoreWorktreeContext`, `new GitWorktreeService(originalCwd)`
in `AppContainer`) already handle either format, so no migration
concern for older sidecars.
2. `makeTempRepo` in worktreeStartup.test.ts didn't configure
`core.autocrlf=false`. On Windows runners the default is `true`,
so files committed and pushed to the test's fake-remote `pull/<N>/head`
ref get CRLF-converted on the worktree's checkout. The PR-content
assertion `expect(prFile).toBe('from PR 42\n')` then failed with
`'from PR 42\r\n'`.
Add `core.autocrlf=false` + `core.eol=lf` to the temp-repo setup
so test files round-trip byte-for-byte regardless of host platform.
Local mac: cli worktreeStartup 15/15 still pass. Windows verification
deferred to CI.
* fix(worktree): reject '..' segments + use junction on Windows
Two Copilot findings on symlinkConfiguredDirectories (PR #4381 round 3):
1. The settingsSchema description, docs/users/features/worktree.md, and
WorktreeSettings JSDoc all promise that entries containing `..` are
rejected — but the post-resolve isWithinRoot check accepted
`foo/../bar` (resolves to `bar`, inside the repo). Add a literal `..`
segment check before path.resolve so the code matches the contract.
2. On Windows, fs.symlink(..., 'dir') requires
SeCreateSymbolicLinkPrivilege (admin / Developer Mode) and EPERMs on
default consumer installs. Use 'junction' for directory entries on
win32 — junctions are reparse points that achieve the same semantics
without elevation. Keep 'dir' on POSIX and 'file' for non-directory
sources (no junction-equivalent for files; rare path).
Adds an integration test exercising `foo/../bar` to lock in the
syntactic guard; existing absolute-path and traversal tests already
covered the other rejection forms.
* fix(worktree): PR-worktree HEAD-SHA capture + symlink guard tests
Three findings from wenshao round 4 (PR #4381):
1. For --worktree=#42 (PR worktrees), originalHeadCommit was captured
from the parent repo's HEAD via getCurrentCommitHash() — but the
worktree branches off FETCH_HEAD (the PR tip), not main. Downstream,
WorktreeExitDialog's `rev-list <originalHeadCommit>..HEAD` would
count every commit in the fetched PR as "new work this session"
alongside the user's actual commits.
Same root cause covers the FETCH_HEAD TOCTOU window: between
`git fetch origin pull/<N>/head` and `git worktree add ... FETCH_HEAD`,
a concurrent `git fetch` from any other process sharing this repo
could overwrite .git/FETCH_HEAD, causing the worktree to branch off
an unrelated commit.
Fix: add GitWorktreeService.resolveRef(ref) that returns a 40-char
SHA (or null). In setupStartupWorktree, immediately after
fetchPullRequestRef succeeds, resolve FETCH_HEAD to an immutable
SHA; pass that SHA both as the baseRef to createUserWorktree (closes
the TOCTOU) AND as originalHeadCommit in the returned context
(closes the exit-dialog miscount). Fail-close on null resolve.
2. Orphaned JSDoc block at gitWorktreeService.ts:1035-1048 — originally
wrote validateUserWorktreeSlug's docs, stranded above parsePRReference
after that function was inserted between them. Move the block down to
sit immediately above validateUserWorktreeSlug at its current line.
3. `.git` / `.qwen` symlink rejection guards (~20 lines of security-
critical code at gitWorktreeService.ts:1640-1655) had no regression
tests — only absolute paths, `..` traversal, isWithinRoot escapes,
and missing sources were covered. Add two integ tests in
gitWorktreeService.symlinks.integ.test.ts: one asserts `.git/hooks`
is refused, one asserts `.qwen/projects` is refused.
Also extends the existing PR-worktree integration test in
worktreeStartup.test.ts to assert originalHeadCommit equals the
resolved FETCH_HEAD SHA AND does NOT equal the parent repo's main HEAD
— the assertion would fail loudly if the new SHA-capture path were
reverted.
* fix(worktree): realpath check on symlinkDirectories source + dest paths
Security fix from PR #4381 round 7 (wenshao/qwen3.7-max). The lexical
isWithinRoot + .git/.qwen blocklist checks in symlinkConfiguredDirectories
all operated on path.resolve(repoRoot, raw) — a STRING operation that
doesn't follow symlinks. A committed (or out-of-band) symlink at
<repo>/node_modules pointing into .git would pass every gate:
1. path.resolve gives `<repo>/node_modules` (lexical, passes
isWithinRoot against repo root).
2. The .git/.qwen blocklists also see the lexical path — they don't
detect that the realpath chains into .git.
3. fs.stat() follows the symlink and succeeds against .git/.
4. fs.symlink writes `<worktree>/node_modules → <repo>/node_modules`,
which OS-side resolves through to <repo>/.git. Any tool inside the
worktree that writes to node_modules/hooks/post-merge then has RCE
on the next hook-firing git operation.
Fix: after fs.stat succeeds, fs.realpath the source and RE-RUN the three
containment checks against the realpath. Refuse on any escape. Use the
realpath (not the lexical sourceAbs) as the symlink target so the new
link is one-hop canonical rather than preserving the chain.
Also closes the dest-side variant of the same root cause — flagged in
round 4 thread #5 (declined then as overthinking) but now in scope per
the skill's iteration rule (two consecutive rounds raising the same
root-cause class). path.join(worktreePath, raw) is also lexical: if
git worktree add materialized a committed worktree-level symlink (e.g.
HEAD ships tools → /etc), then fs.mkdir / fs.symlink for a nested entry
like "tools/cache" writes OUTSIDE the worktree. Realpath the dest
parent before mkdir and refuse if it escapes the worktree.
New integ test covers both source-side variants (escape-to-git via
out-of-band symlink + escape-to-outside-dir) in one block. Was RED
against the pre-fix code: <wt>/escape-to-git was created as a symlink
that chained into the source repo's .git. GREEN after the fix.
* fix(worktree): canonicalise repo root before symlinkDirectories checks
Round-7's source-side realpath fix introduced a canonical-vs-lexical
mismatch: `repoRootAbs = path.resolve(this.sourceRepoPath)` is purely
lexical, while `realSource = await fs.realpath(sourceAbs)` is canonical.
On macOS where `/tmp → /private/tmp` and `/var → /private/var` are
ubiquitous, and on any Linux/Windows setup where the user's checkout
sits behind a symlink, the prefixes diverge at the symlink boundary and
`isWithinRoot(realSource, repoRootAbs)` silently rejects every
configured entry.
Production callers (worktreeStartup.ts, EnterWorktreeTool,
agent isolation) all pass the lexical path returned by
`git rev-parse --show-toplevel`. The integ tests masked the bug because
the shared `beforeEach` did `repoRoot = await fs.realpath(dir)` upfront.
Round 8 fix:
- Hoist `repoRootAbs`, `gitDirAbs`, `qwenDirAbs`, and `realWorktreePath`
outside the for-loop — they're loop invariants and were being
recomputed once per entry.
- `await fs.realpath(this.sourceRepoPath)` for `repoRootAbs` so every
containment check below is canonical-vs-canonical. The derived
`gitDirAbs` / `qwenDirAbs` blocklist paths inherit the canonical
prefix automatically. `sourceAbs = path.resolve(repoRootAbs, raw)`
inherits it too, so the early lexical reject paths (absolute, `..`,
repo-root equality, isWithinRoot) stay self-consistent.
- Fail-close: if the repo root itself doesn't realpath (deleted /
inaccessible), bail out of the entire symlink loop rather than
continuing with comparisons we can't trust. Non-destructive — the
worktree was created earlier by `git worktree add`.
New integ test provisions the production shape: a symlink path used
as `sourceRepoPath`, distinct from its canonical realpath. RED on the
pre-fix code (assertion fired with "symlinkDirectories entry was
silently rejected — canonical vs lexical isWithinRoot mismatch"),
GREEN after.
* fix(cli): auto-prepend @ when pasting or dropping multiple file paths
When pasting or drag-and-dropping a single file path, Qwen Code
automatically prepends @ to convert it into an @file reference. However,
pasting or dragging multiple file paths (separated by newlines or
whitespace) did not receive the same treatment, requiring users to
manually add @ to each path.
This change extends the paste detection logic in text-buffer.ts to
detect and prepend @ to multiple file paths, matching the behavior
of single-file paste/drag. The fix also strips surrounding quotes
(common in drag-and-drop input) before path validation.
Before:
- Drag & drop 1 file → @file ✅
- Drag & drop 3 files → 'file1' 'file2' 'file3' ❌
- Paste 1 file → @file ✅
- Paste 3 files → file1 file2 file3 ❌
After:
- Drag & drop 1 file → @file ✅ (unchanged)
- Drag & drop 3 files → @file1 @file2 @file3 ✅ (fixed)
- Paste 1 file → @file ✅ (unchanged)
- Paste 3 files → @file1 @file2 @file3 ✅ (fixed)
* fix(cli): simplify path extraction and escape spaces for @-paths
Refactor multi-file paste @-path detection:
- Extract tryExtractFilePaths() and extractPathsFromSegment() helpers
to eliminate ~100 lines of duplicated path-extraction logic
- Add shellModeActive guard to newline paste branch for consistency
- Remove redundant isPaste variable
- Escape spaces in paths with backslash so downstream parseAllAtCommands
parser correctly handles filenames with spaces (e.g. @/path/to/my\ file.txt)
* fix(cli): address wenshao's code review for multi-file paste
Address 3 critical and 4 suggestion issues from wenshao's review:
Critical fixes:
- Prevent silent data loss: only transform paste when all tokens are
valid paths. If any non-path token exists, preserve original content
(hadNonPathToken tracking)
- Fix O(n²) synchronous fs calls: pre-filter tokens with looksLikePath()
to skip non-path tokens before expensive fs.existsSync calls
- Add tests for paths with spaces and escapePath integration (6 new tests)
Suggestion fixes:
- Fix quoted path regex: require path-like prefix to avoid false matches
on English contractions (don't → /'([~/.][^']*)'/g)
- Flatten if/else in newline paste branch
- Add CRLF, shell mode, and null-return tests
- Escape commas in paths for parseAllAtCommands compatibility
* fix(cli): use escapePath to avoid CodeQL warning
Use escapePath() for whitespace escaping instead of manual regex to
avoid CodeQL's incomplete-string-escaping warning, then additionally
escape commas.
* fix(cli): add comma to SHELL_SPECIAL_CHARS to fix CodeQL warning
- Add comma to SHELL_SPECIAL_CHARS in core so escapePath handles it
- Simplify escapePathAndCommas to just call escapePath(path)
- This avoids CodeQL's incomplete-string-escaping warning
* fix(cli): address wenshao's remaining code review findings
- looksLikePath: add support for relative paths (./, ../, ~/) and dotfiles
- Greedy matching: reverse to longest-match-first for paths with spaces
- Add tests for relative paths, longest-match-first, and invalid paths
* fix(cli): address wenshao's remaining review suggestions
- Fix stale JSDoc: change 'shortest' to 'longest' match-first
- Remove overly broad includes('/') from looksLikePath
- Sync SHELL_SPECIAL_CHARS in vscode-ide-companion (add comma)
- Add tests for shell metacharacters (parentheses, brackets, semicolons)
- Add short-circuit when hadNonPathToken is set
- Inline escapePathAndCommas (now redundant with comma in SHELL_SPECIAL_CHARS)
* fix(cli): address wenshao's latest review suggestions
- Fix quotedPathRegex to support Windows drive-letter paths
- Fix looksLikePath to handle quoted Windows paths split by whitespace
- Allow bare filenames for single-token segments
- Add tests for Windows drive-letter and quoted Windows paths
- Add comma to paths.test.ts escapePath test
* fix(cli): address wenshao's latest JSDoc and test suggestions
- Fix looksLikePath JSDoc to include ../ and ..
- Fix tryExtractFilePaths JSDoc to reflect all shell-special chars
- Add test for bare filename (README.md) single-token segment
* fix(telemetry): attach interaction span to session root context
startInteractionSpan was the only startSpan call site missing the ctx
argument. OTel responded by minting a fresh random trace id, splitting
the interaction span away from its semantic children (llm_request /
tool / tool.execution), which DO inherit the sessionId-derived trace
id. The result: any session producing an interaction span ends up with
two unrelated trace ids — one one-span trace for the interaction, one
multi-span trace for everything else — and the hierarchy renders as
disconnected items in trace viewers.
Pin the interaction span to the session root context. Not via
resolveParentContext() — that prefers any active OTel span over the
session root, and interaction spans are turn boundaries that must
always anchor at the session root, regardless of whatever wrapping
span happens to be active in OTel context.
Also reset session-context module state inside
clearSessionTracingForTesting() so a test that sets a fake session
root cannot leak into the next test.
Adds regression coverage on interaction span parentContext, including
the case where an unrelated OTel span is active to confirm we bypass
resolveParentContext().
Fixes#4486
* refactor(telemetry): trim verbose comments around #4486 fix
Per CLAUDE.md guidance on comment density: keep only the WHY a future
maintainer cannot derive from the code or the issue link.
- session-tracing.ts: condense the 8-line interaction-span comment to
the single load-bearing point — resolveParentContext() is deliberately
bypassed and should not be "simplified" back into it.
- clearSessionTracingForTesting hygiene comment: one line stating the
cross-module reach, no restatement of the test-leak rationale.
- session-tracing.test.ts: drop the multi-line describe header and the
inline rationale in the second test; the describe / it names + the
production comment already convey intent. Move #4486 into the describe
name to match the existing `(#NNNN review)` convention used elsewhere
in this file.
No behavior change. All 72 tests still pass.
* test(telemetry): cover otelContext.active() fallback in startInteractionSpan
The two existing #4486 regression tests both call setSessionContext()
before invoking startInteractionSpan, so they never exercise the
nullish-coalescing fallback `getSessionContext() ?? otelContext.active()`.
This third case starts with no session context set (the beforeEach hook
already leaves getSessionContext() === undefined), an unrelated active
OTel span in the mock context, and asserts the interaction span attaches
to that active span rather than silently being created with no parent.
The fallback is essentially unreachable in production (sdk.ts seeds
session context during SDK init before any interaction can run), but it
exists as defense against startup edge cases / `/clear` / `/resume`
paths where session context could be transiently undefined while a stale
span lingers in the OTel async context. Without this test, a future
refactor could delete the `?? otelContext.active()` clause and silently
re-introduce the same class of bug #4486 fixed, in a different scenario.
Suggestion from wenshao on PR #4499.
* test(telemetry): tighten fallback test to match file convention
Three style nits caught by /simplify against the freshly-added test:
- Use `toMatchObject({ __activeSpan: fakeActive })` with a captured
reference instead of `toEqual(expect.objectContaining({ __activeSpan:
expect.anything() }))`. The latter would pass even if production code
returned `__activeSpan: undefined`; the former gives referential proof
that the actual active span propagated through. Matches the existing
three re-parent tests in this file (lines 395, 669, 741).
- Use `{ kind: 'fake-active-span' }` for the active span placeholder to
match the same convention.
- Collapse the 2-line setup comment to 1 line — the "no
setSessionContext call" directive is the load-bearing bit; the
"beforeEach left undefined" half was restating beforeEach.
No behavior change. 73 tests still pass.
* fix(vscode-ide-companion): exclude workspace packages from NOTICES.txt generation
Workspace-linked packages (link: true in package-lock.json) have no
version field, causing @undefined entries in NOTICES.txt. Skip them
during dependency collection since they are first-party code.
Regenerated NOTICES.txt on top of the express 5.2.1 lockfile update.
Closes#4446
* fix(vscode-ide-companion): resolve workspace and nested deps in NOTICES.txt generation
Rewrite collectDependencies to mirror Node.js module resolution:
- Walk up node_modules chain from each package's location (not just root)
- Follow workspace link resolved pointers to collect their third-party deps
- Pass resolved lockfile key to getDependencyLicense for exact path lookup
Previously @modelcontextprotocol/sdk and its transitive deps (zod-to-json-schema,
ajv@8, etc.) were missing because they are installed under the workspace's local
node_modules and were never hoisted to root. Also fixes version mismatch where
ajv@6.12.6 license was incorrectly used instead of ajv@8.17.1.
Total NOTICES entries: 80 → 102.
* fix(core): prevent auto-skill creation from overwriting existing skills (#4437)
The auto-skill review agent's `write_file` previously accepted any path
inside `.qwen/skills/` as long as the existing file carried
`source: auto-skill` in its frontmatter — so two consecutive reviews that
picked the same skill name would silently clobber each other, and any
user-edited auto-skill could be lost the same way.
`write_file` is reserved for CREATING new skills (the system prompt
already routes updates through `edit`), so the fix is to deny the
write whenever the target path already exists. Two small changes in
`skillReviewAgentPlanner.ts`:
1. Split the EDIT and WRITE_FILE cases in `evaluateScopedDecision`.
EDIT keeps its current `source: auto-skill` check; WRITE_FILE now
denies any pre-existing target via `fs.stat` (ENOENT → allow,
anything else → deny).
2. `buildTaskPrompt` enumerates existing skill directory names so the
agent picks a non-colliding name on the first attempt; the deny
above is the hard guard for when it doesn't.
The deny rule message tells the agent to retry with `<name>-2` (or use
`edit` for updates), so the model self-corrects the rare collision
without a code-level rename.
Fixes#4437
* fix(test): hoist non-null PermissionManager assertion into a helper so tsc --build is happy
The CI failure was tsc --build flagging `pm` as possibly null
(Config#getPermissionManager returns PermissionManager | null). Local
`tsc --noEmit` and eslint were silent because they don't run the
composite build path. Move the null check into a single
`scopedPm()` helper that throws if the contract breaks, and use it
everywhere — no asserter syntax in test bodies.
* refactor(core): tighten auto-skill review guard per round-1 review
Round-1 feedback on PR #4489 (#4437). Five low-cost adjustments to the
permission-layer guard + enumeration:
- WRITE_FILE now requires basename === SKILL.md, not just "under
.qwen/skills/". Prevents the agent from writing aux files (notes,
attachments) into the skills directory layout.
- buildTaskPrompt now takes a single projectRoot and derives skillsRoot
internally so the displayed root and the enumerated names always
share a source — removes the drift surface.
- listExistingSkillDirNames now treats `isSymbolicLink()` as a skill
candidate alongside `isDirectory()`, matching skill-load.ts and
skill-manager.ts. Symlinked skill dirs are a supported workflow;
without this they were absent from the "do NOT reuse" enumeration.
- Tests added for three new code paths from the v2 PR that lacked
coverage: write_file outside the skills root, write_file via a
symlink that escapes the root, and write_file when fs.stat fails
with a non-ENOENT error (EISDIR).
- WRITE_FILE branch comment rewritten — the prior text claimed `edit`
was the only path that could create a new file, but EDIT also allows
creation when the path doesn't exist yet; clarified the real invariant
(write_file cannot update; edit can both create and update).
Out of scope for this round (replied + declined):
- Atomic create-only write to close the stat-then-write race
(manager.ts already serializes intra-process; the cross-process
window is microseconds and the recommended fix re-opens the
generic-WriteFileTool change that PR #4440 was rejected for).
- EACCES/ELOOP/EIO-specific deny messages (observability gap; the
failure mode is essentially unreachable in practice).
* test(core): correct misleading WRITE_FILE catch-branch test (#4489 round 2)
Round-1 added a test named "denies write_file when fs.stat fails with a
non-ENOENT error (EISDIR)" — but fs.stat on a directory succeeds with
isDirectory:true and does NOT throw EISDIR (EISDIR comes from readFile/
writeFile). The test passes via path A (try { stat; return 'deny' }),
not the catch block it claims to exercise. wenshao flagged it in
round 2.
Rename to "denies write_file when the target path is a directory, not
a file" — honest about what it tests. Add a code comment explaining
why the non-ENOENT catch isn't separately tested: anything that would
throw from fs.stat (EACCES, ELOOP, ENAMETOOLONG, EIO) also throws from
assertRealProjectSkillPath one step earlier, covered by the symlink-
traversal test. Spying on fs.stat from ESM tests is blocked by Vitest;
chmod-based reproductions are non-portable to Windows CI. The deny
contract is structurally clear enough that the extra isolation isn't
worth the test infrastructure cost.
* feat(cli): dense inline panel for parallel agent fan-out
When a tool group is composed entirely of multiple `task_execution`
agent invocations (the shape produced by `/review`'s 9-agent fan-out),
`CompactToolGroupDisplay` collapses the whole group into one line —
`Agent × 9 / <last agent's name>` — even though the agents may run
for minutes each. Status, current activity, elapsed, and tokens are
all hidden, so the most informative span of a multi-agent run is
also the most opaque.
Route those groups to a new `InlineParallelAgentsDisplay` that
surfaces every agent on its own row:
╭─ Parallel agents · 9 · 3/9 done ───────────────────────╮
│ ○ Agent 1: Correctness ReadFile server.ts 3m 38s · 7.0k tok
│ ✔ Agent 2: Security 12s · 8.1k tok
│ ○ Agent 3: Code Quality ReadFile index.ts 3m 38s · 9.0k tok
│ ...
╰────────────────────────────────────────────────────────╯
Each row pulls activity / elapsed live from `BackgroundTaskRegistry`
on a 1s tick (same pattern LiveAgentPanel uses). When the registry
unregisters a finished foreground subagent, the row falls back to
`AgentResultDisplay.executionSummary` for elapsed + tokens so the
column doesn't blank out the moment an agent completes.
A new `InlineAgentClaimContext` lets the inline display claim the
agentIds it's rendering; `LiveAgentPanel` filters those out so the
same agent never appears in both surfaces. Claims are refcounted so
React's commit/cleanup interleave doesn't transiently drop a claim
while the same id is being re-claimed by a remount.
Routing conditions in `ToolGroupMessage`:
- Live phase only (`isPending`). Once the group commits to
`<Static>`, the expanded path with `SubagentScrollbackSummary`
owns the permanent record.
- Group has ≥2 calls and ONLY agent calls — mixed groups keep
the legacy renderer so sibling tools stay visible.
- No pending confirmation — those go through the normal renderer
so the keyboard-focus surface for approval stays intact.
Verified visually in tmux with `/review <pr-url> --comment` against
qwen-code PR 4472: all 9 agents render with live status / activity /
elapsed / tokens, transition glyphs ○→✔ in place, and the footer
LiveAgentPanel correctly suppresses the duplicate rows.
11 new tests + all 57 prior tests on touched files pass.
* refactor: address PR review feedback
- Split InlineAgentClaimContext into read + write contexts so
claimers (InlineParallelAgentsDisplay) don't re-render every
time some unrelated inline display claims its own ids. The
write API now has a stable identity for the lifetime of the
provider; only readers (LiveAgentPanel) react to claim-set
changes. Add a test that locks in the stability invariant so a
future memo on `[version]` is caught before it ships.
- Extract `isPureParallelAgentGroup` predicate in ToolGroupMessage
alongside the existing `isSubagentToolEntry` / `isTerminalSubagentTool`
helpers so the routing intent reads at the call site instead of
being spelled out inline.
- Document that `recentActivities` is mutated in place by the
registry; the rows useMemo's `now`-keyed re-read is what
surfaces the latest entry, so `activityLabel` must treat the
value as a tick-snapshot rather than closing over the live
array.
- Document the exhaustiveness of the `hasLiveAgent` status check
(`running | background`) against the upstream
`AgentResultDisplay.status` union so a future status addition
is caught.
- Document why `NAME_COL_WIDTH = 26` (fits /review's longest
agent label at full length on typical 100-col widths) instead
of leaving it as a magic number.
- Add an inline comment in gemini.tsx explaining why
InlineAgentClaimProvider sits inside BackgroundTaskViewProvider
(visible to both surfaces, no provider-boundary crossing).
* refactor: dense panel committed-only, live phase defers to LiveAgentPanel
- Dense panel renders only in committed phase, replacing verbose
per-agent ToolMessage expansion with one compact row per agent.
- Live phase: pure parallel agent groups return null so LiveAgentPanel
below the input is the sole live surface (fixes terminal agents
rendering as verbose ToolMessages above input during live phase).
- Remove InlineAgentClaimContext (no longer needed without live-phase
inline panel).
* refactor: dense panel both phases, LiveAgentPanel maxRows 12
- Show InlineParallelAgentsDisplay in both live and committed phases
with all agents (running + completed). LiveAgentPanel below the
composer also shows running agents during live phase (brief overlap
that resolves as agents complete and expire from the panel).
- Increase LiveAgentPanel DEFAULT_MAX_ROWS from 5 to 12 so all 9
/review agents are visible without truncation.
- Add totalAgentCount prop to InlineParallelAgentsDisplay for correct
header when rendering a subset of agents.
* feat(cli): keyboard navigation for LiveAgentPanel
- Add "main" as first entry in LiveAgentPanel, followed by running agents
- ↓ from Composer focuses LiveAgentPanel (selects "main")
- ↓/↑ navigates between entries with ▸ selection indicator
- Enter on agent opens BackgroundTasksDialog directly in detail mode
- Esc or ↑-at-top returns focus to Composer
- Printable chars auto-unfocus and type through to Composer
- Simplify header from "Active agents (N/N)" to "Active agents (N)"
- Add livePanelFocused + livePanelSelectedIndex state to
BackgroundTaskViewContext, keyboard handling stays in InputPrompt
* refactor: remove redundant Active agents header, keep only main
* fix: eslint warnings — missing deps in useCallback/useEffect
Add livePanelFocused, livePanelSelectedIndex, enterBgDetailFromPanel,
setBgSelectedIndex, bgEntries.length to InputPrompt handleInput deps.
Add isDetailMode to BackgroundTasksDialog effect deps. Remove unused
setBgPillFocused import.
* fix: address Critical review feedback
- Use bgAgentCount (agent-only) instead of bgEntries.length for
keyboard navigation bounds (was counting shells/monitors/dreams).
- Auto-clear livePanelFocused when no agent entries remain (prevents
stuck focus state when LiveAgentPanel returns null).
* fix: update AgentTabBar test for setLivePanelFocused change
* fix(core): consolidate AbortController handling to stop listener leaks in long sessions
Users hit `MaxListenersExceededWarning: 1509 abort listeners added to
[AbortSignal]` in long interactive sessions. The agent runtime nests
parent→child controllers (masterAbortController → per-message round →
per-API-call round → tool execution) and each layer registered its own
`addEventListener('abort', ...)` on the parent without `{once:true}` or
reverse cleanup, so listeners accumulated on long-lived parents across
hundreds of model turns.
Add `utils/abortController.ts` with three helpers:
- `createAbortController(maxListeners = 50)` — factory that pre-caps the
signal so the warning never fires on per-request signals.
- `createChildAbortController(parent)` — WeakRef-based parent→child
propagation with `{once:true}` on the parent listener AND a reverse-cleanup
listener on the child that detaches the parent listener when the child
aborts. This is the key mechanism — short-lived children stop accumulating
dead listeners on long-lived parents.
- `combineAbortSignals(signals, {timeoutMs})` — N-way combiner that replaces
the existing one-input `combinedAbortSignal.ts` (kept as a `@deprecated`
shim so `httpHookRunner.ts` doesn't churn).
Migrate every production `new AbortController()` in `packages/core/src` (24
sites) to the helper. Wrap `_runReasoningLoopInner` per-iteration body and
`AgentHeadless.execute` in `try/finally` so the round controller is aborted
(triggering reverse cleanup) even when the model stream or tool execution
throws. Add `{once:true}` to the manual abort listeners in `hookRunner`,
`functionHookRunner`, and `message-bus` that were missing it. Remove the
`raiseAbortListenerCap` band-aid from `openaiContentGenerator/pipeline.ts` —
no longer needed now that the per-round signal carries `maxListeners=50`.
Add `cli/utils/warningHandler.ts` as a belt-and-suspenders: hides
`MaxListenersExceededWarning.*AbortSignal` from end users in production
(any shape Node ≥20 emits), keeps it visible under `DEBUG`/`QWEN_DEBUG`/
`NODE_ENV=development`. Uses `process.on('warning', ...)` without
`removeAllListeners` so third-party warning subscribers stay intact.
Direct reproducer in `docs/verification/abort-controller-refactor/` proves
the old pattern accumulates 2000 listeners over 2000 rounds while the new
pattern stays at 0.
* fix(core): address PR #4366 review feedback
Four issues from the Copilot review:
1. combineAbortSignals — add a per-iteration `aborted` check inside the
for-loop so we short-circuit if an input signal flips aborted between
the initial scan and listener registration. In single-threaded JS this
can't actually interleave, but the defensive check makes correctness
obvious and protects against signals whose `aborted` getter has side
effects. New test exercises the path via a Proxy that flips after the
initial scan.
2. warningHandler docstring — was stale: said "AbortSignal / EventTarget"
while the regex was tightened to AbortSignal-only in the previous review.
3. README.md — replace personal absolute path with `$WT` placeholder so
the verification recipe is shareable.
4. README.md — replace the markdown table with per-scenario headed
sections. Prettier had interpreted an inline `ps -ef | grep sleep`
pipe character as a column separator, breaking the table rendering on
GitHub. Per-section format is also easier to scan and edit.
* test(core): fix abortController race-defense test to actually hit the loop check
The previous version set the Proxy's `aborted` to true before calling
combineAbortSignals, so the initial `find` scan caught it and we took the
fast path — not the per-iteration check the test was meant to validate.
Switch to an access counter so `aborted` is false on the first read (during
`find`) and true on subsequent reads (inside the loop). This forces the
loop to enter, then catches the flip via the defensive per-iteration check
before any listener is attached to the next input.
Verified the test fails if the per-iteration check is removed.
* fix(lint): include docs/**/*.mjs in the script ESLint block so the AbortController repro passes lint
CI Lint flagged 11 no-undef errors in
docs/verification/abort-controller-refactor/listener-accumulation-repro.mjs
(AbortController, console, process) because the project's flat config
only declared Node globals for ./scripts/**/*.mjs.
The reviewer's suggestion (`/* eslint-env node */`) doesn't work under
ESLint 9 flat config — env directives are deprecated there. The proper
fix is to extend the existing script-globals block to also cover the
verification repro script under docs/.
* fix(core,cli): address PR #4366 critical review findings
Two real bugs the reviewer caught and I confirmed locally:
1. warningHandler.ts didn't actually suppress anything. Adding a
`process.on('warning')` listener does NOT prevent Node's default
onWarning printer from writing to stderr — the default is just an
ordinary listener registered in `lib/internal/process/warning.js`.
My previous code therefore:
- failed to suppress targeted AbortSignal warnings (they still hit
stderr via the default printer)
- produced a SECOND copy of every non-suppressed warning (default
printer + my handler's own stderr.write)
The unit tests missed it because they synthesised a fake warning and
called `process.listeners('warning')` directly rather than going
through `process.emitWarning`.
Fix: snapshot the existing `'warning'` listeners (which include the
default printer and any third-party telemetry hooks) BEFORE replacing
them. Install ours as the sole listener. For non-suppressed warnings
fan out to the captured set so the default printer + telemetry still
fire; for suppressed warnings stop here. Tests now use
`process.emit('warning', ...)` to drive the real listener chain, plus
a spawned-child integration test that asserts the real stderr from
`process.emitWarning` is empty for AbortSignal warnings and still
contains DeprecationWarning text.
2. abortController.createChildAbortController kept a WeakRef to the
child controller. A natural usage pattern — pass `child.signal` into
an async API and drop the controller object — could let the
controller be GC'd while the signal is still in use, after which
`parent.abort()` would no longer propagate. Reproduced with
`node --expose-gc`.
Fix: hold the child strongly via the parent's listener closure. The
reverse-cleanup listener still removes the closure when child aborts
(closure releases child → GC-eligible), and the parent's `{once:true}`
listener self-removes when parent fires (same effect). Net listener
accounting on long-lived parents is unchanged; the only difference is
the controller now stays alive long enough for propagation to reach
downstream consumers that hold only the signal. Tests updated: drop
the old `--expose-gc`-dependent assertion that abandoned children
GC immediately (that was a property of the OLD contract); add a
signal-only-retention test that verifies propagation under the new
contract without needing GC at all.
Verified: 32 helper/warning tests pass (incl. spawned-child stderr
integration); 363 affected caller tests pass; typecheck + prettier +
eslint clean for the touched files.
* fix(core,cli): address PR #4366 review — fix combineAbortSignals orphan listeners + runtime DEBUG toggle
Two real bugs the reviewer caught:
1. combineAbortSignals registered its cleanup listener on
controller.signal AFTER the for-loop. Node does NOT fire 'abort'
listeners added to an already-aborted signal, so when the
per-iteration defensive check aborted the controller mid-loop, the
cleanup never ran — orphaning every input-signal listener registered
before the break, and leaving the (also-registered-after-the-break)
setTimeout uncleared.
Fix: skip timeout scheduling when controller.signal.aborted is
already true post-loop, and when it's true call cleanup()
synchronously instead of registering a doomed listener. Existing
test for the mid-iteration path now also asserts that the
pre-break input signal (a) has zero abort listeners — that's the
assertion that catches the orphan bug. New test for the
already-aborted-input + timeoutMs combination confirms the timer
isn't scheduled (would otherwise overwrite the abort reason).
2. warningHandler captured isDebugMode() in a closure at init time, so
toggling DEBUG / QWEN_DEBUG at runtime (e.g. via a /debug slash
command) didn't update suppression behavior. Moved the check inside
the handler — warnings are rare so the per-emit env-lookup cost is
negligible. New test asserts a mid-stream DEBUG=1 flip starts
forwarding suppressed warnings to the prior-listener chain.
* test(core): strengthen the timeout-guard test in combineAbortSignals to actually exercise the new !aborted check
Reviewer correctly pointed out that the previous version of this test
took the pre-loop fast path (since `a.abort('pre')` ran before
`combineAbortSignals`), so it never reached the in-loop guard at
abortController.ts:138.
Switched to the Proxy `aborted`-getter pattern from the sibling
mid-iteration test (so the loop genuinely re-checks `aborted` and
short-circuits inside the for-loop), and added a `setTimeout` spy that
asserts the timer was never scheduled — this is the only observable
difference from "scheduled then immediately cleared by synchronous
cleanup()", which is what the timer-advance assertion alone couldn't
distinguish.
Verified by mutation testing: removing the guard makes the new test
fail; restoring it makes it pass. Refs PR #4366.
* test(core): cover timeout-triggered cleanup of input-signal listeners in combineAbortSignals
Reviewer noted the timeout path only had an empty-input test, leaving
the leak-sensitive case uncovered: when timeoutMs fires with a
long-lived source signal in the input list, do the input-side
listeners get released? They do (the timeout callback aborts the
combined controller, which fires the auto-cleanup listener registered
on its signal, which calls the per-input removeEventListener), but
that path wasn't tested.
Adds a test that snapshots the source listener count before, asserts
it increased by 1 after combineAbortSignals returns, advances fake
timers past timeoutMs, and asserts the count returns to baseline.
Refs PR #4366.
* fix(test): use pathToFileURL for the warning-handler e2e import on Windows
CI failure on windows-latest:
AssertionError: expected '\r\nnode:internal/modules/run_main:12…'
to match /DeprecationWarning.*Plain deprecation/
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme in:
file, data, and node are supported by the default ESM loader. On
Windows, absolute paths must be valid file:// URLs. Received protocol 'd:'
The e2e test wrote a child script with an `import "<helperPath>"` where
helperPath was a raw Windows absolute path (`D:\a\qwen-code\...`). Node's
ESM loader parses that as a URL on Windows and rejects the `D:` "scheme".
Converted the helper path to a `file://` URL via `pathToFileURL`. macOS
test still passes; the Windows-specific schemes-must-be-URL behavior is
now honored. Refs PR #4366.
* fix(core,cli): address PR #4366 review batch — onAbort leak, migrate missed sites, tighten tests
Adopted 6 of the 7 review threads (skipping the debug-logging suggestion).
1. processFunctionCalls onAbort leak (CRITICAL): the new
`finally { roundAbortController.abort(); }` in _runReasoningLoopInner
would fire the `onAbort` handler in `processFunctionCalls` if
scheduler.schedule or batchDone threw (the explicit
removeEventListener at the old happy-path exit would be skipped),
emitting spurious "Tool call cancelled by user abort." TOOL_RESULT
events for every un-emitted callId — corrupting the transcript and
misleading the model on the next round. Fixed by wrapping schedule
+ batchDone in their own try/finally so removeEventListener always
runs before the outer finally's abort.
2. Migrate 3 new-from-main `new AbortController()` sites that this
PR's audit missed (they came in via the merge from main):
- goals/goalHook.ts (2 sites: judgeController, fallback signal) —
consistency
- hooks/promptHookRunner.ts (1 site: internalAbortController) —
real leak (manual addEventListener without {once:true} or
cleanup, exactly the pattern this PR exists to fix). Switched to
createChildAbortController + finally `internalAbortController.abort()`
for reverse cleanup on the success path.
3. Repro script (`listener-accumulation-repro.mjs`): inlined helper
diverged from production — used WeakRef on child, while production
was changed to strong-ref earlier in this PR. Updated the inlined
copy to match production exactly, with a comment noting the
intentional WeakRef-on-parent-only pattern.
4. warningHandler.ts: documented the snapshot-and-replace trade-offs
in the JSDoc (late-added listeners bypass our filter; late
`removeListener` calls have no effect on our fan-out). Tried the
re-snapshot-per-warning approach the reviewer suggested but it
doesn't work — `removeAllListeners('warning')` permanently removes
the snapshot from Node's tracking, so a `process.listeners('warning')`
filter at fan-out time always returns empty for prior listeners.
The current design is the right trade-off; documentation is the
correct fix.
5. abortController.test.ts: added three coverage gaps the reviewer
identified —
- createChildAbortController forwards custom maxListeners
- manual cleanup() before scheduled timeout fires cancels it
- timeoutMs <= 0 is treated as "no timeout"
6. Migrated `httpHookRunner.ts:202` (the lone caller of the deprecated
`createCombinedAbortSignal`) to `combineAbortSignals` directly,
then deleted `combinedAbortSignal.ts` + its test. All semantics
covered by `combineAbortSignals` tests in abortController.test.ts.
Refreshed `migration-completeness.txt` (now empty — clean grep).
Tests: 194 pass across abortController/warningHandler/agent-runtime/
followup/hooks/goal/promptHook suites. Typecheck + prettier clean.
* docs(verification): commit the headless-scenario scripts referenced by the PR body
The PR body's "End-to-end scenarios I drove locally" section points at
docs/verification/abort-controller-refactor/scripts/02-lite.sh and 06-headless-sigint.sh.
These are the actual reproducible commands behind the EXIT codes /
warning counts reported there — checking them in so anyone can replay
without copy-pasting from the PR description.
Refs PR #4366.
* docs(verification): sync automated-results with current state
Two doc fixes the reviewer flagged:
- migration-completeness.txt was a 0-byte file with a confusing
cross-reference. Populated with the actual grep command + its
"(no output)" result so the empty-output state is explicit.
- automated-results.md still referenced combinedAbortSignal.test.ts (8
tests, @deprecated shim) — both files were deleted in 94e8c5812 when
httpHookRunner.ts migrated to combineAbortSignals directly. Replaced
the line with a reference to httpHookRunner.test.ts. Also updated
the test counts to reflect current state (26 abortController, 13
warningHandler — both grew with the review cycle) and removed the
stale combinedAbortSignal.ts entry from the prettier-check command.
Refs PR #4366.
* test(core): pin two abort-cascade behaviors PR #4366 introduced
Adopting 2 of 3 new review threads (the third — automated-results.md
drift — was already fixed in 5aa7110e4).
1. packages/core/src/agents/arena/ArenaManager.test.ts: pin the
master→agent abort cascade introduced by switching per-agent
controllers to `createChildAbortController(this.masterAbortController)`.
New test spawns ≥2 agents, calls `manager.cancel()`, and asserts every
`agentState.abortController.signal.aborted === true`. Existing cancel
test only checked backend + status; if a future refactor re-introduced
independent controllers, the cascade would silently regress.
2. packages/core/src/followup/speculation.test.ts: cover the
`startSpeculation` abort wiring introduced when the manual
addEventListener + .finally removeEventListener pattern got replaced
by createChildAbortController + .finally abort(). Three tests:
- parent abort propagates to state.abortController (lifetime contract)
- parent-already-aborted fast path returns aborted state
- parent-signal listener count returns to baseline after the fire-and-
forget loop settles (reverse-cleanup proof)
Mocked `runWithForkedChatModel` and `OverlayFs` so the background
loop is a no-op — these tests only assert the synchronous wiring,
not the loop's content.
* fix(test): speculation.test.ts TS errors + sync verification doc counts
Two real CI blockers in the just-added speculation tests (TS2554 and
TS2339) plus stale doc counts the reviewer flagged.
1. saveCacheSafeParams takes 3 positional args (generationConfig,
history, model), not a single object. Compile error on every
platform. Fixed by switching to the correct shape; also moved
getEventListeners to a static `import` at the top of the file
(dynamic `await import('node:events')` exposes EventEmitter's
static method via the namespace type rather than as a direct
property, so destructuring fails type-check).
2. docs/verification/abort-controller-refactor/README.md still claimed
"18 + 1 GC" tests for abortController and "9" for warningHandler;
actual current counts are 26 and 13. Also dropped the stale
combinedAbortSignal reference and added a note about the new
ArenaManager cascade + startSpeculation wiring pin tests.
Refreshed smoke-boot.log against current built bin (still 0.15.11,
which is what package.json reports on this branch).
Refs PR #4366.
* refactor(core): narrow PR #4366 scope per yiliang's review — revert independent-controller migrations
Adopting @yiliang114's review feedback (#4366 review comment, 2026-05-22):
keep only the migrations that fix the real leak path (the agent-runtime
parent→child chain that accumulates listeners on a long-lived parent
signal in long sessions) and revert the consistency-only migrations on
independent short-lived controllers.
Issue #4423 confirms the user-visible bug is the nested-chain
accumulation — the reverted sites do not contribute to that bug.
Migrations KEPT:
- agents/runtime/agent-interactive.ts (master + per-message round)
- agents/runtime/agent-core.ts (per-iteration + wait + processFunctionCalls)
- agents/runtime/agent-headless.ts (external → execution)
- hooks/promptHookRunner.ts (real cleanup leak: addEventListener without
{once:true}, never removed)
- hooks/httpHookRunner.ts → combineAbortSignals direct (shim deleted)
- hookRunner.ts / functionHookRunner.ts / message-bus.ts: {once:true} only
- openaiContentGenerator/pipeline.ts band-aid removal (per-request signals
are children of the per-round controller, which carries maxListeners=50)
- warningHandler.ts belt-and-suspenders
Migrations REVERTED (independent short-lived controllers; restored to
`new AbortController()` + their original cleanup patterns):
- agents/arena/ArenaManager.ts (master + per-agent)
- agents/background-agent-resume.ts (3 sites)
- core/client.ts (recall — restored manual addEventListener + finally
removeEventListener pattern from main)
- followup/speculation.ts (restored parentAbortHandler + finally
removeEventListener)
- goals/goalHook.ts (judgeController + fallback signal)
- memory/manager.ts (dream controller)
- services/chatCompressionService.ts (fallback signal)
- services/chatRecordingService.ts (autoTitle controller)
- tools/agent/agent.ts (fg + bg subagent controllers — restored manual
onParentAbort + finally removeEventListener)
- tools/monitor.ts (entryAc)
- tools/shell.ts (promote + 3 entryAc)
- utils/fetch.ts (fetchWithTimeout)
Tests removed alongside the reverts:
- ArenaManager.test.ts "cancels cascades..." — the cascade itself was an
intentional behavioral improvement that's now reverted, so the
pin-test belongs with it
- speculation.test.ts "startSpeculation — abort-controller wiring" block
(3 tests) — they tested helper-wired behavior we reverted
Verification docs updated to reflect the narrower scope.
Net change: 19 raw `new AbortController()` remain (intentional, per
migration-completeness.txt rationale); previously was 0.
Refs PR #4366, issue #4423.
/context counted every registered deferred tool — MCP tools plus
low-frequency built-ins like web_fetch, monitor, cron_*, exit_plan_mode,
enter/exit_worktree, send_message, task_stop — even when ToolSearch had
never loaded them. The real API request (client.ts:506) only sends
revealed tools, so the displayed totals diverged from what's actually
in the prompt.
The previous `getFunctionDeclarations({ includeDeferred: true })` was
added alongside ToolSearch (#3589) to keep `displayBuiltinTools = total
- mcp` non-negative, but it aligned both sides to the "registry"
dimension instead of the "prompt" dimension. This change aligns both
sides to "prompt" (matching client.ts): the function-declaration call
drops the override, and the per-tool loop skips deferred-but-not-revealed
tools too — keeping the math consistent without overcounting.
On a default session that has just sent a single message, this reclaims
~8.2k tokens of false overhead (MCP 4.9k + deferred built-ins 3.3k) and
reattributes them to the messages category, where they actually live.
Closes#4508
Co-authored-by: Qwen-Coder <noreply@alibaba-inc.com>
* fix(extension): populate resources when marketplace points at whole folder
`collectResources` in the Claude→Qwen converter silently dropped every
file when a marketplace entry referenced the *whole* resource folder
(e.g. `commands: ["./commands/"]`) instead of individual sub-entries
(`skills: ["./skills/xlsx"]`).
The cause was a stale skip-branch: `convertClaudePluginPackage` deletes
`tmpDir/<destFolderName>` before calling `collectResources` (so it can
honor selective sub-entry lists), but `collectResources` still believed
the prior `copyDirectory` had already placed the files at the
destination and short-circuited. The freshly-`mkdir`'d folder was left
empty and the install reported success.
Fix:
- Directory branch: when `dirName === destFolderName`, flatten contents
into `destDir` (instead of nesting under `destDir/<dirName>/`); for
sub-entries (`./skills/xlsx`) keep nesting so `tmpDir/skills/xlsx/`
still works for anthropics/skills shape.
- File branch: drop the skip — always copy. `destFile =
destDir/<fileName>` is correct for both layouts.
Verified end-to-end against `microsoft/skills:deep-wiki` (13 commands,
10 skills, 3 agents now all install and surface in `extensions list`)
and against `anthropics/skills:document-skills` (4 sub-skills still
install correctly).
Fixes#4452
* docs(extension): correct stale JSDoc on collectResources
The JSDoc still claimed "If a resource is already in the destination
folder, it will be skipped" — true under the prior implementation but
stale after #4497's fix, which removed all skip logic so the function
copies unconditionally (the caller clears destDir beforehand).
Spotted by wenshao on #4497.
Bailian Token Plan now advertises the chat models documented by ModelStudio while keeping qwen3.6-plus as the first default option. The VS Code companion uses a dedicated Bailian Token Plan list instead of reusing the Coding Plan model set, so both auth surfaces stay aligned without changing credentials or endpoints.
Constraint: Token Plan uses BAILIAN_TOKEN_PLAN_API_KEY and the dedicated token-plan ModelStudio endpoint; this change does not alter either credential wiring or endpoint selection.
Rejected: Add image-generation models to modelProviders.openai | those models use a different workflow and should not appear as chat model choices.
Rejected: Reuse ALIBABA_SUBSCRIPTION_MODELS for Token Plan | Coding Plan and Token Plan now expose different model catalogs.
Confidence: high
Scope-risk: narrow
Directive: Keep qwen3.6-plus first unless intentionally changing the default model selected after Token Plan auth.
Tested: cd packages/core && npx vitest run src/providers/__tests__/presets/alibaba-token-plan.test.ts
Tested: cd packages/cli && npx vitest run src/ui/auth/useAuth.test.ts src/ui/hooks/useProviderUpdates.test.ts
Tested: cd packages/vscode-ide-companion && npx vitest run src/services/subscriptionPlanDefinitions.test.ts src/services/settingsWriter.test.ts
Tested: npm run typecheck
Tested: npm run build
Tested: Token Plan E2E with qwen3.6-flash returned token-plan-ok using BAILIAN_TOKEN_PLAN_API_KEY mapped from local TOKENS_PLAN_API_KEY
Not-tested: Full npm run preflight
* fix(cli): require whitespace before @ to trigger file completion
Input like `cici@192.168.0.160` was incorrectly triggering @ file
completion mode, causing the session to become unresponsive because
Enter was consumed by the suggestion handler instead of submitting.
Add a check that @ must be at position 0 or preceded by a space,
matching the existing `isAtCommand()` semantics used at submit time.
* test(cli): add regression tests for @ completion whitespace check
Add two test cases to prevent regression:
- cici@192.168.0.160 should not trigger AT completion
- user@example.com should not trigger AT completion
* fix(cli): use \s regex for @ whitespace check to match isAtCommand
Use /\s/.test() instead of === ' ' so the completion trigger matches
isAtCommand's /\s@/ pattern, covering tabs and other whitespace.
* feat(cli): headless runaway-protection guardrails (#4103)
Adds two opt-in run-level budgets and a startup safety warning for
non-interactive / CI / SDK runs. All defaults preserve existing
behavior; the budgets only fire when the user explicitly sets a limit.
Phase 1 — surface unsafe configs and fix doc drift
- New `--yolo`-without-sandbox stderr warning at startup of every
non-interactive run, emitted by `getHeadlessYoloSafetyWarning` in
`packages/cli/src/utils/headlessSafetyWarnings.ts`. Suppressible
via `QWEN_CODE_SUPPRESS_YOLO_WARNING=1` (strict `1`/`true` match so
`=0` / `=false` don't silence it). Strict env match also applied to
the `SANDBOX` check so values like `SANDBOX=0` don't accidentally
bypass the warning.
- Gated on `!config.isInteractive()` at the gemini.tsx call site so
TUI users aren't nagged.
- `docs/users/configuration/settings.md`: corrected
`model.skipLoopDetection` default (`true`, not `false`) and reworded
the `--yolo`/sandbox section — `--yolo` does NOT auto-enable a
sandbox; sandboxing must still be opted into explicitly.
Phase 2 — run-level budgets with distinct exit code
- `--max-wall-time` / `model.maxWallTimeSeconds`: wall-clock duration
for the whole run. Flag accepts `90` (s), `30s`, `5m`, `1h`,
`500ms`. Settings is plain seconds.
- `--max-tool-calls` / `model.maxToolCalls`: cumulative tool
executions (success + failure). Ticked BEFORE each `executeToolCall`
so a budget of N caps the run at exactly N executions.
- New `FatalBudgetExceededError` (exit code 55), distinct from
`FatalTurnLimitedError` (53) and `FatalCancellationError` (130) so
CI scripts can branch on the reason. JSON output mirrors the
`handleMaxTurnsExceededError` / `handleCancellationError` envelope
convention.
- Enforced via `RunBudgetEnforcer` in
`packages/cli/src/utils/runBudget.ts`, wired to the same
`AbortController` as SIGINT so existing cancellation plumbing
carries the abort. A `routeAbort` helper distinguishes budget vs.
SIGINT at the abort-check sites and at the outer catch.
Critical correctness fixes (informed by the #4105 review pass)
- Drain-loop fall-through: the inner drain-item `for await` previously
exited via `finalizeAssistantMessage(); return;`, swallowing a
budget abort that fires during the last drain item and surfacing
exit code 0. Now routes through `routeAbort` so exit 55 is
preserved.
- Settings symmetry: `maxWallTimeSeconds: 0` in settings.json is now
rejected (same as `--max-wall-time 0`); the enforcer treats `<=0`
as "no timer" so silent disable would be a foot-gun.
`validateMaxWallTimeSetting` also rejects `Infinity` / `NaN`.
- `setTimeout` overflow: both parser paths reject durations above
`Math.floor((2^31 - 1) / 1000)s` (~24.8 days). Node clamps
oversized delays to 1ms and fires the timer almost immediately;
fail loud at startup instead.
- First-fence-wins + SIGINT race: `markExceeded` no-ops if the
controller was already aborted by a third party, so a budget tick
arriving after user SIGINT doesn't misattribute the abort to exit
code 55.
- Outer catch re-routes mid-stream `AbortError`s through the budget
handler so users see "Run aborted: …" instead of raw "AbortError".
Tests
- `runBudget.test.ts` (32 tests): parser happy / reject paths,
setting validator, post-increment off-by-one, `maxToolCalls=0`
meaning "disallowed", `-1` meaning unlimited, wall-clock under
fake timers, `stop()` cancels pending timer, idempotent `start()`,
first-fence-wins, SIGINT-race protection.
- `headlessSafetyWarnings.test.ts` (7 tests): YOLO + sandbox / env
matrix; strict-truthy `SANDBOX` check; suppression env.
- Pre-existing suites: `nonInteractiveCli.test.ts` (46),
`gemini.test.tsx` (23), `config/config.test.ts` (220),
`core/utils/errors.test.ts` (12), `core/config/config.test.ts`
(172) all green after picking up the new config getters / CliArgs
fields.
Backward compatibility
- All budgets default to `-1` (unlimited); existing CLI invocations
behave identically.
- New stderr warning only fires in the narrow YOLO-no-sandbox case,
with an explicit suppress env.
- New exit code 55 is purely additive; no existing exit codes change
meaning.
* fix(cli): address audit findings for headless guardrails (#4103, #4502)
Round-1 audit (3 angles × line-by-line + removed-behavior + cross-file)
plus an open-ended design pass surfaced eight correctness issues. This
commit lands all of them; the larger ACP / serve-mode structural items
are documented for follow-up.
Correctness fixes
- headlessSafetyWarnings: `SANDBOX` env check reverted to plain truthy.
The sandbox transport sets `SANDBOX` to `sandbox-exec` (macOS
seatbelt) or the container name (`qwen-code-sandbox`), neither of
which matches `isTruthyEnv`. The PR's strict-`1`/`true` check was
emitting the "no sandbox" warning INSIDE real sandboxes. Match the
rest of the codebase (sandboxConfig.ts, gemini.tsx, Footer.tsx,
prompts.ts, …) which all treat any non-empty value as "sandboxed".
- nonInteractiveCli main-loop abort: add `finalizeAssistantMessage()`
before `routeAbort()`. The drain-item loop already had it (PR #4502
Critical bug #1); the main loop was asymmetric — stream-json
consumers would see an unterminated `message_start` when a budget /
SIGINT abort landed mid-stream.
- nonInteractiveCli drain-loop `routeAbort`: also flush
`flushQueuedNotificationsToSdk(localQueue)` and
`finalizeOneShotMonitors()` before exiting. The old `return`-and-
fall-through path went through the outer holdback loop, which did
this flushing; switching to `routeAbort()` skipped it, so
`task_started` envelopes lost their paired `task_notification`.
- nonInteractiveCli catch handler: emit `adapter.emitResult({...})`
BEFORE `handleBudgetExceededError`, with the budget message as
`errorMessage` when budget tripped. Previously the budget handler
`process.exit(55)`ed before the adapter could emit a terminal
`result` envelope, so STREAM_JSON consumers never saw a stream
terminator on budget exits and hung waiting for one.
- runBudget: new `validateMaxToolCalls` mirrors
`validateMaxWallTimeSetting`. yargs coerces non-numeric flag values
(`--max-tool-calls abc`) to `NaN`, and the enforcer's `>= 0` gate
treats `NaN` and negatives as "no limit", silently disabling the
budget. Reject `NaN`, `Infinity`, fractional, and negative-other-
than-`-1` values at both flag and settings layers. `0` remains
legal (`first tick aborts`), unlike wall-time where 0 is fatal.
- runBudget: new `MIN_WALL_TIME_SECONDS = 1` floor. Previously
`--max-wall-time 500ms` parsed cleanly and aborted on the next
event-loop tick before any model round-trip — almost certainly a
typo (`5m`?) and not a useful guardrail at any rate.
- nonInteractiveCli `tickToolCall`: exempt `ToolNames.STRUCTURED_OUTPUT`.
Under `--json-schema` this is the terminal "I'm done" contract tool,
not real work. Without the exemption a budget-edge completion is
aborted as a false positive (model used N tools then emitted
structured_output as call N+1 → exit 55 instead of success).
- commands/serve.ts: emit the YOLO-no-sandbox warning at daemon
startup when settings.json statically configures
`tools.approvalMode: 'yolo'` with no `tools.sandbox` /
`SANDBOX` env. The daemon can't use `getHeadlessYoloSafetyWarning`
(no Config yet — sessions get their own) so we re-derive the
predicate from settings. Per-session ACP override is documented as
out of scope.
Documentation
- `docs/users/features/headless.md`: new "Scope" subsection under
Run-level budgets explaining (a) `--max-tool-calls` counts top-level
dispatches only — subagent / `agent` tool inner calls are not
counted, (b) `structured_output` is exempt, (c) stream-json input
mode resets budgets per user message, (d) `qwen serve` / ACP
sessions do not currently consult budgets from settings.json.
Tests
- `runBudget.test.ts` grows from 32 → 41 tests: `validateMaxToolCalls`
(NaN / Infinity / negatives / fractional), `parseDurationSeconds`
sub-second rejection, `validateMaxWallTimeSetting` sub-second
rejection.
- `headlessSafetyWarnings.test.ts`: replaced the "still warns when
SANDBOX is 0/false/no" case (which encoded the strict-check bug) with
positive coverage for the real sandbox-set values
(`sandbox-exec`, `qwen-code-sandbox`).
All previously-green suites still green: cli/nonInteractiveCli (46),
cli/gemini.test (23), cli/config/config.test (220), core/utils/errors
(12), core/config/config.test (172). 337 tests across the touched suites.
Won't-fix (out of scope, documented or pre-existing)
- Unpaired `tool_use` in stream-json when a tool is aborted mid-execution
— pre-existing structural gap (SIGINT mid-tool has the same outcome);
PR amplifies it but doesn't introduce it.
- Narrow SIGINT-vs-budget-timer race — already mitigated by
`markExceeded`'s `signal.aborted` check.
- `tickToolCall` increments past abort (cosmetic; only affects the
`observed` value in the error envelope for a pathological caller).
* fix(cli): round-2 audit fixes for headless guardrails (#4103, #4502)
Round-2 audit (after round-1 commit 40ae6dd0f) surfaced two NEW
correctness issues introduced by the round-1 catch-handler restructure,
plus a handful of polish items from a parallel design pass.
Correctness fixes (new bugs from R1)
- nonInteractiveCli catch handler: wrap `adapter.emitResult` in
try/catch. R1 moved the emit BEFORE `handleBudgetExceededError` so
STREAM_JSON consumers see a terminal envelope first. But emitResult
eventually hits `stdout.write`, which throws on EPIPE /
ERR_STREAM_WRITE_AFTER_END when a piped consumer closes early
(`qwen -p ... | head -n 1` is the common CI case). Letting that
throw bubble out skipped both `handleBudgetExceededError` and
`handleError`, dropping the documented exit-code-55 contract
precisely when stdout was in trouble. Best-effort emit and continue
to the exit handler.
- nonInteractiveCli `structured_output` exemption: also require
`config.getJsonSchema?.() !== undefined`. Without that guard, an
MCP server registering an unrelated tool literally named
`structured_output` would silently bypass `--max-tool-calls`. Also
documents (in `headless.md` "Scope") the related caveat that failed
Ajv-validation retries skip the tick too, so a malformed-output
retry loop is NOT bounded by `--max-tool-calls` — combine with
`--max-session-turns` or `--max-wall-time`.
Polish
- runBudget `validateMaxToolCalls` upper bound: cap at 1_000_000.
`1e10` (typo for `1e1`) would otherwise parse cleanly, pass the
`>= 0` gate forever, and silently disable the budget — the exact
foot-gun `MAX_WALL_TIME_SECONDS` was built to prevent. Symmetry.
- runBudget `parseDurationSeconds` sub-second hint: only append the
"did you mean Ns?" suggestion when the input actually contained
`ms`. Bare `0.5` would otherwise produce a useless "did you mean
0.5s?" suggestion.
- nonInteractiveCli `routeAbort`: the `throw 'unreachable'` is only
hit if `handleBudgetExceededError` / `handleCancellationError` ever
becomes resumable (e.g. mocked `process.exit` in a test). Carry
the original exceeded.message into the thrown Error so the outer
catch's `errorMessage` field stays actionable instead of degrading
to a literal "unreachable" string.
- commands/serve.ts: compare `approvalMode` against `ApprovalMode.YOLO`
enum instead of the string literal `'yolo'`. If the enum value is
ever renamed, the startup warning stays in sync with the helper at
`headlessSafetyWarnings.ts` instead of silently going dead.
Documentation
- `headless.md` "Scope": clarify the `structured_output` exemption is
unconditional (including failed validations); add explicit note
that `--max-session-turns` does NOT exempt `structured_output`, so
size to `N+1` for `N` real-work turns under `--json-schema`.
- `headless.md` flag table: add `1.5h` to the accepted-forms hint for
`--max-wall-time` (the parser already accepts fractional units).
Tests
- `runBudget.test.ts`: new coverage for the `validateMaxToolCalls`
ceiling. Total 42 tests across `runBudget.test.ts` (was 41), all
green. cli/nonInteractiveCli, gemini.test, config/config all
unchanged and still green.
Won't-fix (documented above or out of scope)
- ACP per-session approval-mode escalation (mid-session flip to YOLO)
doesn't print the warning — daemon-level wiring; out of scope for
this PR.
- 1s wall-time floor vs higher (5–10s) — debatable, keeping 1s with
loud sub-second rejection; can raise later without semver impact.
- Integration test for the full budget-trip → catch → emitResult →
exit 55 path — requires a process-exit-mocking harness; tracked as
follow-up.
* docs: align headless guardrails examples with R1 sub-second floor
Round-3 audit caught two stale doc surfaces that R1's 1-second wall-time
floor (and R2's `1.5h` fractional-unit addition) didn't update:
- `docs/users/features/headless.md` budget table: replace stale `500ms`
example with `1.5h`, add explicit "minimum 1s — sub-second values are
rejected as typos" note.
- `docs/users/configuration/settings.md` `model.maxWallTimeSeconds` row:
same fix. Also extend `model.maxToolCalls` row with the structured_output
exemption note, the `0` semantic, and the 1,000,000 ceiling that R2
added.
A user copying the documented `--max-wall-time 500ms` example from either
surface would hit a startup error after R1.
Known follow-up (not addressed in this commit)
- No test exercises the R2 `isStructuredOutputExempt` predicate end-to-end.
Adding one needs the same process-exit-mocking harness called out in the
R2 commit as a separate follow-up.
* docs: align JSDoc / schema / CLI help with R1+R2 validation rules
Round-4 final-pass audit caught four schema/help-text/JSDoc surfaces
that drifted from the validators introduced in R1 (1s wall-time floor,
24-day ceiling) and R2 (1M tool-call ceiling, structured_output
exemption, `0` sentinel).
- `runBudget.ts` `parseDurationSeconds` JSDoc: replace stale claim
that `500ms` is accepted and "sub-second precision is preserved"
with the actual contract — `[MIN_WALL_TIME_SECONDS, MAX_WALL_TIME_SECONDS]`,
ms suffix only legal when value resolves to >= 1s. Adds `1.5h` to
the accepted-forms list.
- `settingsSchema.ts` `model.maxWallTimeSeconds` description: now
documents the 1s minimum and ~24-day ceiling.
- `settingsSchema.ts` `model.maxToolCalls` description: documents the
structured_output exemption, the `0` sentinel ("no tool calls
allowed"), and the 1,000,000 ceiling.
- `vscode-ide-companion/schemas/settings.schema.json`: mirrors both
schema descriptions above so the VS Code settings UI auto-completion
matches.
- `config.ts` yargs `--max-wall-time` description: documents the 1s
floor and the ~24-day max.
- `config.ts` yargs `--max-tool-calls` description: documents the
structured_output exemption, the `0` sentinel, and the 1M ceiling.
`qwen --help` is the most-read surface for these flags; matches the
prose docs in headless.md and settings.md.
No code changes — pure doc/help-text alignment.
---------
Co-authored-by: 克竟 <dingbingzhi.dbz@alibaba-inc.com>