Compare commits

...

51 Commits

Author SHA1 Message Date
易良
cea15a118b
fix(core,cli): replace full-history structuredClone with shallow/tail variants to prevent OOM on resume (#4644)
* 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.
2026-06-01 22:53:48 +08:00
JerryLee
68e4819d73
fix(cli): use session channel when closing ACP sessions (#4522)
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.
2026-06-01 16:23:42 +08:00
qqqys
788f215117
Improve hooks matcher display (#4545)
* feat(cli): improve hooks matcher display

* test(cli): cover hooks navigation levels
2026-06-01 16:18:10 +08:00
jinye
7448724d8a
fix(core): preserve uid in atomicWriteFile to avoid breaking shared-write files (#4431)
* 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.
2026-06-01 16:15:15 +08:00
Dragon
59c283670e
Hide internal docs from docs site (#4357) 2026-06-01 15:55:14 +08:00
顾盼
707f1bdb5f
fix(cli): persist /memory toggle state across dialog reopen (#4650)
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.
2026-06-01 11:29:02 +08:00
Yufeng He
1c48e4121b
fix(core): apply output language to side queries (#4636) 2026-05-31 18:03:05 +08:00
Yufeng He
a3bc42dc55
fix(core): harden context error text collection (#4632) 2026-05-31 18:02:39 +08:00
yao
d074ed8434
feat(cli): Add settings JSON corrupted warning dialog (#4560)
* 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>
2026-05-31 18:02:20 +08:00
Yufeng He
093545b71f
fix(cli): hide completed sticky todos (#4635)
* fix(cli): hide completed sticky todos

* fix(cli): remeasure sticky todos on status changes
2026-05-31 17:59:12 +08:00
Yufeng He
9dafd60d5d
fix(core): enforce adjacent tool results (#4622)
* fix(core): enforce adjacent tool results

* fix(core): handle orphan cleanup edge cases
2026-05-31 17:57:22 +08:00
Yufeng He
5743c2a05c
fix(acp): drop discontinued Qwen OAuth method (#4639) 2026-05-31 17:56:05 +08:00
Kagura
1014848234
fix(config): load home .env vars before settings ${VAR} resolution (#4466) (#4474)
* 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>
2026-05-31 15:03:46 +08:00
Yan Shen
54b6b204d2
fix(cli): stabilize statusline preset ordering (#4634)
* 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.
2026-05-31 14:44:22 +08:00
JerryLee
7a31c80f0e
fix(core): guard oversized resumed history sends (#4531)
* fix(core): guard oversized resumed history sends

* fix(core): preserve history on hard rescue stop

* fix(core): defer hard-rescue compression recording until guard passes

* test(core): clarify hard-rescue compression status

* test(core): cover hard rescue rollback invariants

* docs(core): clarify hard rescue rollback comment

* docs(core): document deferred compression recording
2026-05-31 14:27:35 +08:00
ZevGit
3fc1849892
feat(core): add memory pressure monitor (#4403)
* feat(core): add memory pressure monitor

* fix(core): address memory pressure review

* fix(core): isolate session memory cleanup
2026-05-31 13:57:52 +08:00
Dragon
60f6c5aba8
fix(core): surface Anthropic empty stream provider errors (#4540)
* 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
2026-05-31 13:15:55 +08:00
jinye
a1043ee3c9
fix(core): emit enable_thinking on DashScope when reasoning is disabled (#4505) 2026-05-31 12:32:52 +08:00
jinye
c699738f9a
fix(rewind): use notification type for mid-turn messages to fix count mismatch (#4580)
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
2026-05-29 21:32:11 +08:00
qwen-code-ci-bot
54fc50360c
chore(release): v0.17.0 [skip ci]
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-05-29 18:02:11 +08:00
顾盼
2a2f92aafd
fix(core,cli): label screenshot-triggered compaction accurately in the auto-compact notice (#4623)
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.
2026-05-29 17:35:57 +08:00
Yufeng He
a6f640a941
fix(core): use undici fetch for IDE proxy requests (#4607) 2026-05-29 17:16:17 +08:00
qwen-code-ci-bot
efba25f063
chore(release): v0.16.2 [skip ci]
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-05-29 17:10:07 +08:00
qqqys
96f08ebe22
Emit PermissionDenied hooks for AUTO classifier blocks (#4376)
* fix(core): emit permission denied hooks for auto blocks

* test(cli): cover permission denied hook display

* docs(core): clarify permission denied hook semantics

* fix(core): respect disabled hooks for permission denied

* test(core): cover auto permission denied hooks

* test(cli): cover acp permission denied hooks

* test(core): cover unavailable permission denial hooks

* test(core): cover auto-approved permission hooks
2026-05-29 17:09:07 +08:00
顾盼
365409366d
refactor(core)!: replace tail-preservation compaction with summary + restoration attachments (#4599)
* 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.
2026-05-29 16:20:13 +08:00
顾盼
39cc9b3e6f
feat(computer-use): zero-config built-in via open-computer-use MCP (#4590)
* 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.
2026-05-29 10:39:51 +08:00
易良
27b06290c9
fix(cli): track model-sent slash command history (#3826)
* 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
2026-05-29 10:27:17 +08:00
gwinthis
7bed56b9b6
feat(telemetry): foundation for skill-based RT optimization (P0+P1) (#4565)
* 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>
2026-05-29 02:17:40 +08:00
yuanyuanAli
7732554805
feat(channels): add Feishu (Lark) channel adapter (#4379)
* 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
2026-05-28 20:11:00 +08:00
jinye
34b7d472ef
fix(telemetry): improve LogToSpan bridge error info and TUI handling (#4482)
* 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)
2026-05-27 20:13:51 +08:00
Kagura
c425037998
fix(cli): surface startup warnings on stderr before TUI render (#4448) (#4461)
* 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>
2026-05-27 19:46:03 +08:00
顾盼
0c3cd0052f
feat(cli): default auto-dream/auto-skill to on and add /memory toggle (#4547)
* 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.
2026-05-27 17:25:06 +08:00
顾盼
a5ec1af301
fix(permissions): make command substitution ask, not deny (#4093) (#4386)
* 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
2026-05-27 17:06:48 +08:00
顾盼
5ad5301805
feat(worktree): Phase D — startup --worktree flag + symlinkDirectories + PR refs (#4381)
* 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.
2026-05-27 17:04:51 +08:00
DennisYu07
bc1bac506a
move new app prompt from system prompt to skills (#4567) 2026-05-27 14:57:30 +08:00
MikeWang0316tw
ce53283af4
fix(cli): auto-prepend @ when pasting or dropping multiple file paths (#4544)
* 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
2026-05-27 14:06:24 +08:00
jinye
77333a4d7c
fix(telemetry): attach interaction span to session root context (#4499)
* 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.
2026-05-27 11:33:29 +08:00
易良
92d533265c
fix(vscode-ide-companion): exclude workspace packages from NOTICES.txt generation (#4455)
* 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.
2026-05-27 11:24:38 +08:00
JerryLee
5aca042421
fix(models): refresh raw model-derived defaults (#4517) 2026-05-27 09:33:14 +08:00
JerryLee
641a1a7395
fix(cli): persist MCP server removals (#4535) 2026-05-26 17:57:41 +08:00
Dragon
ec850ea72b
fix(sdk): Include CLI chunks in SDK package (#4541) 2026-05-26 16:40:49 +08:00
顾盼
2b394f6614
fix(core): prevent auto-skill creation from overwriting existing skills (#4437) (#4489)
* 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.
2026-05-26 14:37:21 +08:00
Shaojin Wen
36e640d3a1
feat(cli): dense inline panel + keyboard navigation for parallel agent fan-out (#4477)
* 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
2026-05-26 14:23:24 +08:00
jinye
174e8de179
fix(core): stop AbortSignal listener leak in long sessions (MaxListenersExceededWarning) (#4366)
* 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.
2026-05-26 14:21:49 +08:00
Dragon
60dbbaaed4
fix(sdk): honor canUseTool timeout in CLI control requests (#4491) 2026-05-26 13:41:38 +08:00
pomelo
3cda1e26e7
fix(cli): align /context token breakdown with actual API request (#4512)
/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>
2026-05-26 11:23:01 +08:00
顾盼
1f6f888999
fix(extension): populate resources when Claude marketplace points at whole folder (#4497)
* 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.
2026-05-26 10:46:06 +08:00
YingchaoX
22cae555b4
fix(auth): align Token Plan model defaults with ModelStudio (#4478)
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
2026-05-26 10:23:29 +08:00
Shaojin Wen
e8b79d7721
fix(cli): require whitespace before @ to trigger file completion (#4487)
* 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.
2026-05-26 00:07:22 +08:00
Edenman
331f45e907
feat(cli): headless / non-interactive runaway-protection guardrails (#4103) (#4502)
* 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>
2026-05-26 00:06:26 +08:00
jinye
62ed44e1f3
feat(telemetry): client-side HTTP span + opt-in W3C traceparent propagation (#4384) (#4390)
* feat(telemetry): propagate W3C traceparent on outbound LLM requests

Part 1 of #4384 (sub-issue of #3731 P3 deeper observability).

Today qwen-code's only OTel instrumentation is `HttpInstrumentation`,
which only patches Node's `http`/`https` modules. The `openai` and
`@google/genai` SDKs use `globalThis.fetch` (undici), so outbound LLM
requests carry no `traceparent` header and trace context dies at the
qwen-code process boundary.

Adds `@opentelemetry/instrumentation-undici@0.14.0` (peer-compatible
with the installed `@opentelemetry/instrumentation@0.203.0`) and wires
it into `initializeTelemetry()` next to the existing
`HttpInstrumentation`. Default propagator (W3C tracecontext + baggage)
remains unchanged — no explicit `textMapPropagator` needed.

`ignoreRequestHook` skips OTLP exporter endpoints to avoid the
classic feedback loop (OTel SDK uses fetch to upload OTLP data; without
the hook each upload would create a span that gets uploaded, infinitely).
Configured `otlpEndpoint` / per-signal endpoints are stripped of trailing
slash and query string for robust prefix matching against undici's
`request.origin + request.path`.

Outbound LLM calls now also produce a client-side HTTP span (separating
network TTFB / transfer time from the existing `api.generateContent`
total-duration span).

Design doc: docs/design/telemetry-outbound-propagation-design.md
(Part A — traceparent; Part B — session id header — lands in a
follow-up PR per the design's split rationale.)

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* fix(telemetry): harden OTLP feedback-loop guard + slim lockfile diff

Review feedback on #4390:

1. CI was failing on npm ci because the lockfile was generated with npm 11
   locally (it sprinkles `peer: true` annotations npm 10 reads differently
   and rejects). Regenerated with npm 10 (matching CI's Node 22.x default),
   so the diff vs main is now 18 lines (the actual instrumentation-undici
   entry) instead of 105 lines of npm-version drift noise.

2. (Copilot inline at sdk.ts:330) `otlpUrlPrefixes` was derived from raw
   Config strings, so a settings.json `"otlpEndpoint": "\"http://...\""`
   (quoted) or trailing `#fragment` would silently miss the prefix match
   and reintroduce the feedback loop the hook exists to prevent. Replaced
   the regex-based suffix trim with a WHATWG URL parser:
   - strips ?query, #fragment, trailing slash
   - trims symmetric ASCII quotes a user may have placed in settings.json
   - falls back to safe suffix trimming if URL parsing fails (misconfigured
     endpoint still gets SOME protection)

3. (CodeQL inline) Replaced the `/\?.*$/` regex in ignoreRequestHook with
   `indexOf('?')`/`indexOf('#')` slicing for ReDoS hygiene. The regex was
   linear in practice but flagged as polynomial — using indexOf removes
   the ambiguity and is arguably simpler.

Added 3 tests in sdk.test.ts covering the new normalizations (#fragment
on incoming path, quoted endpoint, #fragment on configured endpoint).

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* feat(telemetry): propagate X-Qwen-Code-Session-Id on outbound LLM requests

Part 2 of #4384. Stacks on top of PR #4390 (traceparent via undici).

Adds a product-namespaced HTTP header X-Qwen-Code-Session-Id to every
outbound LLM request when telemetry is enabled, so server-side ingestion
can correlate observed requests with qwen-code session metric/log records.
Pattern matched from claude-code (X-Claude-Code-Session-Id, verified at
src/services/api/client.ts:108 in their open-source repo).

Critical design decision (design doc section 4.3): the OpenAI / Anthropic
providers use a per-request fetch wrapper rather than the SDK defaultHeaders
option, because content-generator SDK clients are constructed once and NOT
recreated on /clear-triggered session resets (Config.resetSession updates
this.sessionId but the contentGenerator keeps using the stale header value).
Reading config.getSessionId() from inside the wrapper at request time gives
the live value.

Gemini provider uses static httpOptions.headers — @google/genai HttpOptions
interface does not expose a fetch hook (only headers, baseUrl, apiVersion,
timeout, extraParams). This is a known limitation: after session reset,
Gemini X-Qwen-Code-Session-Id stays stale until the contentGenerator is
recreated. Documented in telemetry.md and the design doc section 8.6;
spans/logs continue to carry the live session id for trace/log correlation.
Lazy-invalidate fix is a follow-up sub-issue.

Header is omitted when telemetry is disabled OR when getSessionId returns
an empty string (some HTTP middleware rejects empty header values).

Integration sites:
- packages/core/src/core/openaiContentGenerator/provider/default.ts
  (base class — automatically covered by deepseek/minimax/mistral/
  modelscope/openrouter subclasses; openrouter calls super.buildHeaders)
- packages/core/src/core/openaiContentGenerator/provider/dashscope.ts
  (overrides buildClient — must be touched separately; QwenContentGenerator
  inherits via this provider)
- packages/core/src/core/anthropicContentGenerator/anthropicContentGenerator.ts
- packages/core/src/core/geminiContentGenerator/index.ts (factory function,
  not the GeminiContentGenerator class — no signature change)

End-to-end verification (local HTTP server in tmux):
  PASS: traceparent + X-Qwen-Code-Session-Id on every LLM request
  PASS: session id refreshes after simulated /clear (staleness regression
        guarded by llm-correlation-fetch.test.ts)
  PASS: OTLP upload traffic not traced (no feedback loop — PR A
        ignoreRequestHook working)

Robot generated with Qwen Code https://github.com/QwenLM/qwen-code

* fix(telemetry): R2 review fixes — critical correctness + tsc + boundary safety

Adopts 7 review findings from wenshao on #4390 (+ duplicates from now-closed
#4393). Critical bugs first, polish second.

CRITICAL:

1. tsc TS2322 — wrapper return type incompatible with Anthropic SDK Fetch.
   `typeof fetch` (Node WHATWG, 2 overloads) is not structurally assignable
   to Anthropic's narrower `Fetch = (input: RequestInfo, init?) => ...`,
   even though they're call-compatible at runtime. Make wrapper generic
   `<TFetch extends FetchLikeLoose>` so callers preserve their exact fetch
   signature; cast the Anthropic call site through `unknown` with a comment
   explaining why.

2. tsc TS2352 / TS2493 — `baseFetch.mock.calls[0]![1] as RequestInit` was
   out-of-bounds when wrapped was called with no init arg. Replaced with a
   `makeFetchMock()` helper returning typed accessors.

3. normalizeOtlpPrefix catch fallback was DANGEROUS — a config of `"http"`
   produced prefix `"http"` which `startsWith`-matched every outbound HTTP
   request → silently disabled ALL instrumentation (no client spans, no
   correlation header — defeats the entire feature). Fixed: catch returns
   undefined + diag.warn. Misconfigured endpoint loses its feedback-loop
   guard (acceptable) instead of disabling all guards (catastrophic).

4. `url.startsWith(prefix)` matching was NOT boundary-safe — port collision
   (`:4318` matches `:43180`), hostname suffix collision (`otlp.example.com`
   matches `otlp.example.com.evil.net`), path-segment collision (`/v1`
   matches `/v1foo/x`). Replaced with origin-equality + path-prefix +
   boundary-char check (next char must be `/`, `?`, `#`, or end-of-string).

5. HttpInstrumentation also lacked the OTLP feedback-loop guard. The OTLP
   HTTP exporter (`@opentelemetry/exporter-trace-otlp-http`) uses node:http
   (patched by HttpInstrumentation, NOT undici). Without this, every OTLP
   upload batch creates a parasitic client span → feedback loop. Added
   `ignoreOutgoingRequestHook` that reuses the same `matchesOtlpPrefix` /
   `stripPathSuffix` helpers as the undici instrumentation.

SAFETY:

6. Request input + undefined init dropped the Request's own headers
   (Authorization etc.) because `new Headers(undefined)` → `{...init, headers}`
   replaced them with just our session header. Fix: when input is a Request
   and init.headers is unset, seed from input.headers before adding ours.

7. Wrapped fetch had no try/catch — a throwing Config getter or Headers
   constructor would propagate as TypeError and break the LLM request path.
   Wrapped header construction in try/catch; on failure, fall through to
   baseFetch with original init (no header) + diag.warn. Telemetry must
   never break the model call.

COVERAGE:

- 3 new sdk.test.ts boundary tests (port/host/path)
- 1 new sdk.test.ts normalizeOtlpPrefix catch-branch coverage
- 1 new sdk.test.ts HttpInstrumentation OTLP guard test
- 1 new sdk.test.ts proxy-mode wrapped-fetch test (default.test.ts)
- 1 new anthropic test asserting wrapped fetch installed on Anthropic SDK
- 2 new llm-correlation-fetch.test.ts (Request-headers preservation + try/catch fall-through)

All 668 tests pass (1 pre-existing Anthropic User-Agent failure on main is
unrelated). tsc clean.

Declined: #10 DRY-refactor of baseFetch extraction across 3 sites — the
duplication was pre-existing (default/dashscope buildClient was already
near-identical), refactoring is a separate cleanup PR not gated by this
feature. Will reply on the thread.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* chore(deps): allow patch updates for @opentelemetry/instrumentation-undici

Switch from exact pin `0.14.0` to `^0.14.0` for consistency with the rest
of the `@opentelemetry/*` deps in this block (all carated).

For 0.x semver, npm treats `^0.14.0` as `>=0.14.0 <0.15.0`, so patch
updates within the 0.14.x line — which are tied to the same
`@opentelemetry/instrumentation@0.203.x` peer — flow in via `npm update`
without requiring a manual package.json edit. A bump across the 0.x
minor (e.g. 0.15.x) would shift the instrumentation peer compatibility
and still requires explicit attention, which the caret correctly blocks.

Per review feedback on #4390 (wenshao).

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* test(telemetry): stub getTelemetryEnabled + getSessionId in Gemini factory tests

The X-Qwen-Code-Session-Id commit added a `staticCorrelationHeaders(gcConfig)`
call inside the Gemini content generator factory. That helper reads
`gcConfig.getTelemetryEnabled()` and `gcConfig.getSessionId()` per request.

Both pre-existing Gemini tests in `contentGenerator.test.ts` build a minimal
partial Config stub via `as unknown as Config` and only stub the methods the
factory used to need. The new call path now hits the unstubbed methods at
runtime, surfacing as `TypeError: config.getTelemetryEnabled is not a function`
on all three CI platforms.

Add the two missing stubs to both test cases. The Gemini factory continues
to ignore the values when telemetry is off — these stubs only have to exist,
not return anything in particular.

Local check ran the full test suite for the four directories `/loop` covers
plus `src/core/contentGenerator.test.ts` itself; all green. Also re-ran the
other test files that build partial Config mocks via the same idiom
(`client.test.ts`, `config.test.ts`, `nextSpeakerChecker.test.ts`,
`content-generator-config.test.ts`) — none exercise the new code path.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* fix(telemetry): R3 review fixes — port + protocol + quote + safety

Four issues found by wenshao reviewing the R2 boundary-safety pass on PR
#4390. All four close gaps where the OTLP feedback-loop guard or the
correlation-header path could fail silently.

1. **Port normalization mismatch** (sdk.ts ignoreOutgoingRequestHook):
   `normalizeOtlpPrefix` builds prefixes via `URL.origin`, which strips
   default ports (`:80` for http, `:443` for https). The hook reconstructed
   request origin manually as `${proto}://${host}${portPart}`, keeping the
   port. Result: prefix `http://collector` (no explicit port) didn't match
   a request to `http://collector:80/v1/traces` because their `.origin`
   differed → guard bypassed → feedback loop. Now the reconstructed origin
   is also routed through `URL` so both sides apply the same default-port
   stripping.

2. **HTTPS proto silent fallback** (sdk.ts ignoreOutgoingRequestHook):
   The `(req.protocol && ...) || 'http'` fallback would silently mis-bucket
   HTTPS requests as HTTP when `req.protocol` was unset, so HTTPS OTLP
   endpoints couldn't match their prefix. Changed to fail open: when proto
   can't be determined, return false (request gets instrumented). Worst
   case is a parasitic client span — observable, recoverable — versus the
   previous unbounded silent feedback loop. Picked fail-open over the bot's
   port-based heuristic because non-standard HTTPS ports break the
   heuristic but not fail-open.

3. **Quote-stripping divergence** (sdk.ts normalizeOtlpPrefix):
   `parseOtlpEndpoint` (line 109) uses `/^["']|["']$/g` which strips
   asymmetric leading/trailing quotes; `normalizeOtlpPrefix` previously
   only stripped symmetric pairs. A settings.json typo like `"value'` would
   let the exporter connect (parseOtlpEndpoint trims) but leave the guard
   returning `undefined` (normalizeOtlpPrefix rejected) → parasitic loop.
   Aligned `normalizeOtlpPrefix` to the same lenient regex.

4. **`staticCorrelationHeaders` missing try/catch** (llm-correlation-fetch.ts):
   `wrapFetchWithCorrelation` already catches all internal exceptions and
   falls through to baseFetch — same "telemetry must never break LLM path"
   contract was missing on the static-headers helper. A throw here would
   propagate up to the Gemini content-generator factory and crash
   content-generator init for the whole session. Wrapped the body in
   try/catch with `diag.warn` fall-through to `{}`.

Tests: added 4 regression tests covering each scenario:
- default-port HTTP request matched against portless prefix (1)
- hook returns false when req.protocol missing on https endpoint (2)
- asymmetric-quoted endpoint normalizes for guard parity (3)
- staticCorrelationHeaders returns {} when config getter throws (4)

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* docs(telemetry): fix misleading "BOTH" wording in wrapFetchWithCorrelation

The comment described the header-seeding logic as merging "BOTH the
init.headers AND the Request's own headers", but the two branches are
mutually exclusive — `new Headers(init?.headers)` runs unconditionally
(empty Headers when init.headers is undefined), and the Request-headers
copy only runs when init.headers is undefined. So in practice it's
either-or, not BOTH.

Reworded to match the actual logic per #4390 review feedback (wenshao).
Behavior unchanged.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* fix(telemetry): strip port from req.host fallback + document undici scope

Two issues found by wenshao reviewing the R3 boundary-safety fixes on PR
#4390.

1. **`req.host` may already include `:port`** (sdk.ts ignoreOutgoingRequestHook):
   When `req.hostname` is absent and `req.host` is the fallback, the value
   may already be `"collector:4318"`. Naively appending `:${req.port}`
   produced `"http://collector:4318:4318"` → `new URL()` rejects → catch
   returns false → silent guard bypass for that request. Currently
   unreachable because `@opentelemetry/otlp-exporter-base` always sets
   `hostname` from WHATWG URL parsing, but the fallback exists in the
   code and must be correct — a future OTLP transport that emits `host`
   without `hostname` would silently trigger the feedback loop. Strip the
   port when falling back; bracketed IPv6 literals like `"[::1]:443"`
   keep their bracketed host intact.

2. **Undici scope honesty** (telemetry.md):
   Previous docs framed the propagation as "outbound LLM requests", but
   `UndiciInstrumentation` actually patches `globalThis.fetch` for the
   whole process — `WebFetch`, MCP clients, IDE extension calls all get
   spans + `traceparent` injection too. Added a "Scope: all fetch() calls,
   not just LLM" subsection covering: (a) trace ID leakage to third-party
   URLs (the user-supplied destinations of `WebFetch` see our trace ID;
   not secret per W3C but worth knowing); (b) non-LLM span volume
   inflating OTLP batches with a workaround tip. Per-destination scoping
   toggle deferred as a follow-up — out of scope for this PR.

Added regression test for the host:port-fallback path. Test exercises
the previously broken combination (hostname absent, host carries port)
through the existing test harness.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* feat(telemetry): scope X-Qwen-Code-Session-Id to first-party hosts by default

Address LaZzyMan's REQUEST_CHANGES review of PR #4390.

The original design injected `X-Qwen-Code-Session-Id` on every outbound
LLM request gated only by `telemetry.enabled`. Review caught that this
broadcasts a stable cross-request client identifier to every configured
third-party provider (OpenAI, Anthropic, OpenRouter, MiniMax, ModelScope,
Mistral, vanilla Gemini, ...), which the claude-code precedent does NOT
justify — claude-code is a first-party Anthropic→Anthropic flow; qwen-code
is an open-source CLI connecting to many providers.

Fix: add a host allowlist with a deliberately narrow default. The header
is now only attached to destinations whose hostname matches:

  dashscope.aliyuncs.com
  dashscope-intl.aliyuncs.com
  *.dashscope.aliyuncs.com
  *.dashscope-intl.aliyuncs.com
  *.alibaba-inc.com
  *.aliyun-inc.com

This is exactly the set where the LLM provider, the upstream telemetry
backend (ARMS Tracing), and qwen-code itself are the same legal entity —
mirroring the first-party claude-code pattern and preserving the real
product value (server-side trace stitching against DashScope) without
exposing the session id to third parties.

Operators with broader correlation requirements override via:

  "telemetry": {
    "sessionIdHeaderHosts": ["*"]                          // restore broadcast
    "sessionIdHeaderHosts": []                              // fully disable
    "sessionIdHeaderHosts": ["api.example.com", "*.foo"]    // custom allowlist
  }

Implementation:

- NEW `telemetry/trusted-llm-hosts.ts`: `DEFAULT_SESSION_ID_HEADER_HOSTS`
  + `matchesTrustedHost(hostname, patterns)` + `extractRequestHost(input)`.
  Pattern syntax is intentionally tiny (bare hostname OR `*.suffix`,
  dot-anchored to reject `evil-alibaba-inc.com` style attacks). Unit-tested
  in dedicated test file including TLD/sub-domain attack vectors.

- `wrapFetchWithCorrelation` (openai + anthropic providers): resolves the
  allowlist at wrap time (Config snapshot), inspects each request's
  destination URL inside `correlationFetch`, falls through to baseFetch
  for non-trusted destinations. Wildcard escape hatch via `["*"]`.

- `staticCorrelationHeaders` (Gemini factory): now takes an optional
  `destinationUrl` and applies the same host gate. The Gemini SDK default
  endpoint `generativelanguage.googleapis.com` is NOT on the default
  allowlist, so vanilla Gemini calls receive no header — matching the
  "first-party only" scope. Operators who put the Gemini SDK on a
  DashScope-compatible endpoint via `baseUrl` get the header naturally.

- `Config.getTelemetrySessionIdHeaderHosts()` getter +
  `TelemetrySettings.sessionIdHeaderHosts` interface field + JSON schema
  entry in `settingsSchema.ts`. Wired through `resolveTelemetrySettings`.

- Defensive optional-chaining + try/catch on the Config getter call at
  wrap time so partial test mocks (or pre-getter Config implementations)
  fall back to the default allowlist rather than crashing buildClient.

Tests: 12 new cases covering host match/skip on default allowlist,
sub-domain handling, TLD-suffix attack rejection, `["*"]` broadcast
override, `[]` full-disable, custom operator allowlist, unparseable
destination (fail closed), and the three Gemini factory paths
(googleapis.com default → omit; DashScope `baseUrl` → inject; custom
allowlist → inject).

Docs updated in `docs/developers/development/telemetry.md` Session
correlation header section, including override examples and the new
Gemini host-gate semantics.

Closes the LaZzyMan REQUEST_CHANGES blocker. The cross-vendor
fingerprint-broadcast failure mode is now opt-in rather than default,
restoring the first-party-only semantics that make the claude-code
precedent applicable.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* fix(telemetry): R5 review fixups — Vertex destination + ["*"] trim + docs

Self-review pass on commit 1c8528a56 (host-scoped session-id header):

1. **Vertex AI destination guessing**
   (geminiContentGenerator/index.ts)
   `@google/genai` routes to `{region}-aiplatform.googleapis.com` (not
   `generativelanguage.googleapis.com`) when `vertexai: true` and no
   `baseUrl`. The previous "guess generativelanguage" default would have
   mis-bucketed Vertex traffic under any operator-supplied allowlist that
   covered the public Gemini endpoint but not the Vertex one. Today
   invisible (both off the default allowlist), but a latent gotcha for
   operators tuning `telemetry.sessionIdHeaderHosts`.
   Fix: pass `undefined` when `config.baseUrl` is unset (fail-closed —
   no header). Operators who want correlation against Google endpoints
   must set `baseUrl` explicitly, which is also the SDK's input for
   destination resolution.

2. **`["*"]` broadcast escape hatch tolerates whitespace**
   (llm-correlation-fetch.ts)
   `[" * "]` (a settings.json hand-edit with a stray space) previously
   silently fell back to "no host matches" — the opposite of operator
   intent. Now `.trim()` before comparing, so common whitespace mistakes
   still trigger broadcast.

3. **Doc note on wrap-time allowlist snapshot**
   (llm-correlation-fetch.ts JSDoc)
   The session id is read live per-request, but `trustedHosts` is
   snapshotted once at `wrapFetchWithCorrelation` call time. Spell this
   out in the JSDoc so a future maintainer doesn't read the live
   `getSessionId()` and assume the allowlist is the same shape.

4. **Defensive test coverage**
   (trusted-llm-hosts.test.ts, llm-correlation-fetch.test.ts)
   Added: extractRequestHost with explicit port / userinfo / query /
   fragment / IPv6 bracket form. Whitespace `[" * "]` broadcast test.
   IPv6 case documents the "bracketed → never matches" behavior is
   intentional fail-closed for the named-host allowlist scope.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* chore: regenerate settings.schema.json for sessionIdHeaderHosts

Lint check `Check settings schema is up-to-date` failed because the
checked-in `packages/vscode-ide-companion/schemas/settings.schema.json`
wasn't regenerated after adding `telemetry.sessionIdHeaderHosts` to
`settingsSchema.ts` in commit 1c8528a56. Regenerated via
`npm run generate:settings-schema`.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* docs(design): update telemetry-outbound-propagation design for R3 host-allowlist scoping

Adds a "修订历史" header table at the top and a new §11 "R3 修订 —
Host-Allowlist Scoping for X-Qwen-Code-Session-Id" capturing what changed
after LaZzyMan's REQUEST_CHANGES review, why, and how. Inline pointers
added at §3.1, §3.2, §4.3, §4.4, §9 (claude-code comparison table) to
point readers at §11 — original prose preserved as a record of the
decision path rather than rewritten in place.

Concretely §11 covers:
- The three-step LazzyMan critique and why R1's "broadcast to all
  providers" was structurally wrong for an open-source multi-provider CLI
- The default allowlist (`DEFAULT_SESSION_ID_HEADER_HOSTS`) and its
  semantic alignment with the DashScope provider detector
- Pattern grammar (bare hostname / `*.suffix` dot-anchored), the
  TLD-suffix attack vectors it rejects, why no regex / port-aware globbing
- `wrapFetchWithCorrelation` host gate, wrap-time vs request-time
  semantics, `[" * "]` whitespace tolerance
- `staticCorrelationHeaders` `destinationUrl` parameter, Gemini factory's
  fail-closed treatment of unset `baseUrl` (avoids the Vertex
  vs `generativelanguage.googleapis.com` ambiguity)
- All R3 file changes mapped to the original §5 file-change list
- Mapping of LazzyMan's three concerns to R3's responses
- §10 future-work additions: `traceparent` per-destination toggle,
  `X-Qwen-Code-Request-Id`, IPv6 allowlist syntax

No code changes; documentation only.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* fix(telemetry): defensive allowlist normalization + positive proxy test

Three issues found by wenshao reviewing the R3 host-allowlist scoping.

1. **[Critical] `broadcastAll` outside safety try/catch**
   (llm-correlation-fetch.ts wrapFetchWithCorrelation)
   The try/catch only fires when `getTelemetrySessionIdHeaderHosts()`
   throws. If it returns a malformed value — a bare string (settings.json
   typo `"sessionIdHeaderHosts": "host"` instead of `["host"]`), an array
   containing `null`/`undefined`/number entries, or whitespace-padded
   entries — `.some((p) => p.trim() === '*')` throws TypeError at
   buildClient time, bricking the LLM session before the first prompt.
   `staticCorrelationHeaders` already handled this via its end-to-end
   try/catch but the sister helper diverged. Settings loader does no
   runtime schema validation so this is reachable via a single typo.

   Fix: normalize the allowlist at wrap time:
     1. catch a throwing getter (existing)
     2. reject non-array → default allowlist (NEW — bare string typo)
     3. filter out non-string elements (NEW — [null, ...] typo)
     4. trim every surviving entry uniformly (NEW — see #2 below)
   Then `trustedHosts.includes('*')` instead of `.some((p) => p.trim() === '*')`,
   since patterns are already pre-trimmed.

2. **Trim asymmetry between `*` detection and host-pattern match**
   (llm-correlation-fetch.ts)
   `[" * "]` was tolerated (trimmed before `===` compare) but
   `[" dashscope.aliyuncs.com "]` silently never matched. The
   normalization above fixes this by trimming uniformly upstream.

3. **Proxy fetch test: only negative assertions**
   (openaiContentGenerator/provider/default.test.ts)
   The test asserted `callArg.fetch !== proxyFetch` and `!== globalThis.fetch`
   but both passed for ANY wrapper, including a buggy one that
   accidentally wraps globalThis.fetch instead of proxyFetch. Added a
   positive assertion: call the wrapped fetch and verify proxyFetch was
   the delegation target.

Tests: 4 new cases — whitespace-padded host pattern, bare-string
malformed config (both wrapper and static), null/number-containing
array malformed config (both wrapper and static), positive proxy fetch
delegation. All pass; pre-existing Anthropic User-Agent failure
unrelated.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* refactor(telemetry): split outbound correlation out of telemetry scope (R4)

Address LaZzyMan round-8 follow-up review on PR #4390: even though R3's
host allowlist made the default behavior safe, the meta-architectural
concern remains: telemetry's namespace and consent flow shouldn't quietly
extend to wire-level behavior aimed at third-party LLM provider request
streams. The recipient sets differ; the consent decisions differ; they
deserve separate namespaces, separate threat models, separate PRs.

This commit (called R4 in the design doc) collapses the PR scope so it
lands ONLY telemetry observability work:

REMOVED from this PR:
  - packages/core/src/telemetry/llm-correlation-fetch.ts(.test.ts)
  - packages/core/src/telemetry/trusted-llm-hosts.ts(.test.ts)
  - telemetry.sessionIdHeaderHosts setting + Config getter +
    resolveTelemetrySettings wiring + settingsSchema entry
  - wrapFetchWithCorrelation usage from four provider construction
    points (default.ts, dashscope.ts, anthropicContentGenerator.ts,
    geminiContentGenerator/index.ts)
  - All session-id provider tests across the four providers + the
    contentGenerator.test.ts mock stub
  - "Session correlation header" section in telemetry.md

ADDED:
  - OutboundCorrelationSettings interface in packages/core/src/config/config.ts,
    standalone top-level namespace separate from TelemetrySettings —
    SECURITY-RELEVANT label, all defaults off
  - Config.getOutboundCorrelationPropagateTraceContext() getter
  - outboundCorrelation top-level entry in settingsSchema.ts with
    propagateTraceContext: { default: false } and explicit
    SECURITY-RELEVANT framing in the description
  - CLI config-load pipeline passes settings.outboundCorrelation into
    ConfigParameters
  - NOOP_PROPAGATOR (TextMapPropagator no-op) in sdk.ts, conditionally
    installed on NodeSDK when propagateTraceContext is false (default).
    When true, omits textMapPropagator from NodeSDK options so the SDK
    keeps its default W3C composite propagator
  - 2 new sdk.test.ts cases covering the propagator gate behavior

UNCHANGED:
  - UndiciInstrumentation registration + OTLP feedback-loop guard +
    HttpInstrumentation OTLP guard from R2/R3 stay intact — they are
    pure telemetry (client HTTP spans into the operator's own OTLP
    collector), no wire-level data egress
  - Documentation rewrites telemetry.md to split "client-side HTTP
    span on outbound fetch" (telemetry) from a new "Outbound
    correlation (SECURITY-RELEVANT)" top-level section
  - design doc gets R4 revision row + new §12 "R4 Scope Conflation
    Split" capturing the rationale and follow-up PR outline

The session-id apparatus (R3 code) lives in git history at commits
1c8528a56 / cb162e716 / 7a1b4f8d0 / 40e1efc1f / 106598ca2; the
follow-up PR can cherry-pick or restore those files under the new
outboundCorrelation.* namespace as LazzyMan suggested.

Vscode-ide-companion settings.schema.json regenerated.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* docs(telemetry): disclose telemetry.enabled dependency on propagateTraceContext

Self-review pass on R4 commit 9bdd3bd6f flagged one footgun: both
`docs/developers/development/telemetry.md` and the settingsSchema.ts
description for `outboundCorrelation.propagateTraceContext` describe
the toggle's behavior without noting that the flag is a silent no-op
when `telemetry.enabled` is false. An operator who sets only
`outboundCorrelation.propagateTraceContext: true` and forgets the
telemetry switch gets zero behavior change — no error, no warning, no
traceparent.

Fix: add the dependency disclosure to both surfaces, plus a JSON
example showing both flags wired together for the ARMS+DashScope
cross-process trace continuation use case.

Also fix a minor comment accuracy nit at `sdk.test.ts:683`: said the
SDK installs `W3CTraceContextPropagator` instance when opt-in is true,
but the actual default is `CompositePropagator(W3CTraceContextPropagator
+ W3CBaggagePropagator)` per `@opentelemetry/sdk-node` source.

Vscode-ide-companion settings.schema.json regenerated to reflect the
expanded description string.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* test(config): cover getOutboundCorrelationPropagateTraceContext defaults

R4 (commit 9bdd3bd6f) added the getter but the test file didn't grow a
corresponding describe block — sibling telemetry getters all have unit
tests but this new one was missed.

Add 4 cases covering the security-relevant default-to-false invariant
and explicit-set behavior:
- omitted outboundCorrelation → false
- empty outboundCorrelation: {} → false (the `?? false` collapse on the
  getter, complementing the same on the constructor)
- explicit true → true
- explicit false → false

PR #4390 review (wenshao).

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* docs(design): reflect post-R4 polish commits in §12

R4 (commit 9bdd3bd6f) was followed by two polish commits that the
design doc §12 didn't track:

- 0be0df270 (docs): telemetry.enabled dependency disclosure on
  propagateTraceContext — added to telemetry.md + settingsSchema
  description because a self-review pass identified the silent-no-op
  footgun (operator sets propagateTraceContext: true but forgets
  telemetry.enabled: true, sees zero behavior change with no error).
- c0352fd5b (test): 4 config.test.ts cases covering the
  getOutboundCorrelationPropagateTraceContext default-false invariant
  (omitted / {} / explicit true / explicit false) — wenshao review
  flagged the test gap.

Updates §12.4 with a new "Hidden dependency: telemetry.enabled" sub-
section explaining the gating relationship and pointing forward at the
follow-up PR (future outboundCorrelation.* settings inherit the same
dependency). Updates §12.5 implementation table to add the
config.test.ts row and clarify the telemetry.md / vscode-schema rows
were touched again in the polish pass.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* refactor: simplify post-R4 polish per /simplify review

/simplify review pass on commits 0be0df270 + c0352fd5b + 62cf6b4ee
flagged 4 concerns. Fix all 4:

1. **settingsSchema.ts description**: footgun warning ("Depends on
   telemetry.enabled: true") was at char 600+ of a 650-char description.
   VS Code settings UI truncates to ~300 chars inline → the most
   important warning was hidden in the most-glanced view. Hoist to first
   sentence ("Requires telemetry.enabled: true.").

2. **config.test.ts**: drop the task-narration comment
   ("PR #4390 R4: keep wire-level toggle out of telemetry namespace.")
   that just restated the change context. The remaining 2-line comment
   explaining WHY default-to-false is security-relevant survives.

3. **config.test.ts**: collapse 4 separate `it()` blocks into a single
   `it.each([...])` covering the same 4 precondition × expectation
   combinations. Removes boilerplate (`new Config({...baseParams, ...})`
   repeated 4×) without losing assertion power; case-3 ("explicit false")
   was a weak duplicate of case-2 ("empty object") since both hit the
   same `?? false` branch, but keeping all 4 in the parametric table
   documents intent more clearly than dropping case-3.

4. **design doc §12.4 + §12.5**: strip specific commit SHAs
   (`0be0df270`, `c0352fd5b`) — design docs should be evergreen, not
   doubled-up commit logs (those live in `git log`). Keep the design
   intent ("two panels both document the dependency" / "test block
   added") without naming the specific commits.

Regenerated vscode-ide-companion/schemas/settings.schema.json to
reflect the hoisted description sentence.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
2026-05-25 22:16:54 +08:00
334 changed files with 38316 additions and 4069 deletions

View File

@ -0,0 +1,136 @@
---
title: 'Memory Pressure Monitor'
date: '2026-05-21'
status: 'implemented'
---
# Memory Pressure Monitor
## Problem
Long-running Qwen Code sessions can accumulate memory through large tool
results, repeated file reads, chat history, and native/external allocations.
Before this change, the core package had diagnostics and session-reset cleanup,
but no runtime response when memory pressure rises during normal tool
execution.
The highest-value cache-specific gap is `FileReadCache`: it already has a
bounded FIFO size, but it did not have a time-based eviction path. That means a
session can retain inactive file-read metadata until the hard entry limit is
hit, even when the process is under memory pressure.
## Goals
- Add a low-overhead memory pressure check after tool execution.
- Prefer surgical cleanup before destructive cleanup.
- Respect container memory limits when cgroup v2 or cgroup v1 memory limit
files are available.
- React to V8 heap pressure before JavaScript heap OOM on high-memory hosts.
- Keep subagent/scoped `Config` instances isolated from parent session cleanup.
- Make behavior configurable through environment variables without adding a new
user-facing settings surface.
## Non-Goals
- Do not add a background polling loop.
- Do not make explicit GC the default; it only runs when enabled and Node was
started with `--expose-gc`.
- Do not change prior-read enforcement semantics. Cache eviction can remove old
metadata, but it must not weaken stale-file checks for retained entries.
## Design
`Config.initialize()` creates one `MemoryPressureMonitor` per initialized
`Config`. `getMemoryPressureMonitor()` mirrors the existing `getFileReadCache()`
Object.create isolation pattern: when a child config is created through
prototype delegation, the getter lazily installs an own monitor bound to that
child config.
`CoreToolScheduler.executeSingleToolCall()` calls `scheduleCheck()` in its
`finally` block after ending the tool span. `scheduleCheck()` coalesces multiple
calls in the same event-loop turn with `queueMicrotask`, so concurrent read-like
tool batches do not run one memory check per tool result.
The monitor uses the stronger of two pressure signals:
- RSS divided by an effective process memory limit. Prefer cgroup v2
`/sys/fs/cgroup/memory.max` when it is a finite positive value; fall back to
cgroup v1 `/sys/fs/cgroup/memory/memory.limit_in_bytes`, then to
`os.totalmem()` otherwise. cgroup v1's huge "unlimited" sentinel values are
ignored.
- V8 `heapUsed` divided by `getHeapStatistics().heap_size_limit`.
Using both signals matters because containers usually fail by RSS/cgroup limit,
while local high-memory machines can hit V8 heap OOM long before RSS is a large
fraction of total system memory.
Default thresholds are intentionally conservative enough to react before the OS
or container OOM killer does:
- `softPressureRatio = 0.50`
- `hardPressureRatio = 0.65`
- `criticalRatio = 0.80`
- `cleanupCooldownMs = 5000`
- `enableExplicitGC = false`
Environment overrides:
- `QWEN_MEMORY_PRESSURE_SOFT`
- `QWEN_MEMORY_PRESSURE_HARD`
- `QWEN_MEMORY_PRESSURE_CRITICAL`
- `QWEN_MEMORY_ENABLE_GC=1`
Invalid ratios fall back to defaults. Valid ratios must be ordered as
`soft < hard < critical`, with a lower soft bound of `0.3` and an upper
critical bound of `0.98`. Ratio env vars are parsed strictly with `Number()`,
so values such as `0.8extra` are rejected instead of partially accepted.
Invalid memory-pressure env configuration writes a visible warning to stderr
and to the debug log before falling back to defaults.
## Cleanup Policy
Pressure levels map to increasingly strong cleanup:
- `soft`: evict stale `FileReadCache` entries not accessed in 60 minutes.
- `hard`: evict cache entries not accessed in 30 minutes.
- `critical`: clear the file-read cache and optionally trigger `global.gc()`.
The monitor intentionally does not force chat compaction. Compaction can call
the model backend and rewrite active chat state, so it should be triggered only
from a call site that can safely coordinate with the conversation loop.
Cleanup is fire-and-forget from the scheduler, but the monitor guards cleanup
steps with `cleanupInProgress` and a cooldown timestamp. A higher-pressure
cleanup can bypass the cooldown and queue behind an in-progress lower-pressure
cleanup, so a `critical` check is not lost while a `soft` cleanup is finishing.
After successful cleanup it logs an RSS delta on `setImmediate()`, but RSS
movement is diagnostic only: V8 and libc may retain freed pages even when
JavaScript objects became collectible. Consecutive failures count cleanup-step
exceptions, not unchanged RSS, and the counter is reset on a new session. If
three successful cleanup attempts in a row free less than 1% RSS, the monitor
emits `memory-cleanup-ineffective` as a diagnostic signal without treating the
cleanup step itself as failed.
## Test Coverage
The implementation is covered by:
- threshold validation tests;
- environment config parsing, fallback, visible warning, and explicit GC tests;
- pressure classification tests using mocked `process.memoryUsage()`;
- cgroup v2 `memory.max` and cgroup v1 `memory.limit_in_bytes` behavior;
- V8 heap limit behavior;
- `scheduleCheck()` coalescing;
- scheduler integration that invokes `scheduleCheck()` after tool execution;
- soft and critical cleanup actions;
- cleanup failure accounting for thrown cleanup steps;
- cleanup listener exception isolation and ineffective-cleanup diagnostics;
- child `Config` monitor isolation through `Object.create`;
- `FileReadCache.evictNotAccessedSince()` behavior.
## Risks And Tradeoffs
- RSS can stay flat after cleanup because V8 or libc may retain freed memory.
RSS deltas are logged, but unchanged RSS does not count as a cleanup failure.
- Time-based file-read cache eviction may reduce fast-path hits for old files,
but it preserves recently active entries and only runs under memory pressure.

View File

@ -17,13 +17,15 @@ npm install
### Setup Content
Link the documentation content from the parent `docs` directory:
Prepare the public documentation content from the parent `docs` directory:
```bash
npm run link
```
This creates a symbolic link from `../docs` to `content` in the project.
This creates a `content` directory with copies of the public docs sections.
Internal planning, design, and E2E notes remain outside the docs site content
tree.
### Development

View File

@ -7,10 +7,10 @@
"type": "module",
"main": "index.js",
"scripts": {
"link": "ln -s ../docs content",
"link": "node scripts/link-public-docs.mjs",
"clean": "rm -rf .next",
"dev": "npm run clean && next --turbopack",
"test": "echo \"Error: no test specified\" && exit 1"
"test": "vitest run --config vitest.config.js"
},
"dependencies": {
"next": "^16.0.8",
@ -18,5 +18,8 @@
"nextra-theme-docs": "^4.6.1",
"react": "^19.2.1",
"react-dom": "^19.2.1"
},
"devDependencies": {
"vitest": "^3.2.4"
}
}

View File

@ -0,0 +1,26 @@
import { cp, mkdir, rm, symlink } from 'node:fs/promises';
import { join } from 'node:path';
import { PUBLIC_DOC_ROOTS } from '../src/app/public-docs.js';
const contentDir = 'content';
async function linkPublicDocs() {
try {
await rm(contentDir, { force: true, recursive: true });
await mkdir(contentDir);
await cp('../docs/index.md', join(contentDir, 'index.md'));
await cp('../docs/_meta.ts', join(contentDir, '_meta.ts'));
for (const root of PUBLIC_DOC_ROOTS) {
await symlink(join('..', '..', 'docs', root), join(contentDir, root));
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to link public docs into ${contentDir}: ${message}`,
);
}
}
await linkPublicDocs();

View File

@ -1,10 +1,23 @@
import { generateStaticParamsFor, importPage } from 'nextra/pages';
import { notFound } from 'next/navigation';
import { useMDXComponents as getMDXComponents } from '../../../mdx-components';
import { filterPublicStaticParams, isPublicDocsPath } from '../public-docs';
export const generateStaticParams = generateStaticParamsFor('mdxPath');
const generateAllStaticParams = generateStaticParamsFor('mdxPath');
export const dynamicParams = false;
export async function generateStaticParams(...args) {
const staticParams = await generateAllStaticParams(...args);
return filterPublicStaticParams(staticParams);
}
export async function generateMetadata(props) {
const params = await props.params;
if (!isPublicDocsPath(params.mdxPath)) {
notFound();
}
const { metadata } = await importPage(params.mdxPath);
return metadata;
}
@ -13,6 +26,10 @@ const Wrapper = getMDXComponents().wrapper;
export default async function Page(props) {
const params = await props.params;
if (!isPublicDocsPath(params.mdxPath)) {
notFound();
}
const {
default: MDXContent,
toc,

View File

@ -0,0 +1,59 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => {
const generateAllStaticParams = vi.fn();
return {
generateAllStaticParams,
generateStaticParamsFor: vi.fn(() => generateAllStaticParams),
};
});
vi.mock('nextra/pages', () => ({
generateStaticParamsFor: mocks.generateStaticParamsFor,
importPage: vi.fn(),
}));
vi.mock('next/navigation', () => ({
notFound: vi.fn(),
}));
vi.mock('../../../mdx-components', () => ({
useMDXComponents: () => ({
wrapper: ({ children }) => children,
}),
}));
describe('generateStaticParams', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('filters internal docs from Nextra static params', async () => {
mocks.generateAllStaticParams.mockResolvedValue([
{ mdxPath: [] },
{ mdxPath: ['users', 'foo'] },
{ mdxPath: ['en', 'users'] },
{ mdxPath: ['design', 'bar'] },
{ mdxPath: ['plans'] },
]);
const { generateStaticParams } = await import('./page.jsx');
await expect(generateStaticParams()).resolves.toEqual([
{ mdxPath: [] },
{ mdxPath: ['users', 'foo'] },
{ mdxPath: ['en', 'users'] },
]);
});
it('fails closed if Nextra changes the static params shape', async () => {
mocks.generateAllStaticParams.mockResolvedValue([{ slug: ['users'] }]);
const { generateStaticParams } = await import('./page.jsx');
await expect(generateStaticParams()).rejects.toThrow(
'Expected generateStaticParamsFor("mdxPath") to return objects with an mdxPath array.',
);
});
});

View File

@ -0,0 +1,33 @@
const LOCALE_SEGMENTS = new Set(['en', 'zh', 'de', 'fr', 'ja', 'ru', 'pt-BR']);
// Keep this in sync with the public top-level page entries in docs/_meta.ts.
// docs-site/scripts/link-public-docs.mjs consumes the same allowlist.
export const PUBLIC_DOC_ROOTS = ['users', 'developers'];
const PUBLIC_DOC_ROOT_SET = new Set(PUBLIC_DOC_ROOTS);
function publicRootFromSegments(segments = []) {
if (segments.length === 0 || (segments.length === 1 && segments[0] === '')) {
return undefined;
}
const rootIndex = LOCALE_SEGMENTS.has(segments[0]) ? 1 : 0;
return segments[rootIndex];
}
export function isPublicDocsPath(mdxPath = []) {
const root = publicRootFromSegments(mdxPath);
return root === undefined || PUBLIC_DOC_ROOT_SET.has(root);
}
export function filterPublicStaticParams(staticParams = []) {
return staticParams.filter((staticParam) => {
if (!Array.isArray(staticParam?.mdxPath)) {
throw new TypeError(
'Expected generateStaticParamsFor("mdxPath") to return objects with an mdxPath array.',
);
}
return isPublicDocsPath(staticParam.mdxPath);
});
}

View File

@ -0,0 +1,43 @@
import { describe, expect, it } from 'vitest';
import { filterPublicStaticParams, isPublicDocsPath } from './public-docs.js';
describe('isPublicDocsPath', () => {
it.each([
[[], true],
[[''], true],
[['users', 'foo'], true],
[['design', 'bar'], false],
[['en', 'users'], true],
[['plans'], false],
[['en'], true],
])('returns %s for %j', (mdxPath, expected) => {
expect(isPublicDocsPath(mdxPath)).toBe(expected);
});
});
describe('filterPublicStaticParams', () => {
it('keeps public paths and rejects internal docs paths', () => {
expect(
filterPublicStaticParams([
{ mdxPath: [] },
{ mdxPath: [''] },
{ mdxPath: ['users', 'foo'] },
{ mdxPath: ['en', 'developers'] },
{ mdxPath: ['design', 'bar'] },
{ mdxPath: ['plans'] },
]),
).toEqual([
{ mdxPath: [] },
{ mdxPath: [''] },
{ mdxPath: ['users', 'foo'] },
{ mdxPath: ['en', 'developers'] },
]);
});
it('fails closed if Nextra changes the static params shape', () => {
expect(() => filterPublicStaticParams([{ slug: ['users'] }])).toThrow(
'Expected generateStaticParamsFor("mdxPath") to return objects with an mdxPath array.',
);
});
});

View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['src/**/*.test.{js,jsx}'],
},
});

View File

@ -0,0 +1,574 @@
# Agent Loop 减轮方案:从 Skill 设计入手
> 与 `rt-optimization-design.md` 同目录,互为补充:那份文档讨论**框架机制**层面减轮(D1 跳过末尾总结轮、D2 fast 路由、D4 prevalidate),这份文档主张**减轮的真正杠杆在 skill/tool 设计层**,并提出一条不依赖框架改造、不依赖 cache hit rate 数据的可实施路径。
---
## 0. 验收 Spec(开发前置 gate)
> 本节是开发的**前置 gate** — 列出哪些 spec 必须在动手前确认、哪些 spec 必须等数据驱动。把 spec 前置而非"做完再看指标",是为了避免:(a) 写完才发现指标不可测、(b) 阈值随结果飘移导致结论失真、(c) 没设止损线让方案陷入"看起来在做、其实没收益"。
>
> **本 spec 框架的适用边界**:本框架假设方向正确性可以在 P1.5 基线测量后判断。这个假设对"减轮"场景成立,因为它有清晰的可测信号(轮数、followup_rate、batch_size)。**超出此假设的场景**(例如未来用同一框架做"质量优化"等难以量化的方向),spec 前置可能反而阻碍快速学习;遇到时回退到 §0.5 治理流程重新评估,不机械套用本框架。
**spec 分四层 — 时机不同**:
| 层级 | 类型 | 锁定时机 |
| ---- | --------------------------------------- | -------------------------------- |
| §0.1 | 工程层 spec(数据管道、代码改动正确性) | **前置**、可立刻锁定 |
| §0.2 | 统计层 spec(项目"算成功"的指标) | **前置**、阈值待 P1.5 基线后锁定 |
| §0.3 | 止损线("如果发生就放弃"硬条件) | **前置**、不可移动 |
| §0.4 | per-skill spec(具体改哪个、目标多少) | **后置**、Layer 1 数据驱动 |
### 0.1 工程层 spec(必须前置 · 可立刻锁定)
数据管道与代码改动的正确性 spec — 不依赖任何业务判断或基线数据,开发前就该锁定:
- **qwen-logger 链路通畅**(§4.1.1b):skill_launch 事件能同时落到 OTLP 和 qwen-logger 两条管道
- **`prompt_id` 串联**:单个 user prompt 触发的 `skill_launch` + 后续 `tool_call` 能用同一个 `prompt_id` grep 出完整 trail
- **`batch_size` 非 undefined**(§4.3.2 方向 A):单工具 batch 显式设 `batch_size = 1` / `batch_position = 0`
- **SQL 可跑通**(§4.1.2):离线 SQL 在真实 telemetry backend 输出非空且能区分高/低 followup_rate skill
- **基线方差 < P50 × 20%**(P1.5):基线测量稳定(否则后续 A/B 对比不可信)—— 注:本条虽列在 §0.1 工程层,但**锁定依赖 P1.5 基线数据**,是 §0.1 中唯一的后置验证项;P1.5 未通过则 §0.2 阈值无法可信锁定
- **Skill 体积预算**(Layer 2 改造):内联 followup 后,skill 描述 token 数不超过改造前的 2×,且绝对值 ≤ 500 tokens(取较小值)。超过则按 §4.2 拆分 skill 而非合并。本条与 §7 第 2 条、§4.2 已有约束对齐,前置到 spec 层
- **`npm run preflight` 全过**:每个 PR 的硬门槛
### 0.2 统计层 spec(必须前置 · 阈值待 P1.5 后锁定)
项目算"统计意义上成功"的指标 — **方向**前置定下,**阈值**等基线测出来后锁定(避免凭空填数字):
| 指标 | 方向 | 锁定时机 | 当前占位阈值(待校准) |
| ---------------------------------- | -------- | --------- | ---------------------- |
| top-3 skill 加权 `followup_rate` | ↓ | P1.5 末 | ≥ 30% |
| 含 skill 的会话端到端 RT P50 | ↓ | P1.5 末 | ≥ 2s |
| `batch_size > 1` 的 tool_call 占比 | ↑ | P3 前 | ≥ 30% |
| 改造的 skill 触发场景 A/B 显著性 | p < 0.05 | P2 改完前 | n 待定 |
> **关键约束**:占位阈值不是承诺。P1.5 基线如果显示"top-5 skill 加权 followup_rate < 30%"(触发 §0.3 止损线 #1),项目终止;**不能为了让阈值"达到"而下调 spec**。
>
> **怎么测**:每个指标的测量方法、SQL 模板、A/B 设计见 §5.1-§5.2;统计显著性(p < 0.05)的样本量计算见 §5.1。
### 0.3 止损线(必须前置 · P-1 锁定后受限可调)
§5.3 已列。这些是"如果发生就放弃"的硬条件 — **任何情况下不能为了达成 §0.2 统计层 spec 而放宽止损线**。
- **结果指标**(3 条):top-5 加权 `followup_rate < 30%` / 改完 2 个 skill RT P50 ↓ < 1s / Layer 3 后 `batch_size P50` 仍 = 1
- **过程指标**(3 条):skill 命中率 ↓ ≥ 5pp / 内联 followup 失败率 ≥ 5% / 用户取消率 ↑ ≥ 2pp
详见 §5.3。
**可调性规则**(避免无数据支撑的纪律刚性):
| 阶段 | 可否调整 | 调整方向 |
| --------------------- | ---------------------------------------- | ------------------------------------------------------------------------------- |
| P-1 锁定时 | ✅ 任意调整(基于历史 telemetry 或共识) | 任意 |
| P-1 锁定后 → P1.5 末 | ❌ 不可调整 | — |
| P1.5 末(基线出来时) | ✅ 仅允许**放宽**一次 | 放宽(如 30% → 25%)需附数据证据 + 2 人评审;**不允许收紧**(避免事后追加止损) |
| P1.5 之后 | ❌ 不可调整 | — |
> 阈值占位值(30% / 1s / 5pp 等)当前**无历史数据支撑**,是 P-1 评审前的工程师直觉。如果 P-1 评审时能拿到最近 4 周历史 telemetry,应基于历史数据校准止损线;拿不到则保留占位值,P1.5 末执行上面的"放宽一次"规则。
### 0.4 per-skill spec(必须后置 · 数据驱动)
具体改哪个 skill、目标 `followup_rate` 改到多少 — **Layer 1 数据出来前不锁定**。
不锁定的理由:先验设计 vs 后验数据可能差很多。强行前置会重蹈 `rt-optimization-design.md` §7 D2 路线的覆辙 —— 前置假设"fast 模型快 2-3s"被 cache 实装这一后验事实推翻,导致方案净收益接近 0 甚至为负。
**产出位置**:per-skill spec 在 P1.5 末由数据驱动产出,每个 Layer 2 PR 的 description 里独立声明(不进 design 文档,避免文档每改一个 skill 就改)。
**per-skill spec 结构模板**(与 §4.2 的 PR description 必含项对齐 — 这两个清单是同一份,§4.2 是过程视角、本节是 spec 视角):
| 字段 | 内容 | 数据来源 |
| --------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------- |
| 1. 当前数据 | invocation_count、followup_rate、top followup tools | Layer 1 telemetry |
| 2. 目标 | followup_rate 从 X% 降到 Y% | 基于 §0.2 改善方向,绝对值 PR 内自行定 |
| 3. 改造范围 | 内联哪些 followup(read/grep/shell read-only),明确**不**内联什么(write 操作 / 跨 skill / 深度推理) | §4.2 改造模式表 |
| 4. 输出契约更新 | skill 描述里加的预声明("Returns: ...") | §3.2 改造示例 |
| 5. A/B 计划 | 改造后 2 周观察 followup_rate / RT P50 / 过程指标,对照 §5.1 验收线 | §5.1 |
| 6. 体积证明 | 改造前后 skill 描述 token 数(用 tiktoken 估算),不得超 §0.1"Skill 体积预算" | §0.1 第 6 条 |
### 0.5 spec 治理
- **修改 §0.1 / §0.3 spec** 需 design 文档更新 + PR 评审;§0.3 仅遵循 §0.3"可调性规则"在 P1.5 末窗口内放宽
- **修改 §0.2 阈值(P1.5 锁定后)** 需附以下至少一项数据证据:
- (a) P1.5 基线测量结果与已锁定阈值的偏差分析(含原始测量记录链接)
- (b) 同类项目的公开 benchmark 数据(含来源链接)
- (c) 内部 ≥ 2 人评审签字的偏差说明
PR 评审时若上述证据均无,评审者**有义务** block PR — 不接受"凭工程师直觉调整"
- **§0.4 per-skill spec** 在数据驱动产出后写入 PR description(按 §0.4 6 项模板),不进 design 文档
---
## 1. 背景与定位
### 1.1 问题
`rt-optimization-design.md` §1.2 给出的基线:3 轮 agent loop,13.4s 端到端,其中 LLM 调用占 78%。每一轮 ~3-4s。
```
Round 1 (3.8s, 28%): LLM 决策调 skill
Round 2 (3.0s, 22%): LLM 决策调 shell
Round 3 (3.8s, 28%): LLM 总结
```
`rt-optimization-design.md` §6/§7 经过两轮 review 后,D2/D4 已被否决,D1/D3 也降级为"等浮油完成后再评估"。但**整份原文档都聚焦在末尾的 Round 3(总结轮)或单轮内的微优化(D4)上,完全没有正面讨论 Round 1 → Round 2 这个"中间轮"为什么会出现、能不能消掉**。
事实是:Round 2 之所以存在,**绝大多数情况是因为 Round 1 调用的 skill 没有返回完整答案**,模型才追加 shell 查询补全。如果 skill 设计成"一次拿到完整结果",3 轮 → 2 轮,省掉的就是 Round 2 那 ~3s — 这是与 D1 完全不重叠的收益面。
### 1.2 与 rt-optimization-design 的关系
| 减轮方向 | 命中的轮次 | 杠杆位置 | 本文档定位 |
| -------------------- | ------------------------------- | ---------------------------- | ---------------------------- |
| D1 `skipLlmRound` | 末尾总结轮 | 框架机制 + per-tool opt-in | 兜底,**放在 Layer 2 之后** |
| D2 fast 路由 | 单轮延迟 | 框架机制 | 已 defer,**不在本文档范围** |
| D3 Summarizing 状态 | 末尾总结轮(感知层) | UI 状态机 | 可选,与本方案正交 |
| D4 prevalidate | 单轮延迟 | 框架机制 | 已 defer,**不在本文档范围** |
| **本方案 Layer 1-3** | **中间决策轮 + 并发未触发的轮** | **skill 设计 + prompt 工程** | **新增方向** |
### 1.3 核心论点
减轮的真正杠杆在 skill/tool 设计层,不在 agent 框架。三个理由:
1. **§1.2 基线本身就暴露问题在 skill** — Round 1 → Round 2 的跳跃是 skill 返回不全才发生的,框架做对了,skill 做错了
2. **框架级减轮最终也要 per-tool opt-in** — D1 的 `skipLlmRound` 必须每个工具显式标记,绕一圈回到 skill 工程,还多一套不变量修复 + 决策门控成本
3. **ROI 局部可测、灰度容易** — 改一个 skill 就少一轮 × 该 skill 触发次数,不依赖 cache hit rate 数据,不依赖跨系统改动
> **实施前必须先走 §0 验收 Spec 前置评审(P-1 阶段,0.5d)** — §0.1 工程层 spec 和 §0.3 止损线在动手前必须锁定;§0.2 统计层阈值的方向也要前置确认(具体数值等 P1.5 基线后再锁)。跳过 §0 进入 P0 实施 = 默认走"做完才看指标"的反模式,文档不背书这种做法。
---
## 2. 设计原则
1. **不改 agent 框架** — 不动 `useGeminiStream` / `coreToolScheduler` / `geminiChat` 核心路径
2. **数据驱动选优先级** — 先建 telemetry,让数据告诉你改哪个 skill,不靠拍脑袋
3. **per-skill 可测可灰度** — 每个 skill 改造独立 A/B,失败局部回退
4. **复利优先** — 收益 = 单次减轮收益 × 触发频率,高频 skill 优先
5. **不绑定 D1** — 本方案的成功不依赖 D1 是否落地
---
## 3. 三层方案
### 3.1 Layer 1:减轮 Telemetry(找金矿)
**目标**:让数据告诉你哪些 skill 最值得改 — 即"用了这个 skill 之后,模型有多大概率追加一次工具调用"。
**核心字段**(per-turn、per-skill-invocation):
```typescript
interface SkillFollowupRecord {
skill_name: string;
prompt_id: string; // 关联同一 user prompt 内的所有 events
turn_index: number; // 该 skill 在 loop 里是第几轮
followup_tool_names: string[]; // 同一 prompt_id 下,skill 之后还调了哪些工具
followup_count: number; // followup_tool_names.length
followup_kinds: Kind[]; // Read/Edit/Execute/...
next_turn_is_terminal: boolean; // skill 之后下一轮就出文字(不再调工具)
user_followup_within_30s: boolean; // 用户在结果显示后 30s 内追加新 prompt(质量回归信号)
}
```
**关键指标**:
- `skill_followup_rate = sum(followup_count > 0) / total_invocations`
- `terminal_after_skill_rate = sum(next_turn_is_terminal) / total_invocations`
- 按 `(skill_name, top followup tool)` 聚合 — 看哪些 skill 之后最常追加哪个工具
**金矿判定**:
```
(invocation_count_weekly × skill_followup_rate) ≥ threshold
↓
该 skill 是减轮金矿,优先 Layer 2 改造
```
阈值建议:top-3 按上式排序的 skill,先改前 2 个。
### 3.2 Layer 2:Skill 输出完整化
**目标**:让被识别为金矿的 skill 一次返回完整答案,消除 Round 1 → Round 2 的跳跃。
**改造模式(按 followup 类型分类)**:
| Followup 模式 | 典型场景 | 改造方向 |
| --------------------------- | -------------------------- | ---------------------------------- |
| skill → `read_file` | skill 给路径,模型再读 | skill 内部直接读,返回内容 |
| skill → `grep/glob` | skill 给目录,模型再搜 | skill 内部搜好,返回匹配 |
| skill → `shell` (read-only) | skill 给命令,模型再执行 | skill 内部跑命令,返回输出 |
| skill → `shell` (write) | skill 给方案,模型再执行写 | **保留**(写操作要确认,不应合并) |
| skill → another skill | 链式调用 | **不合并**(保持组合性) |
**改造检查清单(per-skill PR 模板)**:
1. 在 skill 描述里**预声明输出契约**:明确写 "Returns: full file content / matched lines / command output",让模型知道不必追加查询
2. 在 skill 内部**完成所有 read-only followup**:把 telemetry 显示 >50% 追加率的 read/search 操作内联进 skill
3. **不内联 write 操作**:写操作需要用户确认,必须单独成轮
4. **不内联深度推理 followup**:如果 followup 是"基于此再分析",那是模型的事,不是 skill 的事
5. **附 A/B telemetry**:改造后 2 周对比 `followup_rate` 是否下降到 <20%
**典型改造示例(示意)**:
改造前:
```
skill "list-workspaces" returns: ["ws_a", "ws_b"]
→ Round 2: model calls shell to get details for each workspace
```
改造后:
```
skill "list-workspaces" returns:
- ws_a (owner: foo, last_active: 2026-05-20, status: active)
- ws_b (owner: bar, last_active: 2026-05-01, status: archived)
description updated: "Returns workspaces with owner, last_active, status"
→ Round 2 disappears for ~80% of queries
```
### 3.3 Layer 3:Prompt 教育模型并发
**目标**:对于独立工具(多文件读、多目录搜),让模型在同一轮里并发发起 tool_calls,把 N 轮压成 1 轮。
**前提**:基础设施已就绪 — `tools/tools.ts:818` 的 `CONCURRENCY_SAFE_KINDS` + `coreToolScheduler` 的 `partitionToolCalls` 已经能并发执行同 batch 内的 read/search/fetch 工具。**差的只是模型主动发起并发 tool_calls 的意愿**,qwen-coder 默认偏串行。
**改动位置**:`packages/core/src/core/prompts.ts`(已审计过,加在 `# Final Reminder` 段 L396 附近不会破坏 cache 命中以外的事 — 仅一次性预热成本)。
**指导文本(示意,需 A/B 调优)**:
```
When you need to call multiple independent read-only tools (read_file,
grep, glob, web_fetch), emit them in a SINGLE tool_calls batch — do NOT
call them sequentially across rounds. They will execute concurrently.
Examples:
- Reading 3 files for comparison: emit 3 read_file calls in one batch
- Searching for 2 patterns: emit 2 grep calls in one batch
Do NOT batch when the second call depends on the first call's result.
```
**生效衡量**:新增 telemetry 字段 `batch_size`(同 turn 内 tool_calls 数量)— 改 prompt 前后对比分布。
#### 3.3.1 扩展 `CONCURRENCY_SAFE_KINDS`(Layer 3 子项)
prompt 教育模型并发只是供给侧(模型愿意一次发多个 tool_calls),但 `tools/tools.ts:818` 的 `CONCURRENCY_SAFE_KINDS = { Read, Search, Fetch }` 决定**实际能并发执行的工具范围**:`partitionToolCalls`(`coreToolScheduler.ts:775`)会把"连续的安全工具"打包成 concurrent batch,其余各自串行。
如果模型按指导一次发了 3 个 tool_calls 但其中 1 个属于 `Kind.Execute` 且不在安全集合,整个 batch 就会被拆开串行执行 — Layer 3 prompt 改动的收益会被运行时调度抵消。
**扩展候选**(按风险递增):
- `Kind.Think`(含 save_memory / todo_write)—— **不要加**,有隐式写入
- 只读 shell(`isShellCommandReadOnly()` 返回 true 的 Execute)—— `partitionToolCalls` 已有特判(`coreToolScheduler.ts` `partitionToolCalls` 注释里提到 "Execute (shell) is safe only when isShellCommandReadOnly() returns true"),现状已覆盖,无需改 `CONCURRENCY_SAFE_KINDS`
- MCP 工具按 `Kind` 分类 —— 各 MCP server 行为差异大,需要在工具注册时显式 opt-in 才安全
**结论**:当前集合已经合理,**Layer 3 不依赖扩展 `CONCURRENCY_SAFE_KINDS`**。本节存在的意义是:在收完 `batch_size` telemetry 数据后,**如果发现"并发 batch P50 < 期望值",先检查是不是被 `partitionToolCalls` 切断而非模型不并发**。这是 Layer 3 A/B 失败时的一个诊断路径,不是必做项。
> 信用:codex review 提出"扩展 `CONCURRENCY_SAFE_KINDS` 是被忽略的杠杆"。核对后判断为:现状已有 `isShellCommandReadOnly` 特判覆盖最大头,扩展集合本身收益小、风险大;保留作为诊断路径。
---
## 4. 详细实施
### 4.1 Layer 1:Telemetry 扩展(1-2d)
#### 4.1.1 补 `prompt_id` 到 `SkillLaunchEvent`
**位置**:`packages/core/src/telemetry/types.ts:896`
当前 `SkillLaunchEvent` 仅含 `skill_name` + `success`,**无 `prompt_id`** — 无法跟同一 turn 内的其他 `ToolCallEvent` 关联。
```typescript
// types.ts:896
export class SkillLaunchEvent implements BaseTelemetryEvent {
'event.name': 'skill_launch';
'event.timestamp': string;
skill_name: string;
success: boolean;
prompt_id: string; // 新增
turn_index?: number; // 新增
constructor(
skill_name: string,
success: boolean,
prompt_id: string, // 新增
turn_index?: number, // 新增
) { ... }
}
```
**调用方更新**:`packages/core/src/tools/skill.ts` 的 4 个 `logSkillLaunch` 调用点(L386, L399, L426, L482),传入 `this.params` 拿不到 `prompt_id` — `BaseToolInvocation` 仅持有 `params`,没有 `request.prompt_id` 字段。**实际实现**用鸭子类型方式注入:`SkillToolInvocation` 暴露 `setPromptId(id)` setter + 私有 `promptId` 字段,`CoreToolScheduler.buildInvocation`(`coreToolScheduler.ts:1253`)在 build 后 duck-type 调 `setPromptId(request.prompt_id)`,对齐既有 `setCallId` hook 的 pattern;invocation 在 `execute()` 内的 4 个 `logSkillLaunch` 都传 `this.promptId`。**早期版本的本节描述("BaseToolInvocation 已有 request.prompt_id")是错的**,已在 PR #4565 review 后更正。
#### 4.1.1b qwen-logger 链路修复(前置)
补 `prompt_id` 之前要先解决一个 **既存的链路断点**:`packages/core/src/telemetry/qwen-logger/qwen-logger.ts:908` 定义了 `logSkillLaunchEvent(event)` 方法,但**全仓库无任何调用方** —— `loggers.ts:958` 的 `logSkillLaunch` 直接走 `logs.getLogger(SERVICE_NAME).emit()` 这条 OTLP 路径,绕过了 qwen-logger。
后果:
- OTLP 路径上的 skill_launch 事件能到 OTLP collector(已工作),但 qwen-logger 那条专用上报链路目前是死的
- 如果 telemetry backend 是从 qwen-logger 消费(而非 OTLP),skill_launch 事件**完全不上报**
- §4.1.2 离线 SQL 派生 `SkillFollowupRecord` 依赖 skill_launch 事件落库 —— **必须先验证现在 skill_launch 在 backend 是否可见**
修复方向二选一:
- **A**(推荐)在 `loggers.ts:958` 的 `logSkillLaunch` 里加一行 `QwenLogger.getInstance(config)?.logSkillLaunchEvent(event)`,对齐 `logToolCall` 的 `loggers.ts:230` 写法
- **B** 确认 backend 只从 OTLP 消费,把 qwen-logger 里的 `logSkillLaunchEvent` 标 `@deprecated` 或删除
**为什么只补 QwenLogger 一条路径,不对齐 `logToolCall` 的 4 条全路径**:
`logToolCall`(`loggers.ts:220-247`)实际有 4 条出口:
1. `uiTelemetryService.addEvent(...)` — UI 展示
2. `config.getChatRecordingService()?.recordUiTelemetryEvent(...)` — 聊天历史
3. `QwenLogger.getInstance(config)?.logToolCallEvent(...)` — qwen-logger 后端遥测
4. OTLP `logger.emit(...)` — OpenTelemetry
skill_launch 是**纯后端遥测事件**,不需要在 UI 上展示(用户已经看到 SkillTool 的 returnDisplay)、也不需要进 ChatRecording 的 turn 历史(skill 内部的工具调用已经各自被 recordUiTelemetryEvent 记录)。因此只补第 3 条(QwenLogger),保留第 4 条(OTLP),跳过 1/2 是有意的,不是遗漏。
**字段透传细节**:`loggers.ts:961-966` 用 `{ ...event }` spread 自动透传新字段(`prompt_id` 加进 `SkillLaunchEvent` 后这条路自动生效),但 `qwen-logger.ts:908` 的 `logSkillLaunchEvent` 内部如果显式解构 `event.skill_name` / `event.success`,新字段不会自动纳入,需手动同步。
工作量:A 路径约 0.5d(含 backend 端确认);B 路径约 0.2d(删代码 + 文档说明)。
#### 4.1.2 派生 `SkillFollowupRecord`(离线聚合)
不需要新事件类型 — `ToolCallEvent` 和 `SkillLaunchEvent` 都已带 `prompt_id`,离线 SQL 即可派生:
```sql
-- 伪 SQL,按实际 telemetry backend 调整
WITH skill_events AS (
SELECT prompt_id, skill_name, timestamp FROM events
WHERE event_name = 'skill_launch' AND success = true
),
tool_events AS (
SELECT prompt_id, function_name, timestamp FROM events
WHERE event_name = 'tool_call'
),
followups AS (
SELECT s.skill_name, s.prompt_id,
COUNT(t.function_name) AS followup_count,
ARRAY_AGG(t.function_name) AS followup_tool_names
FROM skill_events s
LEFT JOIN tool_events t
ON s.prompt_id = t.prompt_id AND t.timestamp > s.timestamp
GROUP BY s.skill_name, s.prompt_id
)
SELECT skill_name,
COUNT(*) AS invocations,
AVG(followup_count) AS avg_followup,
SUM(CASE WHEN followup_count > 0 THEN 1 ELSE 0 END)::FLOAT / COUNT(*) AS followup_rate
FROM followups
GROUP BY skill_name
ORDER BY invocations * followup_rate DESC;
```
#### 4.1.3 跑 telemetry 1 周收数据
- 不变更 user-facing 行为
- 不需要任何配置开关 — telemetry 已有 opt-in 框架(`telemetry.target` 设置项)
- 1 周后产出 skill ranking 报告
### 4.2 Layer 2:Skill 改造(per-skill 0.5-1d)
按 Layer 1 数据从 top-down 改造。每个 skill 一个独立 PR,PR description 必须包含:
1. **数据**:当前 invocation_count、followup_rate、top followup tools
2. **改造范围**:内联了哪些 followup(明确不内联什么)
3. **输出契约更新**:skill 描述里加了什么预声明
4. **A/B 计划**:改造后 2 周再观察 followup_rate
**注意事项**:
- Skill 内联 read 操作不要重复 read_file 的所有边界情况处理(编码、二进制检测等)— 调用 `read_file` 工具本身,不要重写
- Skill 内联 grep/glob 同理
- Skill 内联 shell 命令需走 `executeToolCall` 标准路径(保留 telemetry)
- **不要让 skill 体积爆炸**:内联 followup 后 skill 描述 > 500 tokens 时,拆分 skill 而不是合并
### 4.3 Layer 3:Prompt 教育(0.5d 改动 + 实测调优)
#### 4.3.1 加并发指导
**位置**:`packages/core/src/core/prompts.ts` `# Final Reminder` 段(L396)
加上节 3.3 的指导文本。具体措辞需 A/B —— 先用最朴素版本,根据并发率提升程度再细化。
#### 4.3.2 加 `batch_size` telemetry
**位置**:`packages/core/src/telemetry/types.ts` 的 `ToolCallEvent` 或新增轻量级 `ToolBatchEvent`
```typescript
// 选项 A:在 ToolCallEvent 上加字段(侵入小)
export class ToolCallEvent {
...
batch_size?: number; // 同一 batch 内 tool_call 数量
batch_position?: number; // 在 batch 内的位置 (0-indexed)
}
// 选项 B:新增 ToolBatchEvent(语义更清晰,需走完整新事件类型流程)
```
**推荐选项 A** — 改动小、查询时聚合方便。
**状态传递路径**(关键 — 这一步成本被早期版本低估):
`coreToolScheduler.ts:2456` 的 `partitionToolCalls(callsToExecute)` 返回 `batches`,**但 batch 信息在调度路径上立刻丢失**:
```
executeToolCalls
└─ batches = partitionToolCalls(...) // 知道 batch.calls.length
└─ for batch of batches:
└─ this.runConcurrently(batch.calls, ...) // 知道 batch.calls.length
└─ executeSingleToolCall(call, ...) // ❌ 已不知道 batch
└─ ...
└─ finalizeToolCalls
└─ logToolCall(config, new ToolCallEvent(call)) // ❌ 无 batch context
```
`ToolCallEvent` 的构造器(`types.ts:189`)只接收单个 `CompletedToolCall`,无 batch 字段。
修复方向:
- **方向 A**(推荐):在 `ScheduledToolCall` 上加 `batchSize?: number` + `batchPosition?: number`。两条分支分别填充:
- 并发分支(`coreToolScheduler.ts:2459-2460`,`batch.calls.length > 1`):`runConcurrently(batch.calls, ...)` 进入循环前给每个 `call` 写 `batchSize = batch.calls.length`、`batchPosition = i`
- 串行分支(`L2462-2464` 的 `for (const call of batch.calls)`):单工具 batch 显式设 `batchSize = 1`、`batchPosition = 0`(**不要默认 undefined**,否则下游 telemetry 聚合时会把并发未生效的轮次误判为缺失数据)
`new ToolCallEvent(call)` 在构造器里从 `call` 读这两个字段
- **方向 B**:改 `ToolCallEvent` 构造器签名 `new ToolCallEvent(call, batchInfo?)`,所有调用方同步改(4 个 logToolCall 调用点 + 测试)。改动面比 A 大
工作量:方向 A 约 0.5d 含单测;方向 B 约 1d(调用方多)。
**同步衡量"模型并发意愿"** — Layer 3 改 prompts.ts 前后,对比 `batch_size > 1 的 tool_call 占比` 分布。这是 Layer 3 是否生效的关键指标,没这个数据 Layer 3 A/B 无法收尾。
#### 4.3.3 cache 影响评估
`prompts.ts` 改动会让 DashScope ephemeral cache 一次性失效(首次请求 cache miss,之后恢复)。这是已知一次性成本,参见 `rt-optimization-design.md` §7.8 的 prompt 稳态审计。
---
## 5. 验收与度量
> **本节是 §0 验收 Spec 的"方法论"配套** — §0 声明"算成功的指标 + 阈值前置/后置时机",§5 说明"怎么测、SQL 怎么写、A/B 怎么设计"。本节阈值是 §0.2 的当前占位,最终值在 P1.5 基线测量后锁定。
### 5.1 per-skill A/B 指标(改造后 2 周)
| 指标 | 验收线 | 备注 |
| ----------------------------------------- | ------------------------ | -------------------------- |
| 该 skill 的 `followup_rate` | < 20%(改造前若为 70%+) | 主指标 |
| 该 skill 触发场景的端到端 RT P50 | 下降 ≥ 2s | 来自少一轮 LLM 调用 |
| 该 skill 的 `user_followup_within_30s` 率 | 不上升 | 用户没追问 = 答案完整 |
| 该 skill 的 `success` 率 | 不下降 | 内联 followup 没引入新失败 |
### 5.2 整体 RT 指标
| 指标 | 基线 | Layer 2 改完 top-3 skill 后目标 |
| ---------------------------------- | ------------------------------------- | -------------------------------- |
| 端到端 RT P50(含 skill 的会话) | 13.4s(单次采样)/ 待补 ≥3 类场景基线 | 下降 2-3s |
| Tool batch P50 size(Layer 3) | 待测 | ≥ 1.3(>30% 调用涉及并发 batch) |
| Skill 总 followup_rate(加权平均) | 待测 | 下降 ≥ 30% |
### 5.3 失败信号 — 什么时候放弃这个方向
**结果指标止损线**:
- Layer 1 数据出来后,**top-5 skill 的加权 followup_rate < 30%** → 减轮空间小,不值得继续 Layer 2
- Layer 2 改完 2 个 skill 后,**端到端 RT P50 下降 < 1s** → 改造方向错(可能 followup 是写操作不该合并),停下复盘
- Layer 3 prompt 改动 2 周后 **batch_size P50 仍 = 1** → 模型不接受并发指导,放弃 Layer 3,只保留 Layer 1+2
**过程指标止损线(前置预警,避免方案"看起来在做、其实没收益")**:
- **Skill 命中率(intended skill vs selected skill)下降 ≥ 5pp** → skill 描述改坏让模型选错 skill。典型场景:改造前用户问 X 总是命中 skill_a,改造后偶尔被路由到 skill_b 但没产生 error(模型用错 skill 但勉强凑出答案),结果指标看起来正常但 followup_rate 反而上升。**衡量方法**:在 telemetry 加 `skill_invocation_pattern` —— 按 user prompt 前 N 个关键词聚类,看每个 cluster 主要触发哪个 skill;改造前后对比顶 1 偏移
- **Skill 内联 followup 失败率 ≥ 5%** → skill 改造引入了原本不存在的失败模式(如内联 `read_file` 处理大文件爆内存)。衡量:`SkillLaunchEvent.success` 改造前后对比
- **Per-skill 用户取消率(Ctrl+C)上升 ≥ 2pp** → skill 输出变慢或变长导致用户失去耐心。衡量:`ToolCallEvent.status === 'cancelled'` 占比
---
## 6. 与 D1/D3 的衔接
### 6.1 与 D1 的关系
Layer 2 改完 top skill 后,**剩余的 followup-heavy skill 才是 D1 `skipLlmRound` 的真正适用场景** — 那些 skill 输出已经完整(不需要 Round 2),且确实是终态查询(Round 3 总结也是浪费)。
执行次序:
1. Layer 1 telemetry 上线 → 1 周数据
2. Layer 2 改造 top 2-3 skill → A/B 2 周
3. Layer 3 prompt 并发 → 实测 1 周
4. **此时**再评估 D1:剩余高频 skill 里有多少是"输出完整 + 终态查询"形态 → 是否值得 2-3d 框架改造
### 6.2 与 D3 的关系
D3(`StreamingState.Summarizing`)是感知层优化,与本方案完全正交。Layer 1-3 减少的是**真实轮数**,D3 减少的是**用户感知等待**。如果 Layer 2 已经把 RT 降到用户可接受的范围,D3 价值下降;反之 D3 可以叠加。
---
## 7. 限制与已知风险
1. **覆盖率受改造范围限制** — 改 10 个 skill 就只覆盖那 10 个的场景。但收益是确定可测有复利的
2. **Skill 内联 followup 可能让单 skill 变重** — 描述膨胀、加载慢、复用度下降。Layer 2 检查清单第 5 条防御
3. **Layer 3 模型可能不听并发指导** — qwen-coder 训练数据偏串行;A/B 数据可能显示 prompt 改动无效,作为已知失败模式
4. **Telemetry 隐私边界** — `SkillFollowupRecord` 不应记录工具参数(已默认从 `ToolCallEvent.function_args` 拿,但要审计 skill_name 是否泄露用户意图)
5. **不适用于子 agent / cron / notification** — 这些路径不走 skill 系统,本方案不覆盖
6. **基线数据单薄** — 沿用 `rt-optimization-design.md` §1.2 的单次采样,Layer 2 落地前需补 ≥3 类场景基线
7. **`logSkillLaunch` 字段扩展会破坏既有 telemetry consumer** — 4 个调用点 + 下游 logger 都要同步改
8. **`qwen-logger.ts:908` `logSkillLaunchEvent` 当前是死代码** — 仓库内无任何调用方,§4.1.1b 已列前置修复
### 7.1 与已有框架机制的边界(不在本方案范围)
仓库已有几条与减轮间接相关的框架机制,**本方案不重新发明,也不替代**:
| 已有机制 | 位置 | 与本方案的关系 |
| ---------------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| `partitionToolCalls` + `runConcurrently`(并发执行) | `coreToolScheduler.ts:775, 2473` | Layer 3 直接复用;本方案不动它 |
| `CONCURRENCY_SAFE_KINDS`(决定哪些工具可并发) | `tools/tools.ts:818` | §3.3.1 已论证现状合理,不扩展 |
| `FileReadCache`(避免重复读同一文件) | `services/fileReadCache.ts` | 间接影响"模型重复读文件"轮次,已生效;本方案不依赖也不增强 |
| `chatCompressionService`(历史压缩) | `services/chatCompressionService.ts` | 与轮次正交(影响单轮成本而非轮数);与 `rt-optimization-design.md` §3.2 fast 路由的 `wouldTriggerCompression` gate 是同一组件 |
列出这些是为了避免"本方案被理解为忽略了已有机制"。
---
## 8. 实施时间线
> **前提:本时间线从 P-1 开始,不能跳过**。P-1 是 §0 验收 Spec 的前置评审,0.5d 工作量但**强制性** — 不通过则不进入 P0。这一约束是为了避免"先写代码再补 spec"的反模式:spec 后置等于把"算成功"的判断推迟到结果出来后,容易出现"为了让指标好看而调整 spec"的偏差(参见 `rt-optimization-design.md` §7 D2 路线的覆辙)。
| Phase | 内容 | 投入 | 产出 | spec 锁定动作 |
| -------- | ---------------------------------------------------------------------- | --------------------- | ------------------------------ | --------------------------------------- |
| **P-1** | spec 前置评审 | 0.5d | §0.1 / §0.3 锁定 | **锁定 §0.1 工程层 spec + §0.3 止损线** |
| **P0** | qwen-logger 链路修复(§4.1.1b 前置) | 0.5d | skill_launch 事件可见性确认 | 验证 §0.1 第 1 条 |
| **P1** | Layer 1 telemetry:补 `prompt_id` 字段 + 离线 SQL | 1-2d | skill ranking 报告 | 验证 §0.1 第 2/3/4 条 |
| **P1.5** | 1 周数据收集 + 基线测量(≥3 类场景 × ≥10 次) | 1w | 决定改哪 2-3 个 skill | **锁定 §0.2 阈值 + 验证 §0.1 第 5 条** |
| **P2** | Layer 2 改造 top-1 skill(PR + A/B) | 0.5-1d 改造 + 2w 观察 | followup_rate ↓、RT P50 ↓ 验证 | **PR 内声明 §0.4 per-skill spec** |
| **P3** | Layer 3 prompt 并发指导 + `batch_size` telemetry(含 §4.3.2 状态传递) | 1-1.5d 改动 + 1w 实测 | batch_size 分布 | 验证 §0.2 第 3 条 |
| **P4** | Layer 2 继续改 top-2 / top-3 skill(并行 P3) | 0.5-1d × N | 累计 RT P50 ↓ | 每 PR 内声明 §0.4 |
| **P5** | 评估 D1 是否还有价值 | 决策会 | 路线图更新 | — |
**关键决策点(对照 §0.3 止损线)**:
- **P-1 末**:§0.1 / §0.3 任一项无法达成共识 → 不进入 P0
- **P1.5 末**:触发 §0.3 结果指标 #1(top-5 加权 followup_rate < 30%)→ 终止方向;否则锁定 §0.2 阈值
- **P2 末**:触发 §0.3 结果指标 #2(top-1 改造后 RT P50 ↓ < 1s)或任一过程指标 → 停下复盘
- **P3 末**:触发 §0.3 结果指标 #3(batch_size P50 仍 = 1)→ 放弃 Layer 3
- **P5**:根据剩余 skill 形态决定 D1 ROI
---
## 9. 关键代码位置
| 文件 | 关键符号 | 位置 |
| -------------------------------------------------------- | ------------------------------------------------------------- | --------------------------------- |
| `packages/core/src/telemetry/types.ts` | `ToolCallEvent`(含 `prompt_id` / `duration_ms`) | L170 |
| `packages/core/src/telemetry/types.ts` | `SkillLaunchEvent`(需补 `prompt_id`) | L896 |
| `packages/core/src/telemetry/loggers.ts` | `logToolCall` | L220 |
| `packages/core/src/telemetry/loggers.ts` | `logSkillLaunch`(走 OTLP;缺 qwen-logger 转发) | L958 |
| `packages/core/src/telemetry/loggers.ts` | `logToolCall`(双路径:OTLP + qwen-logger,作为修复样板) | L220, L230 |
| `packages/core/src/telemetry/qwen-logger/qwen-logger.ts` | `logSkillLaunchEvent`(**当前死代码**,§4.1.1b 前置修复目标) | L908 |
| `packages/core/src/core/coreToolScheduler.ts` | `partitionToolCalls` | L775 |
| `packages/core/src/core/coreToolScheduler.ts` | `runConcurrently` / batch 调度 | L2456, L2473 |
| `packages/core/src/core/coreToolScheduler.ts` | `logToolCall` 调用点(batch_size 状态传递终点) | L3163 |
| `packages/core/src/services/fileReadCache.ts` | `FileReadCache`(已有,影响重复读取轮次) | L135 |
| `packages/core/src/tools/skill.ts` | `SkillTool` + 4 个 `logSkillLaunch` 调用点 | L386, L399, L426, L482 |
| `packages/core/src/skills/skill-manager.ts` | `SkillManager`(skill 注册/加载) | 全文件 |
| `packages/core/src/skills/skill-load.ts` | skill 描述加载(输出契约改动入口) | 全文件 |
| `packages/core/src/tools/tools.ts` | `Kind` + `CONCURRENCY_SAFE_KINDS` | L793, L818 |
| `packages/core/src/core/coreToolScheduler.ts` | `partitionToolCalls` + `runConcurrently`(已有并发基础设施) | 见 rt-optimization-design.md §5.7 |
| `packages/core/src/core/prompts.ts` | `# Final Reminder` 段(Layer 3 加并发指导处) | L396 |
| `.qwen/skills/` | 各 skill 定义目录(Layer 2 改造对象) | 目录 |

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,878 @@
# Telemetry: Outbound Trace Context & Session ID Header Propagation
> 配套 issue: [#4384](https://github.com/QwenLM/qwen-code/issues/4384)
> 父 issue: [#3731](https://github.com/QwenLM/qwen-code/issues/3731) (P3 deeper observability)
> 前置 PR: #4367 (resource attributes — merged 2026-05-21, commit `64401e1`)
> 基于 2026-05-21 对 qwen-code main 分支 + 直接验证的 claude-code 源码
## 修订历史
| 修订 | 日期 | 触发 | 摘要 |
| ---- | ---------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| R1 | 2026-05-21 | 初稿 | 全广播:所有出站 LLM 请求都带 `X-Qwen-Code-Session-Id` + `traceparent` |
| R2 | 2026-05-22 | wenshao R2/R3 review | 边界安全:URL normalize、port matching、quote 对齐、staticCorrelationHeaders try/catch、host:port fallback strip |
| R3 | 2026-05-23 | LaZzyMan REQUEST_CHANGES | **重大语义改动**:`X-Qwen-Code-Session-Id` 默认作用域收窄到 first-party(Alibaba/DashScope)host 白名单。详见 §11 |
| R4 | 2026-05-25 | LaZzyMan round-8 follow-up (scope conflation) | **PR scope 大幅收窄**:本 PR 仅保留 client HTTP span + OTLP loop guard;`traceparent` 默认 off(NoopTextMapPropagator);新增 `outboundCorrelation.*` 顶级 namespace 放安全相关 toggle;R3 落地的整套 `X-Qwen-Code-Session-Id` 机器**移除本 PR**,搬到独立 follow-up PR。详见 §12 |
**特别提示**:阅读 §3.1(目标)/ §3.2(非目标)/ §4.3(Part B 设计)/ §4.4(配置 schema 影响)/ §5(文件改动清单)/ §9(与 claude-code 对比)/ §10(未来工作)/ §11(R3 host-allowlist scoping)时,请同时参考 §12 —— **R4 修订让 R1-R3 关于"本 PR 同时落地 traceparent + session id header"的论断不再成立**:本 PR 现仅为 telemetry observability + 独立的 outbound trace-context toggle,所有 outbound correlation header 工作(包括 R3 的 host allowlist)整体搬到独立 follow-up PR。R3 工作代码本身没浪费,挪到 follow-up PR 即可复用。
## 1. 背景
#4367 解决了**emitted telemetry 上的 attribute 与 cardinality**(操作员能给 span/log/metric 打 `user.id`/`tenant.id` 这类标签)。但有一类东西它没碰:**outbound LLM 请求的 HTTP header**。今天 qwen-code 发往 DashScope / OpenAI / Gemini / Anthropic 的请求**完全不带任何 cross-process correlation header**——既没有 W3C `traceparent`,也没有 session id。
后果:
1. trace context 在 qwen-code 进程边界断开。若模型服务(如 ARMS Tracing 接入的 DashScope)本身有 OTel instrumentation,它产生的 span 与 qwen-code 的 trace 彼此独立,端到端 trace tree 不存在。
2. 没有 session id 在 wire 上。后端要把 qwen-code 的 metric/log 与服务端日志关联,需要离线匹配 trace id 或时间戳,远不如直接读 header 简单。
3. 本地 trace 缺一层 client-side HTTP span。今天只能看 `api.generateContent` 的总耗时,看不到网络 TTFB / 响应体大小 / 重试次数。
## 2. 现状
### 2.1 仅启用了 `HttpInstrumentation`
`packages/core/src/telemetry/sdk.ts:330`:
```ts
instrumentations: [new HttpInstrumentation()],
```
`HttpInstrumentation` 只 hook Node 内建的 `http`/`https` 模块,**不**覆盖 `globalThis.fetch` / undici 路径。
### 2.2 两套 LLM SDK 都走 fetch / undici
| SDK | HTTP 实现 | `HttpInstrumentation` 是否覆盖 |
| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| `openai@5.11.0` | `globalThis.fetch`(Node 18+ 即 undici)。证据:`node_modules/openai/internal/shims.mjs` 报错 `'fetch' is not defined as a global` | ❌ |
| `@google/genai@1.30.0` | `globalThis.fetch` + `new Headers()`。证据:`dist/node/index.mjs` 内的 `new Headers()` 调用 | ❌ |
| `@anthropic-ai/sdk`(anthropicContentGenerator) | 同样基于 fetch | ❌ |
### 2.3 代码库零 manual propagation
```
grep -rn "propagation\.\|setGlobalPropagator\|W3CTraceContext\|traceparent" packages/core/src --include="*.ts" | grep -v "\.test\."
```
→ 空。没有任何 `propagation.inject()` 调用,没有手动 traceparent 注入。
### 2.4 各 provider 的 `defaultHeaders` 现状
OpenAI 家族(用 `openai` SDK):
所有 OpenAI 子 provider 都 `extends DefaultOpenAICompatibleProvider`。**buildHeaders override 行为分两类**(已 grep audit 验证):
| Provider | 文件 | `buildHeaders()` 行为 | 影响 |
| ---------- | ---------------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------- |
| 基类 | `default.ts:63-74` | 提供 `{ 'User-Agent' }` + customHeaders | 改这里 |
| DashScope | `dashscope.ts:110-124` | **`override` 但不 call `super`**——返回 `User-Agent` + `X-DashScope-*` 全新对象 | **必须单独改这里**,否则 correlation header 丢 |
| OpenRouter | `openrouter.ts:20-30` | `override` 但**先 `const baseHeaders = super.buildHeaders()`** | 改基类自动继承 ✅ |
| DeepSeek | `deepseek.ts` | 不 override `buildHeaders`(只 override `buildRequest` / `getDefaultGenerationConfig`) | 改基类自动继承 ✅ |
| Minimax | `minimax.ts` | 同 deepseek | 自动继承 ✅ |
| Mistral | `mistral.ts` | 同 deepseek | 自动继承 ✅ |
| ModelScope | `modelscope.ts` | 同 deepseek | 自动继承 ✅ |
→ **OpenAI 家族需要触动 2 个文件**:`default.ts` 和 `dashscope.ts`。其余 5 个自动继承。
Google Gemini:
| Provider | 文件 | 头注入路径 |
| -------- | ------------------------------ | -------------------------------------------------------------- |
| Gemini | `geminiContentGenerator.ts:59` | `new GoogleGenAI({ httpOptions: { headers } })` — SDK 原生支持 |
Anthropic:
| Provider | 文件 | 头注入路径 |
| --------- | ------------------------------------------------------------------------------------------------------ | ---------------- |
| Anthropic | `anthropicContentGenerator.ts:177` (`buildHeaders`) + `:212` (`defaultHeaders` arg to `new Anthropic`) | `defaultHeaders` |
**总计 4 个 SDK 构造点**需要注入 session id header。所有 SDK 都已支持 `defaultHeaders` / `httpOptions.headers`,无需 fetch wrapper。
### 2.5 已有的 proxy 与 fetch 配置
`provider/default.ts:87-89`:
```ts
const runtimeOptions = buildRuntimeFetchOptions(
'openai',
this.cliConfig.getProxy(),
);
```
`buildRuntimeFetchOptions` 在用户配 proxy 时返回 `{ fetch: customFetch }` 或类似,触发 `setGlobalDispatcher(new ProxyAgent(...))`(见 `config.ts:1126-1128`)。**undici 全局 dispatcher 模式与 `UndiciInstrumentation` 兼容**——它通过 monkey-patch `globalThis.fetch` 与 undici 的 channel diagnostics 协作,不依赖具体 dispatcher。
## 3. 目标 / 非目标
### 3.1 目标
- 所有 outbound LLM 请求自动带 W3C `traceparent` header(OTel SDK 默认的 `W3CTraceContextPropagator`)
- ~~所有~~ 出站 LLM 请求带 `X-Qwen-Code-Session-Id` header(claude-code 同款产品命名空间) — **R3 修订**:默认仅向 first-party (Alibaba/DashScope) host 注入,第三方 provider 默认不发;详见 §11
- 自动避免对 OTLP exporter endpoint 自身的 trace(feedback loop)
- 给 LLM 请求加一层精确的 client span(网络耗时 vs 模型耗时分离)
- 覆盖 4 个 provider 构造点:OpenAI 基类、DashScope override、Gemini、Anthropic
- streaming 请求 / proxy 模式 / 重试场景全部不退化
- 与 #4367 的设计哲学一致:通过 `defaultHeaders` 这种 SDK-native 选项 — **R1 修订**:因 staleness 问题转用 fetch wrapper;**R3 修订**:fetch wrapper 内再叠加 host gate
### 3.2 非目标
- **`baggage` header**:标准 SDK 已支持,但 qwen-code 没调 `propagation.setBaggage()`,默认不会发送。本设计不主动开启。
- **subprocess `TRACEPARENT` env var 继承**:claude-code 给 Bash/PowerShell 子进程注入 `TRACEPARENT`。qwen-code 的 `BashTool` 没做。是独立 follow-up sub-issue。
- **inbound `TRACEPARENT` / `TRACESTATE` 读取**:claude-code 的 `-p` 模式和 Agent SDK 从 env 读 traceparent 接续父进程 trace。qwen-code 没做。独立 follow-up。
- **`X-Qwen-Code-Request-Id`**:claude-code 有 `x-client-request-id`,对超时容错 correlation 有用。本期不做,可作为下一个 sub-issue。
- **自定义 propagator(B3 / Jaeger / X-Ray)**:默认 W3C 已覆盖 99% 场景。可作为 future config option。
- ~~**per-endpoint 选择性注入**:claude-code 对第三方 endpoint (Bedrock / Vertex) 不发 traceparent;qwen-code 没有第三方区分需要,统一发即可。~~ — **R3 修订**:此论断已被推翻。LaZzyMan review 指出 qwen-code 是开源 CLI 连接多个第三方 provider(OpenAI / Anthropic / OpenRouter / 等),claude-code 的 first-party→first-party 类比不适用;session id header 必须按 host 区分。详见 §11。`traceparent` 仍按 R1 设计全注入(OTel 标准 header,且 trace id 是 `sha256(sessionId)` 哈希值),可作为独立 follow-up 加 per-destination toggle(`telemetry.propagateTraceContext`)。
## 4. 设计
### 4.1 总体分层
```
┌─ qwen-code process ────────────────────────────────────────────┐
│ │
│ ┌─ session-tracing.ts ─┐ │
│ │ active span ctx │ │
│ └──────┬───────────────┘ │
│ │ │
│ ▼ │
│ ┌─ propagation.inject() (called by undici instrumentation) ─┐│
│ │ writes `traceparent: 00-<traceId>-<spanId>-01` to headers ││
│ └─────────────────────────────────────────────────────────────┘│
│ │ │
│ ┌──────▼──────────────────────────────────────────────────┐ │
│ │ fetch() — undici, instrumented │ │
│ │ creates HTTP client span │ │
│ │ injects traceparent into request headers │ │
│ │ (skipped via ignoreRequestHook if endpoint is OTLP) │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │
│ │ ┌─ defaultHeaders (per SDK constructor) ───────┐ │
│ │ │ { 'X-Qwen-Code-Session-Id': sessionId, ... } │ │
│ └───┴────────────────────────────────────────────────┘ │
│ │ │
└─────────────┼──────────────────────────────────────────────────┘
│
▼ outbound HTTP
POST /v1/chat/completions
traceparent: 00-...
X-Qwen-Code-Session-Id: ...
... (existing User-Agent, X-DashScope-*, etc.)
```
两条注入路径独立、互不依赖:
| Layer | 何时注入 | 由谁注入 |
| ------------------------ | ------------------------------------- | ------------------------------------------------------------- |
| `traceparent` | 每次 fetch 调用时 | `UndiciInstrumentation` 自动(来自 OTel SDK 默认 propagator) |
| `X-Qwen-Code-Session-Id` | SDK 构造时一次性写入 `defaultHeaders` | 应用代码 |
### 4.2 Part A — `traceparent` via undici instrumentation
**改动点**:`packages/core/src/telemetry/sdk.ts`
```ts
import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
// ...
const otlpUrls = [
config.getTelemetryOtlpEndpoint(),
config.getTelemetryOtlpTracesEndpoint(),
config.getTelemetryOtlpLogsEndpoint(),
config.getTelemetryOtlpMetricsEndpoint(),
]
.filter((u): u is string => !!u)
.map((u) => u.replace(/\/$/, ''));
instrumentations: [
new HttpInstrumentation(),
new UndiciInstrumentation({
ignoreRequestHook: (request) => {
// request.origin = "https://collector:4318", request.path = "/v1/traces"
const url = `${request.origin}${request.path}`;
return otlpUrls.some((e) => url.startsWith(e));
},
}),
],
```
#### 为什么 `ignoreRequestHook` 必须
OTel SDK 自己用 fetch 把数据 POST 到 OTLP collector。如果不跳,UndiciInstrumentation 会给"上报数据"的请求也建一个 span → 这个新 span 会被再次上报 → 无限循环 / 巨量噪声。每个 OTel 项目都踩过这个坑,OTel 文档明确推荐这种 hook。
#### 默认 propagator
OTel SDK `NodeSDK` 不传 `textMapPropagator` 时默认是 `CompositePropagator([W3CTraceContextPropagator, W3CBaggagePropagator])`。无需显式设置。
#### `traceparent` 格式
```
traceparent: 00-<32hex traceId>-<16hex spanId>-<01 sampled | 00 not sampled>
─┬─ ─┬─
version (固定 00) flags
```
固定 55 bytes,无 padding。
#### `tracestate` 与 `baggage`
- `tracestate`: 上游传过来才续传;自己 inject 不会主动加(OTel SDK 行为)。
- `baggage`: 仅当 `propagation.setBaggage(ctx, ...)` 被调用过才有。qwen-code 不调,所以不会发送。
### 4.3 Part B — `X-Qwen-Code-Session-Id` via fetch wrapper(OpenAI / Anthropic)+ static headers(Gemini)
> **R3 修订**:以下设计描述的是 fetch wrapper 的 staleness 解决和 4 个 provider 集成点 — 这些都保留。但 wrapper 内部增加了一道 host allowlist gate,`staticCorrelationHeaders` 也加了 `destinationUrl` 参数。带 host gate 的最新实现代码与 default allowlist 见 §11。
#### Critical:staleness 问题与方案选择
天真做法(`defaultHeaders` 直接 bake-in `getSessionId()`)有**真 bug**:
1. `pipeline.ts:60` 在 contentGenerator 构造时一次性 `this.client = this.config.provider.buildClient()`,SDK client 的 `defaultHeaders` 在那一刻 capture 当时的 session id
2. `config.ts:1850` 的 session reset(用户 `/clear` 时触发)更新 `this.sessionId` 并 `refreshSessionContext()`,但**不重建 contentGenerator**
3. 后续 LLM 调用仍走旧 client → wire header 仍是旧 session id → 后端 correlation 错位
→ 必须读取 session id **per-request**,不能 bake at构造时。
#### 方案
```
┌─ fetch 支持 ─┐ 方案
OpenAI SDK │ ✅ │ fetch wrapper (per-request 读 sessionId) ✅
Anthropic SDK │ ✅ │ fetch wrapper ✅
@google/genai SDK │ ❌ │ static httpOptions.headers + 接受 staleness
└──────────────┘
```
`@google/genai`'s `HttpOptions` interface 不支持 `fetch`(已 grep `node_modules/@google/genai/dist/genai.d.ts` 验证:只有 `baseUrl`/`apiVersion`/`headers`/`timeout`/`extraParams`)。所以 Gemini 走 static headers,与 OpenAI/Anthropic 不一致——这是 **known limitation**,见 §8.6。
#### 集中辅助函数(per-request fetch wrapper)
新文件 `packages/core/src/telemetry/llm-correlation-fetch.ts`:
```ts
import type { Config } from '../config/config.js';
/**
* Wrap a fetch implementation so every outbound request gets correlation
* headers (`X-Qwen-Code-Session-Id`) populated from the **current** session
* id, not the value captured when the SDK client was constructed.
*
* Matches claude-code's pattern (src/services/api/client.ts:370-390 —
* `buildFetch()`). Per-request injection is necessary because `/clear`
* resets the session id mid-process; SDK clients (and their static
* `defaultHeaders`) are NOT recreated on reset.
*
* Caller responsible for choosing the base fetch — usually
* `runtimeOptions?.fetch ?? globalThis.fetch` so proxy-aware fetch is
* preserved when ProxyAgent is in use.
*
* If telemetry is disabled, returns baseFetch unchanged (no correlation
* header is added, matching the privacy stance of §3.1).
*/
export function wrapFetchWithCorrelation(
baseFetch: typeof fetch,
config: Config,
): typeof fetch {
return async function correlationFetch(input, init) {
if (!config.getTelemetryEnabled()) {
return baseFetch(input, init);
}
const sid = config.getSessionId();
if (!sid) {
// Defensive: empty header value is rejected by some HTTP middleware.
// Skip injection rather than send `X-Qwen-Code-Session-Id: `.
return baseFetch(input, init);
}
const headers = new Headers(init?.headers);
headers.set('X-Qwen-Code-Session-Id', sid);
return baseFetch(input, { ...init, headers });
};
}
```
Companion helper for the SDKs that can only take static headers (Gemini):
```ts
/**
* Static correlation headers. Captures the session id at call time —
* **subject to staleness** if the host SDK keeps these headers in a
* captured-at-construction slot (e.g. `@google/genai`'s `httpOptions.headers`).
* Prefer `wrapFetchWithCorrelation` whenever the SDK exposes a `fetch` hook.
*/
export function staticCorrelationHeaders(
config: Config,
): Record<string, string> {
if (!config.getTelemetryEnabled()) return {};
return { 'X-Qwen-Code-Session-Id': config.getSessionId() };
}
```
#### 集成点 1: `provider/default.ts` (OpenAI 基类)
`buildClient()` 改动——compose 现有 `runtimeOptions.fetch`(proxy)与我们的 wrapper:
```ts
buildClient(): OpenAI {
// ... existing ...
const runtimeOptions = buildRuntimeFetchOptions('openai', this.cliConfig.getProxy());
const baseFetch =
(runtimeOptions as { fetch?: typeof fetch } | undefined)?.fetch
?? globalThis.fetch;
return new OpenAI({
apiKey,
baseURL: baseUrl,
timeout,
maxRetries,
defaultHeaders,
...(runtimeOptions || {}),
// After spread, override `fetch` so our correlation wrapper wraps the
// proxy-aware fetch (or globalThis.fetch when no proxy).
fetch: wrapFetchWithCorrelation(baseFetch, this.cliConfig),
});
}
```
`buildHeaders()` itself unchanged.
#### 集成点 2: `provider/dashscope.ts` (override)
`buildClient()` 同样的 compose 模式(它本来就 override buildClient)。`buildHeaders()` 不动。
#### 集成点 3: `geminiContentGenerator/index.ts` (factory, NOT 构造器)
**修正先前设计的过度声明**:`geminiContentGenerator.ts` 构造器**不需要**改签名。`index.ts:48` 的 factory 函数已经接收 `gcConfig: Config`(line 33 已经在用 `gcConfig?.getUsageStatisticsEnabled()`),只需要在 factory 里把 correlation 静态 headers merge 进 `httpOptions.headers`:
```ts
// geminiContentGenerator/index.ts
let headers: Record<string, string> = { ...baseHeaders };
if (gcConfig?.getUsageStatisticsEnabled()) {
// ... existing x-gemini-api-privileged-user-id ...
}
headers = { ...headers, ...staticCorrelationHeaders(gcConfig) }; // ← 新增
const httpOptions = config.baseUrl
? { headers, baseUrl: config.baseUrl }
: { headers };
// new GeminiContentGenerator(...) unchanged
```
零 signature 改动。
#### 集成点 4: `anthropicContentGenerator.ts`
Anthropic SDK 同样接受 custom `fetch`(已经在用 `buildRuntimeFetchOptions`)。把 `buildClient` 路径里那个 fetch wrap 一下,方式同 OpenAI default.ts。`buildHeaders` 不变。
#### 优先级链
不变:用户的 `customHeaders` 在 `defaultHeaders` merge 中仍然赢(见 §8.2 spoofing 讨论)。fetch wrapper 注入的 `X-Qwen-Code-Session-Id` 在 SDK 的 headers list 之**后**追加到最终 `Headers` 对象上——以 Node `Headers.set()` 的语义,等于覆盖任何之前同名的(包括 user 的 customHeaders 里写的同名 header)。
**对 OpenAI/Anthropic(fetch wrapper 路径)**:correlation > customHeaders > SDK defaults。
**对 Gemini(static headers 路径)**:customHeaders > correlation > SDK defaults(沿用既有 spread 顺序)。
差异是 fetch wrapper 路径下 spoofing 不再可能(fetch wrapper 在 SDK headers 之后跑)。这是 **bug 修复的副产品**,并非有意收紧——但更安全。要在 §8.2 明示。
### 4.4 配置 schema 影响
~~**几乎为零**。本设计不引入新 setting~~ — **R3 修订**:引入了一项新 setting `telemetry.sessionIdHeaderHosts: string[]`,用于覆盖默认的 first-party host 白名单。schema 项已加入 `packages/cli/src/config/settingsSchema.ts`,描述与 override 语法(`["*"]` 恢复广播 / `[]` 全关 / 自定义数组)见 §11。原文以下描述仅适用于 R3 之前:
- `traceparent` 注入由 telemetry enabled 触发(已有 toggle)
- `X-Qwen-Code-Session-Id` 注入也由 telemetry enabled 触发
- `ignoreRequestHook` 的 OTLP url 已经从现有 config 读
未来可以加的 setting(**out of scope**):
- `telemetry.outboundCorrelationHeader`: 自定义 header name(默认 `X-Qwen-Code-Session-Id`)
- `telemetry.outboundPropagationDisabled`: 全局关闭(如果 LLM 服务对未知 header 严格)
- ~~per-destination header scope toggle~~ — **R3 已落地**,见 §11
## 5. 文件改动清单
| 文件 | 改动类型 | 说明 |
| ------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `packages/core/package.json` | 加依赖 | `@opentelemetry/instrumentation-undici` |
| `packages/core/src/telemetry/sdk.ts` | 修改 | +`UndiciInstrumentation` + `ignoreRequestHook` |
| `packages/core/src/telemetry/llm-correlation-fetch.ts` | 新文件 | `wrapFetchWithCorrelation()` (OpenAI/Anthropic) + `staticCorrelationHeaders()` (Gemini fallback) |
| `packages/core/src/core/openaiContentGenerator/provider/default.ts` | 修改 | `buildClient()` 在 `new OpenAI({...})` 里加 `fetch: wrapFetchWithCorrelation(baseFetch, cliConfig)` |
| `packages/core/src/core/openaiContentGenerator/provider/dashscope.ts` | 修改 | 同上(override `buildClient`) |
| `packages/core/src/core/geminiContentGenerator/index.ts` | 修改 | factory 函数里 merge `staticCorrelationHeaders(gcConfig)` 进 `httpOptions.headers`(**caller 已有 Config,零 signature 改动** — 修正之前的 over-specification) |
| `packages/core/src/core/anthropicContentGenerator/anthropicContentGenerator.ts` | 修改 | `buildClient` 路径下用 `wrapFetchWithCorrelation` 包 SDK 的 `fetch` option |
**显式 audited 但无需改动**(避免 reviewer 怀疑漏路径):
- `packages/core/src/qwen/qwenContentGenerator.ts` — `extends OpenAIContentGenerator`,用 `DashScopeOpenAICompatibleProvider`,**自动继承 dashscope.ts 的 buildClient 改动**。所有 Qwen OAuth 流程同样受益。
- `packages/core/src/core/loggingContentGenerator/loggingContentGenerator.ts` — wrapper 模式,不构造 SDK client(它包装其他 contentGenerator 做 telemetry logging),无需改动。
- `packages/core/src/core/contentGenerator.ts` — factory 入口,不持有 client。
| `packages/core/src/telemetry/sdk.test.ts` | 修改 | 加 undici instrumentation 注册 + ignoreRequestHook 测试 |
| `packages/core/src/telemetry/llm-correlation-fetch.test.ts` | 新文件 | telemetry-on/off 行为单测 + per-request 读 sessionId 验证(critical:session reset 后 wrapped fetch 读到新 id) |
| 各 provider 的 `*.test.ts` | 修改 | 断言 SDK 构造时 `fetch` option 是 wrapped 版本(OpenAI/Anthropic);断言 Gemini 构造时 `httpOptions.headers` 含 `X-Qwen-Code-Session-Id` |
| `docs/developers/development/telemetry.md` | 修改 | 新增 "Trace context & session correlation propagation" 段 |
| `docs/design/telemetry-outbound-propagation-design.md` | 本文件 | 设计文档 |
## 6. 分 PR 拆分
按 review 友好度分两个 PR(也可以合一,规模允许):
### PR 1 — `traceparent` 自动注入(structural)
- 加 `@opentelemetry/instrumentation-undici` 依赖
- `sdk.ts` 加 `UndiciInstrumentation` + `ignoreRequestHook`
- 测试:SDK 注册、OTLP endpoint 不被 trace
- 文档片段
**风险**:低。Additive。已有 client span 是 net 增益,不会改变现有 span 结构。
### PR 2 — `X-Qwen-Code-Session-Id` header(结合 helper 函数)
- 新文件 `llm-correlation-headers.ts`
- 4 个 provider 集成
- 测试:每个 provider 断言 header 存在;telemetry-off 时不发
- 文档片段
**风险**:低-中。要小心 `geminiContentGenerator` 构造器签名扩展可能波及调用方。
### PR 3(可选) — Docs + E2E verify
- 完善 `telemetry.md` 段落
- 加 E2E verify script(复用 `/tmp/verify-telemetry-pr-4367.mjs` 模式):实际跑 fetch + 抓 header
也可以合并到 PR 2 里。
### 顺序偏好
PR 1 和 PR 2 技术上**互相独立**——不共享代码。但**推荐 PR 1 先合**:
- `traceparent` 是 OTel **标准** header,任何 OTel-aware collector / 后端立刻识别 → 用户立即获益
- `X-Qwen-Code-Session-Id` 是**产品自定义** header,需要后端配置识别才有价值 → 价值滞后
- 万一 PR 2 review 周期长,PR 1 已经把 cross-process trace 跑通了
- PR 1 是 additive structural(低风险),适合先建立信心
## 7. 测试计划
### 7.1 `sdk.ts` 单测
- ✅ `UndiciInstrumentation` 在 `NodeSDK` 的 `instrumentations` 中存在
- ✅ `ignoreRequestHook` 对 `https://collector:4318/v1/traces` 返回 true
- ✅ `ignoreRequestHook` 对 `https://dashscope.aliyuncs.com/...` 返回 false
- ✅ trailing slash 与无 trailing slash 都正确匹配
### 7.2 `llm-correlation-fetch.ts` 单测
**`wrapFetchWithCorrelation`**:
| 场景 | 期望 |
| ------------------------------------------------------- | ---------------------------------------------------------------------- |
| `getTelemetryEnabled() === false` | wrapped fetch = baseFetch(不加任何 header) |
| `getTelemetryEnabled() === true`, sessionId = "abc-123" | wrapped fetch 发出的 init.headers 含 `X-Qwen-Code-Session-Id: abc-123` |
| `init.headers` 已有 `X-Qwen-Code-Session-Id: spoof` | wrapper 后覆盖为真 sessionId(fetch wrapper 路径不允许 spoof,§8.1) |
| **session reset 后 wrapped fetch 被再次调用** | **读取新 sessionId**(regression guard for staleness fix) |
| baseFetch reject | wrapper 透传 reject 不吞 |
**`staticCorrelationHeaders`**(Gemini path):
| 场景 | 期望返回 |
| ------------------------------------------------------- | ---------------------------------------------------------------- |
| `getTelemetryEnabled() === false` | `{}` |
| `getTelemetryEnabled() === true`, sessionId = "abc-123" | `{ 'X-Qwen-Code-Session-Id': 'abc-123' }` |
| sessionId 中含 unicode(`會話-1`) | 原样返回——HTTP header value 由 SDK 负责编码 |
| sessionId 为空字符串 | `{ 'X-Qwen-Code-Session-Id': '' }`——业务 invariant,不在此层校验 |
### 7.3 Per-provider 集成测试
每个 provider 的 `buildHeaders()` / 构造测试加:
```ts
it('includes X-Qwen-Code-Session-Id when telemetry enabled', () => {
const config = makeFakeConfig({
sessionId: 'sess-xyz',
telemetry: { enabled: true },
});
const provider = new DefaultProvider(genConfig, config);
expect(provider.buildHeaders()['X-Qwen-Code-Session-Id']).toBe('sess-xyz');
});
it('omits X-Qwen-Code-Session-Id when telemetry disabled', () => {
const config = makeFakeConfig({ telemetry: { enabled: false } });
const provider = new DefaultProvider(genConfig, config);
expect(provider.buildHeaders()).not.toHaveProperty('X-Qwen-Code-Session-Id');
});
```
### 7.4 E2E verification(tmux + local HTTP server)
⚠️ **不要** mock `globalThis.fetch` 来抓 header:`UndiciInstrumentation` 通过 undici 的 diagnostics channel hook,monkey-patching globalThis.fetch 可能完全 bypass instrumentation(取决于 patch 顺序),让 `traceparent` 注入测不到。**正确做法是起 local HTTP server**,让 SDK 真发请求,server 端记录收到的 headers。
写一个仿 `/tmp/verify-telemetry-pr-4367.mjs` 的脚本:
1. `http.createServer((req, res) => { capturedHeaders.push(req.headers); res.end('{}') })` 起本地 server
2. 启 telemetry + outfile + 把 OpenAI SDK 的 `baseURL` 指向 `http://127.0.0.1:<port>`(或者用 mock provider 让 SDK 真发 fetch)
3. 触发一次 `client.chat.completions.create(...)`(要带最小可解析的 mock 响应,否则 SDK 解析报错——本地 server 返回合法但空的 OpenAI 响应即可)
4. 断言 `capturedHeaders[0]` 含 `traceparent: 00-...` 和 `X-Qwen-Code-Session-Id: <sessionId>`
5. 另起一个 OTLP collector mock 在 different port,验证给它发的 OTLP 上报**不**触发 `traceparent` 注入(验证 `ignoreRequestHook`)
6. **额外:staleness 验证** — emit request 1 → call `config.resetSession(...)` → emit request 2 → 断言 request 2 的 `X-Qwen-Code-Session-Id` 是新 session id(**这是 #1 fix 的关键回归测试**)
### 7.5 回归保护
- streaming chat completion 的 fetch(带 `stream: true`)仍正常关闭——`UndiciInstrumentation` 历史上对 streaming response 的 span lifecycle 有过 bug,**实施时需要实际跑一次 streaming completion 端到端验证 client span 正常 end + 无 leaked span + 流不被截断**;不假设具体版本号已修
- proxy mode (`ProxyAgent`) 与 instrumentation 同时启用——`ignoreRequestHook` 仍按 endpoint 字符串匹配,proxy 不影响
- 重试(`maxRetries`)下每次重试都得到独立 client span,但都共享同一个 `traceparent` parent(理想是 retry 作为同一个父 span 下多个 child span — 这部分由 SDK 行为决定,本设计不强制)
## 8. 边界 / 边角
### 8.1 customHeaders override 与 spoofing 的不一致行为
不同 provider 路径的 spoofing 表面**不同**(设计后果,非原意收紧):
| Provider 路径 | spoofing 可能? | 原因 |
| --------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------- |
| OpenAI / Anthropic (fetch wrapper 路径) | ❌ 不能 spoof | fetch wrapper 在 SDK headers list 之后 `headers.set('X-Qwen-Code-Session-Id', ...)`,覆盖 user customHeaders 的同名 |
| Gemini (static headers 路径) | ✅ 可 spoof | merge 顺序 `{ ...baseHeaders, ...correlationHeaders, ...customHeaders }`——customHeaders 最后赢 |
claude-code 同样使用 fetch wrapper 路径,行为与 OpenAI/Anthropic 一致(spoofing 不能)。这是修 staleness bug 的副产品,不是原本要做的事。
**不打算"对齐"两条路径**——Gemini 路径的行为是 SDK 限制(没有 `fetch` hook)导致的,反向把 OpenAI 也降级到 static 不合理。
Session id spoofing 不是真威胁(用户控制本地,可以直接改 source code)。文档里要明示这个差异,避免 reviewer 看到 fetch wrapper 路径无法 spoof 时质疑 customHeaders 优先级。
### 8.2 OTLP collector URL 匹配的两类 edge case
#### (a) Auth token in URL
如果用户 OTLP endpoint 形如 `https://collector/path?token=secret`,`ignoreRequestHook` 的 `url.startsWith(e)` 比对应包含 query string。但 undici 给的 `request.path` 只到 path(不含 query),所以比较时 `e` 也只用到 path 部分。为安全起见,剥掉 query:
```ts
const otlpUrls = [...]
.map((u) => u.replace(/\?.*$/, '').replace(/\/$/, ''));
```
#### (b) startsWith 跨 hostname 边界的理论 false positive
若 `e = "http://collector"`(无 port),来路 url = `http://collector-fake/v1/traces` 会被 startsWith 错误匹配。
**实际触发概率极低**:
- OTLP endpoint 几乎总带 port(4317 gRPC / 4318 HTTP),`http://collector:4318` 形态后 `-fake` 这种延伸不可能(port 后跟的是 `/`)
- 用户配 endpoint 不带 port 是配置错误,本来 SDK 就要默认 fallback
**如果想 harden**:解析 URL origin + path 分别比较,不用裸 startsWith:
```ts
const parsed = otlpUrls.map((u) => new URL(u));
return parsed.some(
(e) =>
`${request.origin}` === e.origin && request.path.startsWith(e.pathname),
);
```
本期不做——开销没必要,false positive 实际触发不到。
### 8.3 Vertex AI 模式的 Gemini
`@google/genai` 支持 `vertexai: true` 模式(用 GCP 凭据走 Vertex 端点而非 generative ai endpoint)。两种模式都走 fetch,所以 instrumentation 都覆盖。`httpOptions.headers` 在两种模式下都有效。
### 8.4 Anthropic SDK 已有 `defaultHeaders` 逻辑
`anthropicContentGenerator.ts:177` 已经在调 `buildHeaders()` 然后传给 `new Anthropic({ defaultHeaders })`。但 staleness 同样适用——本设计改用 `fetch` wrapper 路径(与 OpenAI 一致)。
### 8.5 SDK 与 fetch 之间的 trailer header
`openai` SDK 在 streaming 时可能用 `Transfer-Encoding: chunked` 和 trailer headers。这些都不影响 request-time 的 `traceparent` / `X-Qwen-Code-Session-Id` 注入——它们都是请求头,发出时一次性写入。
### 8.6 ⚠️ Known limitation: Gemini 的 session id 在 `/clear` 后 stale
由于 `@google/genai` SDK 不支持 `fetch` hook(`HttpOptions` 接口只有 `baseUrl`/`apiVersion`/`headers`/`timeout`/`extraParams`),Gemini provider 走 static `httpOptions.headers` 路径——session id 在 SDK 构造时 capture,**`/clear` 触发 session reset 后不刷新**。
**实际影响范围**:
- 用户启动 qwen-code → `/clear` → 用 Gemini 模型 → wire 上的 `X-Qwen-Code-Session-Id` 是旧 session id
- 后端 correlation 错位(trace id 和 log 已正确切换到新 session,但 wire header 滞后)
**为什么不修**(本期):
- OpenAI / Anthropic 路径**没有这个 bug**(fetch wrapper 路径 per-request 读 session id)
- Gemini fix path 有几个选项,全部超出本期 scope(见下)
**Future fix path 选项**(按推荐顺序):
| 选项 | 描述 | 代价 |
| --------------------------------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- |
| **A. Lazy invalidate** ★ 推荐 | session reset 时只 mark contentGenerator dirty,下次 LLM 调用时 lazy recreate | 小:~10 行加在 `resetSession` + LLM 调用入口;同步 API,无侵入 |
| B. Eager recreate | session reset 时立即 `await createContentGenerator(...)`,需 async 化 `resetSession` | 中:API 改动级联多处 |
| C. Proxy headers object | 给 `httpOptions.headers` 包 Proxy 拦截 getter | 风险高:`@google/genai` 内部是否 per-request 重读 headers 不可知,行为可能 silently break |
| D. 推动 `@google/genai` 上游加 `fetch` option | 提 PR 给 google-deepmind/generative-ai-js | 长期;不可控 |
**文档要在用户面前说明**:使用 Gemini provider 时如果 `/clear` 后立刻有 LLM 调用,wire 上的 session id 在那一刻是旧的。可以靠 trace correlation 间接修正(spans/logs 上 session.id 已经是新的)。
应单开 follow-up sub-issue 跟踪选项 A。
## 9. 与 claude-code 对比
| 维度 | claude-code | qwen-code 本设计 | 决策依据 |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| Session id header 命名 | `X-Claude-Code-Session-Id`(产品前缀) | `X-Qwen-Code-Session-Id`(产品前缀) | ✅ 同样命名空间策略 |
| Session id 注入机制 | SDK `defaultHeaders`(`client.ts:108`)+ 自定义 `buildFetch()` wrapper(`client.ts:370-390`,per-request `randomUUID()` 注入 `x-client-request-id`) | OpenAI/Anthropic 走 fetch wrapper(per-request 读 session id,避免 `/clear` staleness);Gemini 走 static `httpOptions.headers`(SDK 限制) | 与 claude-code 的 fetch wrapper 模式对齐。claude-code 也用 fetch wrapper 才能 per-request 加 `x-client-request-id` |
| Session id 持久性 | claude-code 没有 `/clear`-式 session reset;session = process | 有 `/clear` reset → fetch wrapper 路径自动跟随;static headers 路径会 stale(§8.6) | qwen-code 独有的复杂度 |
| Session id 编码 | HTTP header(不是 baggage) | HTTP header | ✅ 同——backend 友好 |
| `traceparent` 注入 | 闭源;公开 docs 描述存在;开源 repo 无 `propagation.inject` / `UndiciInstrumentation` 引用 | `@opentelemetry/instrumentation-undici` 自动 | claude-code 怎么实现的不可见。我们选 OTel 官方推荐路径,更轻 |
| `traceparent` 发送范围 | 仅第一方 Anthropic API;不发 Bedrock/Vertex/Foundry | 发给所有出站 fetch (W3C 标准;trace id 是 `sha256(sessionId)` 哈希)。**R3 修订**:session id header 仅向 first-party (Alibaba/DashScope) 白名单注入,第三方默认不发。详见 §11 | R3 后 qwen-code 的 session header 与 claude-code 同样的 first-party-only 语义;`traceparent` 仍待 per-destination toggle follow-up |
| `x-client-request-id` (随机) | 有,自动 | 暂不做(独立 follow-up sub-issue 价值更高) | 范围控制 |
| 子进程 `TRACEPARENT` env | 文档承认存在(实现闭源) | 不做(独立 follow-up) | 范围控制 |
| 入站 `TRACEPARENT` 读取 | 文档承认存在(`-p` / Agent SDK 模式) | 不做(独立 follow-up) | 范围控制 |
**verified vs documented 注解**:
| claim | 验证状态 |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `X-Claude-Code-Session-Id` via `defaultHeaders` | ✅ Open source `src/services/api/client.ts:108` 已读 |
| `x-client-request-id` via fetch wrapper | ✅ Open source `src/services/api/client.ts:370-390` 已读 |
| `traceparent` 注入 | ⚠️ 仅 docs.claude.com/docs/en/monitoring-usage.md 提到;开源 repo `grep -rn "propagation\.inject\|UndiciInstrumentation\|traceparent" src` 返回空 |
## 10. 未来工作
挂在 #3731 P3 下,本设计**不**包含但与之相关:
- **`X-Qwen-Code-Request-Id`** 随机 UUID per request(claude-code 等价:`x-client-request-id`)。对超时/timeout error correlation 有用——超时时服务端可能还没 assign request id,客户端先发的 id 是唯一关联手段。R3 修订后这个建议变得更有意义:per-request UUID 没有"跨请求行为画像"风险,可以作为"对所有 LLM provider 发送的支持/调试 header"。
- **`traceparent` 的 per-destination scope toggle** — R3 修订仅处理了 session id header 的作用域;`traceparent` 仍向所有出站 fetch 注入。可以加 `telemetry.propagateTraceContext: 'trusted-hosts' | 'all' | 'none'`,使用与 §11 同一份 allowlist 决定行为。
- **Gemini 的 session id staleness lazy-invalidate fix**(§8.6 选项 A):`/clear` 时 mark contentGenerator dirty,下次 LLM 调用 lazy recreate。让 Gemini 路径也享受 fetch wrapper 的实时性。
- **子进程 `TRACEPARENT` env**:给 `BashTool` 执行子进程时注入 env,让外部工具能续传 trace。需要单独看 tool execution lifecycle。
- **入站 `TRACEPARENT`**:`--prompt` 模式启动时读 env,让 CI / 外部 orchestrator 能把 qwen-code 接到更大的 trace。
- **可配置 `correlationHeader` name**:让企业 ops 自定义 header(默认 `X-Qwen-Code-Session-Id`)。
- **`baggage` propagation 策略**:是否主动 set baggage 让 `user.id` / `tenant.id` 等也走 baggage 传到下游。本期不做,等需求明确。
## 11. R3 修订 — Host-Allowlist Scoping for `X-Qwen-Code-Session-Id`
> 触发:[LaZzyMan 在 PR #4390 的 REQUEST_CHANGES review](https://github.com/QwenLM/qwen-code/pull/4390)
> 落地 commit:`1c8528a56` (核心实现) + `cb162e716` (Vertex baseUrl fail-closed + `["*"]` trim 容错)
### 11.1 触发与论证
R1 设计把 `X-Qwen-Code-Session-Id` 向**所有**出站 LLM 请求注入,仅由 `telemetry.enabled` 控制。LaZzyMan review 指出了三个递进的问题:
1. **标签错位**:`feat(telemetry):` + `telemetry/` 路径 + `getTelemetryEnabled()` gate 让用户合理理解为"自家可观测性数据流向自家 collector"。但 `X-Qwen-Code-Session-Id` 不会到达 OTLP 后端,它走在 LLM API 请求里发给 DashScope / OpenAI / Anthropic / Gemini / OpenRouter / MiniMax / ModelScope / Mistral。两种不同的数据出口决策绑在一个开关上。
2. **claude-code 类比不成立**:R1 在 §9 把命名空间策略和 fetch wrapper 模式都"对齐"了 claude-code。但 claude-code 是 Anthropic 一方 → Anthropic 一方(single vendor, single direction),qwen-code 是开源 CLI → 多个第三方 provider。"一个稳定 cross-request UUID 广播到所有第三方"是 R1 没正面回答的问题。
3. **traceparent 是同一指纹的另一通道**:trace id = `sha256(sessionId).slice(0, 32)`,对接收方来说仍是稳定 per-session 标识符(哈希后不可逆,但同一 session 仍稳定)。
LaZzyMan 标定 severity:session id `high` / traceparent `medium`。
### 11.2 解法概要
**收窄默认作用域到 first-party hosts**。新增一项 setting:
```jsonc
"telemetry": {
"sessionIdHeaderHosts": ["*"] // 恢复 R1 广播行为
"sessionIdHeaderHosts": [] // 全关 header
"sessionIdHeaderHosts": ["api.mycompany.com",
"*.gateway.mycompany.internal"]
}
```
默认值(来自 `packages/core/src/telemetry/trusted-llm-hosts.ts:DEFAULT_SESSION_ID_HEADER_HOSTS`):
```
dashscope.aliyuncs.com
dashscope-intl.aliyuncs.com
*.dashscope.aliyuncs.com
*.dashscope-intl.aliyuncs.com
*.alibaba-inc.com
*.aliyun-inc.com
```
这个集合的语义是"LLM provider、ARMS Tracing 后端、qwen-code distribution 同一法律实体"——也就是 claude-code 那个 single-vendor / single-direction 关系在 qwen-code 的对应集合。第三方 provider(OpenAI / Anthropic / OpenRouter / 等)默认**不**接收 header。
### 11.3 Pattern 语法(intentionally tiny)
`matchesTrustedHost(hostname, patterns)` 只支持两种模式,与 `DashScopeOpenAICompatibleProvider.isDashScopeProvider` 对齐:
- bare hostname → 精确匹配(case-insensitive)
- `*.suffix` → 匹配 `suffix` 自身 **AND** 任何子域;dot-anchored 拒绝 `evil-alibaba-inc.com` / `alibaba-inc.com.attacker.tld` 等 typo-suffix 攻击向量
不引入 regex、不引入端口/scheme 感知 globbing —— 让 settings 里的字符串就是它字面看起来的语义。
### 11.4 实现差异 vs R1
#### `wrapFetchWithCorrelation` (OpenAI / Anthropic)
R1 的 wrapper 只有 telemetry-enabled + sessionId 两个 gate。R3 在两者之间插入第三个 gate:
```ts
const trustedHosts =
config.getTelemetrySessionIdHeaderHosts?.() ??
DEFAULT_SESSION_ID_HEADER_HOSTS;
const broadcastAll = trustedHosts.some((p) => p.trim() === '*');
return async function correlationFetch(input, init) {
if (!config.getTelemetryEnabled()) return baseFetch(input, init);
if (!broadcastAll) {
const host = extractRequestHost(input);
if (!host || !matchesTrustedHost(host, trustedHosts)) {
return baseFetch(input, init); // host gate
}
}
const sid = config.getSessionId();
if (!sid) return baseFetch(input, init);
// ... header injection
};
```
`trustedHosts` 在 wrap 时一次性 snapshot(与 session id 的"每请求实时读"不同)。中途修改 `telemetry.sessionIdHeaderHosts` 需要重建 contentGenerator 才生效。`[" * "]` 之类带空格的写法通过 `.trim()` 兜底成 broadcast,避免 settings.json 手敲笔误沉默退化。
#### `staticCorrelationHeaders` (Gemini)
签名加一个 `destinationUrl?: string` 参数:
```ts
export function staticCorrelationHeaders(
config: Config,
destinationUrl?: string,
): Record<string, string> {
if (!config.getTelemetryEnabled()) return {};
if (!destinationUrl) return {}; // fail-closed: 不知道目的地就不发
if (!matchesTrustedHost(new URL(destinationUrl).hostname, trustedHosts)) {
return {};
}
return { [SESSION_ID_HEADER]: config.getSessionId() };
}
```
#### Gemini factory 集成
Gemini SDK 有两个不可见 default endpoint(`generativelanguage.googleapis.com` 与 `{region}-aiplatform.googleapis.com`,由 `vertexai` 决定),factory 层无法准确还原其中之一。R3 选择"`config.baseUrl` 没设就传 `undefined`",让 helper fail-closed → 不发 header。运营商想要相关性必须显式设 `baseUrl`(也是 SDK 自己用来解 destination 的同一输入)。这一改动避免了猜错 Vertex destination 后被允许列表错误命中。
### 11.5 新文件 / 新代码
| 文件 | 说明 |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `packages/core/src/telemetry/trusted-llm-hosts.ts` (NEW) | `DEFAULT_SESSION_ID_HEADER_HOSTS` + `matchesTrustedHost` + `extractRequestHost` |
| `packages/core/src/telemetry/trusted-llm-hosts.test.ts` (NEW) | 单测,含 TLD-suffix 攻击向量、IPv6 fail-closed、port/userinfo/query 提取 |
| `packages/core/src/telemetry/llm-correlation-fetch.ts` | 加 host gate;`staticCorrelationHeaders` 加 `destinationUrl` 参数 |
| `packages/core/src/telemetry/llm-correlation-fetch.test.ts` | 加 host-gate 8 个 case;`mockConfig` 用 `'hosts' in opts` 区分 "default allowlist" vs "broadcast" |
| `packages/core/src/telemetry/config.ts` (`resolveTelemetrySettings`) | 透传 `sessionIdHeaderHosts` |
| `packages/core/src/config/config.ts` | `TelemetrySettings.sessionIdHeaderHosts` + `getTelemetrySessionIdHeaderHosts()` getter |
| `packages/core/src/core/geminiContentGenerator/index.ts` | 传 `config.baseUrl` 给 helper;fail-closed when undefined |
| `packages/core/src/core/geminiContentGenerator/index.test.ts` | 重写 telemetry-on Gemini 测试以匹配新 fail-closed 语义 |
| `packages/cli/src/config/settingsSchema.ts` | `sessionIdHeaderHosts` JSON schema 入口 |
| `packages/vscode-ide-companion/schemas/settings.schema.json` | 由 `npm run generate:settings-schema` 重新生成 |
| `docs/developers/development/telemetry.md` | "Session correlation header" 段落改写 + 默认 scope + override 语法 |
### 11.6 对各 LazzyMan 论点的回应
| LazzyMan 论点 | R3 回应 |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ① telemetry 标签错位 | **化解**:在 DashScope 用例下,session id header 字面就是发给 ARMS Tracing 后端(同一法律实体),`telemetry.enabled` 语义对齐 |
| ② cross-vendor stable identifier 广播 | **化解**:默认 allowlist 只含阿里系 first-party host;广播退化为 opt-in (`["*"]`) |
| ③ traceparent 是同一指纹的另一通道 | **暂保留**:traceparent 仍按 R1 全注入。理由:W3C 标准、trace id 是 sha256 哈希、in-vendor trace 续接是 W3C 的核心设计场景。per-destination traceparent toggle 列入 §10 future work |
### 11.7 已知遗留 + 跟进
- **traceparent scope** — 见上文第 ③ 点,列入 §10
- **Per-request random UUID** (`X-Qwen-Code-Request-Id`) — LazzyMan 提的替代方案,列入 §10
- **Gemini staleness lazy-invalidate** (§8.6 选项 A) — 与 R3 解耦,独立 sub-issue
- **`matchesTrustedHost` IPv6 支持** — 当前 IPv6 destination 永不在 allowlist 上(`URL.hostname` 返回 `[::1]` 带方括号,pattern 语法无对应形式)。当前满足"命名 first-party endpoint"用例。若将来有 raw IP allowlist 需求再扩展。
## 12. R4 修订 — Scope Conflation Split
> 触发:[LaZzyMan round-8 follow-up review on PR #4390](https://github.com/QwenLM/qwen-code/pull/4390)
> 落地:本 PR 收窄;R3 落地的 session-id 整套挪到独立 follow-up PR
### 12.1 触发与论证
R3 化解了 LaZzyMan 第一轮 review 的「广播稳定指纹给第三方 provider」担忧(severity: high)。但在 round-8 follow-up 中他升级到更深的架构原则反对:
> "Telemetry is not a container for adjacent features. The `traceparent` cross-process propagation and the `X-Qwen-Code-Session-Id` header injection are **not telemetry**. They are outbound-identity / outbound-correlation work that uses some OTel APIs internally as an implementation detail."
他的核心元论点:
- **"telemetry" namespace 暗示 recipient = 用户自己的 OTLP collector**
- 但 `traceparent` 和 `X-Qwen-Code-Session-Id` 的 recipient = **第三方 LLM provider**
- 两类不同 recipient 应该有两类不同的同意决策树
- 即使默认行为安全(R3 已实现),把 wire-level 行为放在 `telemetry.*` 下**设了坏先例**:未来 telemetry PR 可以继续偷渡 wire 行为给第三方
- "If we accept that principle, the split is mechanical. If we don't, this PR is the wrong place to debate it because the technical fixes are already in."
### 12.2 解法概要("方案 C" hybrid split)
经过几轮内部讨论(含 yiliang 提出的 customHeader 模板替代方案,最终判定 customHeader 不能携带 runtime-dynamic 值),决定走 **方案 C**:
**本 PR 留下**:
- `UndiciInstrumentation` 注册(产 client HTTP span → 用户自家 OTLP collector)
- OTLP feedback-loop guard(前者的必要副作用)
- **`NoopTextMapPropagator` 默认安装** → `propagation.inject()` 是 no-op → outbound `fetch` 上**不再有 `traceparent`**
- **新增 `outboundCorrelation.propagateTraceContext: bool` (默认 false)** 作为独立 namespace 顶级设置;设 true 时安装默认 W3C composite propagator
- 整套 `R3 session-id` 代码(`llm-correlation-fetch.ts` / `trusted-llm-hosts.ts` / `telemetry.sessionIdHeaderHosts` setting / 4 个 provider 集成点 / 所有相关测试)**全部移除**
**搬到 follow-up PR**:
- `X-Qwen-Code-Session-Id` header 整套机器(R3 实现复用)
- 进入新 `outboundCorrelation.*` namespace(具体 setting key TBD,但**不会**叫 `telemetry.*`)
- Follow-up PR 自带:threat model section、独立 review、security-relevant 标注的 docs
- `X-Qwen-Code-Request-Id` per-request UUID(LazzyMan 在 R3 round 提出的替代设计)也归入此 follow-up 的考虑范围
### 12.3 与 R3 R1 论点的映射
| R1/R3 论点 | R4 后状态 |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| §3.1 "所有出站 LLM 请求带 traceparent" | ❌ **R4 默认 off**;需 `outboundCorrelation.propagateTraceContext: true` 才开 |
| §3.1 "所有出站 LLM 请求带 `X-Qwen-Code-Session-Id`" | ❌ **R4 整套移出本 PR**,搬到 follow-up PR |
| §4.3 fetch wrapper 注入 session id | ❌ 整段代码不在本 PR;复用到 follow-up PR |
| §11 host allowlist (R3 设计) | ❌ 同上;整体迁移 follow-up PR |
| §4.4 不引入新 setting | ❌ **本 PR 新增 `outboundCorrelation.propagateTraceContext`** 一个 boolean;session id 相关 setting 在 follow-up PR |
| §10 future work "`X-Qwen-Code-Request-Id`" | ✅ 仍是 future work;与 session-id follow-up 一起设计 |
### 12.4 新 namespace 设计意图
`outboundCorrelation.*` 顶级 namespace 在本 PR 只有一个 boolean (`propagateTraceContext`),看起来过度结构化。但这是**精心选择的**:
- **建立命名空间作为承诺**:让后续 session-id / request-id / etc. 自然进入这个 namespace
- **标注为 security-relevant**:`settingsSchema.ts` description 显式写 "SECURITY-RELEVANT",文档化为"安全设置"而非"observability 设置"
- **defaults 全部 off**:符合 LazzyMan 提出的"open-source 客户端不应未经显式同意向第三方发稳定 id"原则
- **与 telemetry.\* 解耦**:用户读 settings.json 看到 `outboundCorrelation.*` 立刻能识别这是出站 wire 行为,不是 observability
#### 隐性依赖:`telemetry.enabled`
虽然 namespace 与 `telemetry.*` 解耦,**运行时生效仍依赖 `telemetry.enabled: true`** —— OTel SDK 只在 telemetry 启用时初始化,没有 SDK 就没有 propagator 安装、没有 `propagation.inject()` 调用,flag 等于沉默 no-op。容易踩的 footgun:运营商加 `propagateTraceContext: true` 却忘开 telemetry,trap server 上看不到任何 `traceparent`,无 error / 无 warning。
两个面向用户的面板都显式标注此依赖:
- `telemetry.md` 的 `propagateTraceContext` 段附完整双 flag JSON 示例
- `settingsSchema.ts` 的 description string **首句**即 "Requires `telemetry.enabled: true`"(前置以避免 VS Code 设置 UI 长描述折叠后看不到)
未来若添加 session-id header 或其他 `outboundCorrelation.*` setting,**同一依赖关系适用** —— 都得在 telemetry 启用前提下才有意义(因为它们都通过 OTel instrumentation/SDK 注入)。Follow-up PR 应继承此 footgun 提示模式。
### 12.5 实施
| 文件 | 改动 |
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `packages/core/src/telemetry/llm-correlation-fetch.ts` | **删除** |
| `packages/core/src/telemetry/llm-correlation-fetch.test.ts` | **删除** |
| `packages/core/src/telemetry/trusted-llm-hosts.ts` | **删除** |
| `packages/core/src/telemetry/trusted-llm-hosts.test.ts` | **删除** |
| `packages/core/src/telemetry/sdk.ts` | + `NoopTextMapPropagator`;按 `getOutboundCorrelationPropagateTraceContext()` 决定 SDK textMapPropagator |
| `packages/core/src/core/openaiContentGenerator/provider/default.ts` | 移除 `wrapFetchWithCorrelation` 引用 |
| `packages/core/src/core/openaiContentGenerator/provider/dashscope.ts` | 同上 |
| `packages/core/src/core/anthropicContentGenerator/anthropicContentGenerator.ts` | 同上 |
| `packages/core/src/core/geminiContentGenerator/index.ts` | 移除 `staticCorrelationHeaders` 引用 |
| 上述 4 个 provider 的 `*.test.ts` | 删 session-id 相关测试 case |
| `packages/core/src/config/config.ts` | 删 `TelemetrySettings.sessionIdHeaderHosts`、`getTelemetrySessionIdHeaderHosts`;**新增 `OutboundCorrelationSettings` 接口 + `outboundCorrelationSettings` 字段 + `getOutboundCorrelationPropagateTraceContext()` getter** |
| `packages/core/src/telemetry/config.ts` | 删 `resolveTelemetrySettings` 中 sessionIdHeaderHosts 透传 |
| `packages/cli/src/config/settingsSchema.ts` | 删 `sessionIdHeaderHosts` schema;**新增 `outboundCorrelation` 顶级 schema 项** |
| `packages/cli/src/config/config.ts` | 透传 `outboundCorrelation: settings.outboundCorrelation` 进 `ConfigParameters` |
| `packages/vscode-ide-companion/schemas/settings.schema.json` | `npm run generate:settings-schema` 重新生成(description 后续更新时同步刷新) |
| `docs/developers/development/telemetry.md` | 重写 "Trace context propagation" → "Client-side HTTP span on outbound fetch";删 "Session correlation header" 整节;新增 "Outbound correlation (SECURITY-RELEVANT)" 顶级 section;附 `telemetry.enabled` 依赖说明 + JSON 配置示例 |
| `docs/design/telemetry-outbound-propagation-design.md` | 本节 + R4 表头 + 修订指针 |
| `packages/core/src/config/config.test.ts` | **新增 `OutboundCorrelation Configuration` describe block**,`it.each` 4 个 case 锁定 `getOutboundCorrelationPropagateTraceContext` 的 default-false 安全不变性(omitted / `{}` / explicit true / explicit false) |
### 12.6 对 LazzyMan 元论点的回应
| 论点 | R4 后状态 |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| "Telemetry namespace 暗示自家 collector 接收方" | ✅ wire 行为已搬出 `telemetry.*`;新 `outboundCorrelation.*` namespace 显式标识"出站第三方"语义 |
| "默认行为不应未经显式同意向第三方发标识符" | ✅ `propagateTraceContext` 默认 false;session-id 整套 follow-up PR 也将默认 off |
| "telemetry PR 不应偷渡 wire-level 行为" | ✅ 本 PR 不再添加任何"telemetry 控制 wire 行为"的代码路径;wire 行为统一由 `outboundCorrelation.*` 管 |
| "split is mechanical, work isn't wasted" | ✅ R3 落地代码物理删除自本 branch,留在 git history 里给 follow-up PR 复用(或 cherry-pick) |
### 12.7 follow-up PR 大纲(信息性,不在本 PR 范围)
未来 follow-up PR 应包含:
- `outboundCorrelation.sessionIdHeader: { enabled, trustedHosts }` 或类似 setting
- 复用 R3 已实现的 `wrapFetchWithCorrelation` / `matchesTrustedHost` / `DEFAULT_SESSION_ID_HEADER_HOSTS` 代码骨架
- threat model 一节,明确:recipient 集合、稳定 id 的去匿名化窗口、可选 per-request UUID 配套
- **默认 off**(无 default allowlist —— 比 R3 更严,符合 LazzyMan 的开源 CLI 原则)
- security-relevant 标注 + docs/users/configuration/settings.md 收录

View File

@ -18,8 +18,9 @@ qwen-code 目前仅有面向 Arena 多模型对比场景的内部 worktree 实
| Post-creation setup(hooks 配置) | ❌ | ✅ | Phase C |
| StatusLine worktree 状态展示 | ❌ | ✅ | Phase C |
| WorktreeExitDialog(退出提示) | ❌ | ✅ | Phase C |
| `--worktree` CLI 启动标志 | ❌ | ✅ | Phase D |
| 符号链接目录(node_modules 等) | ❌ | ✅ | Phase D |
| `--worktree` CLI 启动标志 | ✅(Phase D) | ✅ | — |
| 符号链接目录(node_modules 等) | ✅(Phase D) | ✅ | — |
| PR 引用(`--worktree=#123`) | ✅(Phase D) | ✅ | — |
| sparse checkout | ❌ | ✅ | Future |
| tmux 集成 | ❌ | ✅ | Future |
| Arena 多模型 worktree 隔离 | ✅(qwen 独有) | ❌ | — |
@ -56,12 +57,13 @@ Arena 的 worktree 路径由 `agents.arena.worktreeBaseDir` 控制,默认 `~/.
### 扩展配置
| 配置项 | 类型 | 用途 | 阶段 |
| ----------------------------- | ---------- | -------------------------------------------------------------- | ------- |
| `worktree.symlinkDirectories` | `string[]` | 符号链接指定目录(如 `node_modules`)到 worktree,避免磁盘浪费 | Phase D |
| `worktree.sparsePaths` | `string[]` | git sparse-checkout cone 模式,大型 monorepo 只写入指定路径 | Future |
| 配置项 | 类型 | 用途 | 阶段 |
| --------------------------------- | ---------- | ---------------------------------------------------------------- | ------- |
| `ui.hideBuiltinWorktreeIndicator` | `boolean` | 隐藏 Footer 中内置 `⎇ worktree-… (…)` 行,留给 custom statusline | Phase C |
| `worktree.symlinkDirectories` | `string[]` | 符号链接指定目录(如 `node_modules`)到 worktree,避免磁盘浪费 | Phase D |
| `worktree.sparsePaths` | `string[]` | git sparse-checkout cone 模式,大型 monorepo 只写入指定路径 | Future |
Phase A / B / C 不新增任何配置项。
Phase A / B 不新增任何配置项。
## 工具设计
@ -233,32 +235,154 @@ _WorktreeExitDialog:_
---
### Phase D:启动时配置(`--worktree` CLI 标志 + 目录符号链接)
### Phase D:启动时配置(`--worktree` CLI 标志 + 目录符号链接 + PR 引用)
**目标:** 支持在启动时直接进入 worktree,并通过目录符号链接减少大型项目的磁盘开销。
**目标:** 支持在启动时直接进入 worktree、通过目录符号链接减少大型项目的磁盘开销,以及通过 PR 引用快速基于一个 pull request 创建 worktree。
**要实现的功能:**
**范围:** 三个功能在一个阶段一起落地,因为它们都挂在同一个启动入口上,且 symlink / PR fetch 两者都需要在 worktree 创建之后立即执行 — 单独拆分会重复改 bootstrap 序列。
_`--worktree [name]` CLI 启动标志:_
#### D-1:`--worktree [name]` CLI 启动标志
- `packages/cli/src/args.ts` 新增 `--worktree [name]` 参数
- 启动流程在进入主循环前调用 `createUserWorktree()`,将 `targetDir` 设为 worktree 路径,并写入 SessionService 状态
- 整个会话从启动即在 worktree 环境中运行,退出时触发 WorktreeExitDialog
**参数形态:** yargs 选项接受三种形式:
_`worktree.symlinkDirectories` 配置项:_
| 形式 | 行为 |
| ------------------------- | ---------------------------------------------------- |
| `qwen --worktree` | bare flag,自动生成 slug(`{形容词}-{名词}-{6hex}`) |
| `qwen --worktree my-name` | 显式 slug,沿用 `EnterWorktreeTool` 的 slug 校验规则 |
| `qwen --worktree=my-name` | 等价于上一种 |
- settings schema 新增 `worktree.symlinkDirectories: string[]`
- `createUserWorktree()` 后遍历配置,调用 `fs.symlink()` 将主仓库目录链接进 worktree
- 跳过目标不存在的项;目标已存在时跳过(不覆盖)
不提供短别名 `-w`(qwen-code 短别名只保留给最高频参数,避免命名冲突)。
**影响文件:**
**启动序列:** worktree 在以下位置创建:
| 文件 | 变更类型 |
| -------------------------------------------------- | ------------------------------------------- |
| `packages/cli/src/args.ts` | 新增 `--worktree [name]` 参数 |
| `packages/cli/src/main.ts`(或启动入口) | 解析 `--worktree` 并在主循环前创建 worktree |
| `packages/core/src/services/gitWorktreeService.ts` | `createUserWorktree()` 后追加 symlink 逻辑 |
| `packages/core/src/config/`(settings schema) | 新增 `worktree.symlinkDirectories` 字段 |
1. `parseArguments()` 解析 argv(已有)
2. resume picker(已有,line 588-629 of `gemini.tsx`)
3. `loadCliConfig()` 初始化 Config + auth(已有,line 643-653)
4. **新增:** 若 `argv.worktree !== undefined`,调用 `createUserWorktree()`
- 写入 sidecar(`writeWorktreeSession()`)
- 设置 `process.chdir(worktreePath)` 同时 `Config.setTargetDir(worktreePath)`
- 同一 worktree 的 re-attach 路径:跳过 `git worktree add` 并就地 chdir(Phase 6 修复)。跨 projectHash 的 `--resume` × `--worktree` 组合在 session lookup 阶段会失败,详见下文"与 `--resume` 的优先级"。
5. 主循环(TUI / headless `-p` / ACP 三种入口都要走第 4 步)
**与 Phase A 简化的差异:** Phase A 的 `EnterWorktreeTool` **不**修改 `Config.targetDir`,依赖模型从工具结果里读到绝对路径并继续使用。Phase D 的 CLI flag 在启动期就生效,没有运行中的模型上下文需要兼容,所以**直接切换 `targetDir` 和 `process.cwd()`** —— 这是更强的隔离保证。两条路径行为不同,需要在用户文档里说明。
**退出行为:** 复用现有 `WorktreeExitDialog`(Phase C 已实现)。Ctrl+C/D 两次触发 → 用户在 keep / remove / cancel 之间选择。不需要新代码路径。
**与 `--resume` 的优先级:**
由于 session 存储以 `projectHash(process.cwd())` 为 key,而 `--worktree` 在 resume picker / `loadCliConfig` 之前就 chdir 到 worktree,所以"在 worktree X 启动的 session,从 worktree Y 内 resume"是**架构上不可达**的(两者的 projectHash 不同,session 文件落在不同目录)。下表反映 D-1 实现 + Phase 6 re-attach 修复后的实际行为:
| `--resume` 状态 | `--worktree` 状态 | 结果 |
| ---------------------------- | -------------------------- | ------------------------------------------------------------------------------------------ |
| 无 | 无 | 普通会话,无 worktree |
| 无 | 有(新 slug) | 新建 worktree |
| 无 | 有(已存在的 slug) | **re-attach** 到已有 worktree(Phase 6 修复) |
| 有 | 无 | 恢复旧 worktree(Phase C 行为,sidecar 命中则注入 reminder) |
| 有(sid 出自同一 worktree) | 有(同一 slug,re-attach) | re-attach + session 命中:正常 resume |
| 有(sid 出自 main checkout) | 有(任意 slug) | **session lookup 失败**:`No saved session found with ID …`,exit 1。documented limitation |
| 有(sid 出自 worktree X) | 有(slug Y, X != Y) | 同上,session 跨 projectHash 不可寻 |
跨 projectHash override 的语义(`--worktree` 在不同 worktree / 主 checkout 的 session 之间转移)需要 storage 锚定到 repo root 而非 cwd-derived projectHash,属于未来 Config 重构范畴。`persistStartupWorktreeSidecar` 内的 `overrodeResumedWorktree` 分支代码保留是为该重构落地后能自动生效,目前在生产路径不会触发。
#### D-2:`worktree.symlinkDirectories` 配置项
**schema:**
```jsonc
{
"worktree": {
"symlinkDirectories": ["node_modules", "dist", ".turbo"],
},
}
```
- 类型:`string[]`,默认 `undefined`(不开启,opt-in)
- 顶层 namespace `worktree` 是新增的(在 `settingsSchema.ts` 中按字母序插在 `tools` 与 `ui` 之间)
- 路径**相对于主仓库根**,绝对路径或包含 `..` 的路径被路径遍历守卫拒绝
**作用范围:** 所有由通用层创建的 worktree,包括:
- `EnterWorktreeTool`(Phase A)
- `AgentTool` `isolation: 'worktree'`(Phase B)
- `--worktree` CLI flag(Phase D-1)
Arena 的 worktree 不走通用层,**不**受此配置影响。
**实现位置:** `GitWorktreeService.performPostCreationSetup()` —— 紧跟现有的 `configureHooksPath()`(Phase C 已建立的模式)。新增 `symlinkConfiguredDirectories()` 方法,遍历配置项调用 `fs.symlink(absSource, absDest, 'dir')`。
**错误处理(fail-open):**
| 场景 | 行为 |
| ----------------------------- | ------------------------------ |
| 源目录不存在(ENOENT) | 静默跳过,debug log |
| 目标路径已存在(EEXIST) | 静默跳过,debug log(不覆盖) |
| 路径遍历(`../`、绝对路径等) | 拒绝该项,debug log warn |
| 其他 I/O 错误 | debug log warn,继续处理后续项 |
worktree 创建本身**不会**因为 symlink 失败而中止 —— 与 `configureHooksPath()` 相同的"best-effort post-creation setup"原则。
#### D-3:PR 引用解析(`--worktree=#<N>` / 全 URL)
**支持形式:**
| 形式 | 解析后的 PR 号 |
| --------------------------------------------------------------- | -------------- |
| `--worktree=#123` | 123 |
| `--worktree '#123'` | 123 |
| `--worktree https://github.com/foo/bar/pull/123` | 123 |
| `--worktree https://gh.enterprise.com/foo/bar/pull/123?baz=qux` | 123 |
**slug 与分支命名:**
- slug:`pr-<N>`(特殊保留前缀,与用户 slug 区分)
- 分支:`worktree-pr-<N>`(沿用 qwen-code 现有 `worktree-<slug>` 命名规则;不采用 claude-code 的 `pr-<N>` 直接命名,避免与本地 `pr-<N>` 分支冲突)
**fetch 策略:**
```
git fetch origin pull/<N>/head
→ 用 FETCH_HEAD 作为新 worktree 的 base
```
不依赖 `gh` CLI —— 纯 git fetch,支持任何 GitHub 实例(公网或企业版),只要 `origin` 远程指向 GitHub。
**错误路径:**
| 场景 | 错误消息 |
| ------------------------ | ---------------------------------------------------------------------------- |
| `origin` 远程缺失 | `--worktree=#<N> requires an "origin" remote that points at GitHub.` |
| `git fetch` 失败 | `Failed to fetch PR #<N>: PR may not exist or origin remote is unreachable.` |
| 网络超时(30s) | 同上,加 `(timeout)` |
| `origin` 远程不是 GitHub | 不做主动检查,由 `git fetch` 自然失败(PR 协议是 GitHub 特有的) |
**与 D-2 的关系:** PR worktree **同样**应用 `symlinkDirectories`(用户期望在 PR 上立刻能跑测试,依赖目录需要复用)。
#### 影响文件
| 文件 | 变更类型 |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `packages/cli/src/config/config.ts` | yargs 新增 `--worktree` 选项;`CliArgs` 接口加 `worktree?: string \| boolean` |
| `packages/cli/src/gemini.tsx` | `loadCliConfig()` 之后、主循环之前调用新的 `setupStartupWorktree()` helper |
| `packages/cli/src/startup/worktreeStartup.ts` | 新建:`setupStartupWorktree()` 处理 slug 解析、PR fetch、sidecar 写入、cwd 切换 |
| `packages/cli/src/nonInteractiveCli.ts` | 复用同一 helper(已有 `restoreWorktreeContext` 注入逻辑,无须改) |
| `packages/cli/src/acp-integration/acpAgent.ts` | 复用同一 helper |
| `packages/core/src/services/gitWorktreeService.ts` | 新增 `parsePRReference()`、`fetchPullRequestRef()`、`symlinkConfiguredDirectories()`;`createUserWorktree()` 接受可选 `baseBranchRef` 参数 |
| `packages/cli/src/config/settingsSchema.ts` | 新增 `worktree.symlinkDirectories: string[]` 顶层项 |
| `packages/vscode-ide-companion/schemas/settings.schema.json` | 重新生成 |
| `docs/users/features/worktree.md` | 新增 Quick Start CLI flag 章节、Settings 表新增一行 |
#### 安全与回滚
- **fail-open vs fail-close:** symlink / hooks 失败 **不** 中止 worktree 创建(同 Phase C 既定模式);PR fetch 失败 **中止** 启动(无 base ref 就无法创建 worktree);slug 校验失败 **中止** 启动(与 `EnterWorktreeTool` 一致)。
- **path traversal:** `symlinkDirectories` 项必须解析后仍在 `repoRoot` 内,否则拒绝该项并 log。
- **PR fetch 超时:** 30 秒硬超时,避免无响应的网络拖死启动。
- **cwd 切换的副作用:** 切 `process.cwd()` 之后,相对路径(如 `--prompt-file ./foo.txt`)的解析会受影响。**对策:** 在切 cwd 之前先解析所有相对路径参数(具体在 `setupStartupWorktree()` 入口处做一次 normalize)。
#### 开放问题
1. **`--worktree-keep-on-exit`?** claude-code 没有,qwen-code 是否需要一个 CLI flag 让 Exit Dialog 默认选 keep?建议**先不加**,等用户反馈。
2. **`worktree.symlinkDirectories` 是否需要 per-project override?** 当前 settings 已经支持 user/workspace/project 三级合并,无需特殊处理。
3. **PR fetch 是否要拉取 `merge` ref(`pull/<N>/merge`,即与 base 合并后的 ref)而非 `head`?** claude-code 选 `head`,理由是用户通常想看 PR 的实际改动。沿用此选择。
---
@ -266,9 +390,8 @@ _`worktree.symlinkDirectories` 配置项:_
以下功能面向更特定的使用场景,当前阶段不纳入排期,待用户需求明确后再评估实现。
| 功能 | 说明 |
| ----------------------- | ------------------------------------------------------------------------------------------- |
| sparse checkout | `worktree.sparsePaths` 配置项,大型 monorepo 只 checkout 指定路径,缩短创建时间和磁盘占用 |
| `.worktreeinclude` 文件 | 将 gitignore 的文件(`.env`、`secrets.json` 等)自动复制进 worktree |
| tmux 集成 | `--worktree --tmux` 在新 tmux 窗口启动 worktree 会话 |
| PR 引用解析 | `--worktree=#123` 自动 fetch PR 分支并基于它创建 worktree(依赖 Phase D `--worktree` 标志) |
| 功能 | 说明 |
| ----------------------- | ----------------------------------------------------------------------------------------- |
| sparse checkout | `worktree.sparsePaths` 配置项,大型 monorepo 只 checkout 指定路径,缩短创建时间和磁盘占用 |
| `.worktreeinclude` 文件 | 将 gitignore 的文件(`.env`、`secrets.json` 等)自动复制进 worktree |
| tmux 集成 | `--worktree --tmux` 在新 tmux 窗口启动 worktree 会话 |

View File

@ -262,6 +262,99 @@ and logs still carry `session.id`, and trace / log backends (Jaeger, Tempo,
Loki, Aliyun SLS / ARMS Tracing) handle per-session slicing natively without
cardinality pressure.
### Client-side HTTP span on outbound fetch
When telemetry is enabled, Qwen Code registers `UndiciInstrumentation`
which creates a client-side HTTP span for every outbound `fetch()`
request originated by the process — including the LLM SDKs (`openai`,
`@google/genai`, `@anthropic-ai/sdk`), the MCP StreamableHTTP client, the
`WebFetch` tool, and any IDE-extension out-of-process calls. The span
lets you see network latency (TTFB / response body transfer) separately
from upstream model processing time, which the existing
`api.generateContent` span alone can't distinguish.
These spans go to your **own** OTLP collector (or file outfile) just like
the rest of the telemetry — they do not affect what is written onto the
outbound HTTP request itself. Whether the W3C `traceparent` header is
also written into the outgoing request stream is controlled by a
**separate, security-relevant setting** documented in
[outbound correlation](#outbound-correlation-security-relevant) below.
**Feedback-loop avoidance.** OTel SDK uses `fetch` internally to upload OTLP
data. Without protection, instrumenting `fetch` would trace those uploads,
which would themselves be uploaded, causing an infinite loop. Qwen Code's
undici instrumentation is configured with an `ignoreRequestHook` that skips
URLs matching the configured `telemetry.otlpEndpoint` /
`telemetry.otlpTracesEndpoint` / `telemetry.otlpLogsEndpoint` /
`telemetry.otlpMetricsEndpoint` prefixes. In file-outfile mode there are no
outbound HTTP uploads, so the hook is a no-op.
## Outbound correlation (SECURITY-RELEVANT)
These settings live in a **separate top-level namespace** from `telemetry.*`
on purpose: telemetry controls data flow into the operator's own
observability backend, while `outboundCorrelation.*` controls what
client-side correlation data qwen-code writes **into outbound LLM API
request streams** that reach third-party LLM provider endpoints
(DashScope, OpenAI, Anthropic, etc.). Different recipients, different
consent decision. **All values default to off.** See PR #4390 review
discussion for the framing rationale.
### `outboundCorrelation.propagateTraceContext`
```jsonc
"outboundCorrelation": {
"propagateTraceContext": false // default
}
```
When `false` (default), Qwen Code installs a no-op `TextMapPropagator` on
the OTel SDK. UndiciInstrumentation still creates client HTTP spans for
your OTLP collector, but `propagation.inject()` is a no-op so **no
`traceparent` is written onto outbound requests**. Trace IDs stay
internal to the operator's collector.
When `true`, the SDK's default W3C composite propagator
(`tracecontext` + `baggage`) is installed and the standard `traceparent`
header is written on every outbound `fetch`:
```
traceparent: 00-<32-hex traceId>-<16-hex parentSpanId>-<01-sampled | 00-not-sampled>
```
Opt in only when the LLM provider also reports into your OTel collector
for cross-process trace stitching — e.g. ARMS Tracing serving DashScope.
For most operators the value is `false`; cross-vendor trace continuation
is niche.
**Depends on `telemetry.enabled: true`.** The OTel SDK only initializes
when telemetry is enabled, so `propagateTraceContext` only takes effect
in that state. Setting it to `true` while telemetry is disabled is a
silent no-op — no SDK, no propagator, no `traceparent` on the wire.
Verify both flags when wiring an ARMS+DashScope correlation setup:
```jsonc
{
"telemetry": {
"enabled": true,
"otlpTracesEndpoint": "http://tracing-analysis-...",
},
"outboundCorrelation": {
"propagateTraceContext": true,
},
}
```
### Other outbound correlation headers
`X-Qwen-Code-Session-Id` and `X-Qwen-Code-Request-Id` are **not part of
this PR**. They will be designed and proposed in their own follow-up
PR(s) under the same `outboundCorrelation.*` namespace, each with its
own threat model and operator-consent flow. PR #4390 review (LaZzyMan)
established the principle: "telemetry's scope of work doesn't include
sending identifiers to LLM providers"; correlation-header work moves to
its own design discussion rather than landing under telemetry.
## Aliyun Telemetry
### Manual OTLP Export

View File

@ -0,0 +1,748 @@
# Worktree Phase D E2E Test Plan
## Scope
End-to-end verification of Phase D features against the local build at
`/Users/mochi/code/qwen-code/.claude/worktrees/tender-jemison-037f0a/dist/cli.js`.
Phase D delivers three cross-cutting capabilities:
- **D-1** — `--worktree [name]` CLI startup flag (bare / explicit slug / `=` form),
with `process.cwd()` + `Config.targetDir` switch and `WorktreeExitDialog`
reuse on exit
- **D-2** — `worktree.symlinkDirectories: string[]` settings key, applied in
`performPostCreationSetup()` so it covers `--worktree`, `EnterWorktreeTool`,
AND `AgentTool isolation: "worktree"` paths
- **D-3** — `--worktree=#<N>` and `--worktree <github-url>` PR-reference forms,
via `git fetch origin pull/<N>/head` (no `gh` CLI dependency)
## Binaries
- **Local build (Phase 6 verification)**: `node /Users/mochi/code/qwen-code/.claude/worktrees/tender-jemison-037f0a/dist/cli.js`
- **Phase 4 dry-run baseline**: globally installed `qwen`
For dry-runs the globally installed `qwen` is expected to fail Groups A / E / F
because the features don't exist yet — that's the validation that the plan
correctly detects implementation.
### Baseline precondition for Group E
Tests **E2** (`EnterWorktreeTool` symlink) and **E3** (`AgentTool isolation`
symlink) require **Phase A + B** to be present in the baseline — they exercise
the existing `enter_worktree` tool and `agent isolation: "worktree"` parameter
to confirm the symlink loop fires on those code paths too.
The globally installed `qwen` may predate PR #4073 (Phase A+B, merged 2026-05-14)
and therefore lack these tools entirely. When that is the case, E2 / E3 cannot
validate "symlink absent because D-2 is absent" — they collapse to "tool
absent." Add this guard at the top of each:
```bash
HAS_ENTER_WORKTREE=$($QWEN "list your tools and stop" --approval-mode yolo --output-format json 2>/dev/null \
| jq -e '.[] | select(.type=="system") | .tools | index("enter_worktree")' >/dev/null && echo yes || echo no)
if [ "$HAS_ENTER_WORKTREE" != "yes" ]; then
echo "SKIP: enter_worktree absent in baseline — E2/E3 require Phase A+B"
exit 0
fi
```
For Phase 6 (post-impl) verification the local build inherently contains
Phase A-C, so the guard is a no-op and the tests run in full.
## Test environment template
Each group runs in its own temp git repo and tmux session:
```bash
TEST_DIR=$(mktemp -d -t qwen-wt-phd-XXXXXX)
TEST_DIR=$(cd "$TEST_DIR" && pwd -P) # resolve symlinks (macOS /var → /private/var)
cd "$TEST_DIR"
git init -q -b main
git config user.email t@e.com
git config user.name t
git config commit.gpgsign false
echo "hello" > README.md
git add README.md
git commit -q -m "initial" --no-verify
PROJECT_ID=$(node -e "console.log(process.argv[1].replace(/[^a-zA-Z0-9]/g,'-'))" "$TEST_DIR")
QWEN="node /Users/mochi/code/qwen-code/.claude/worktrees/tender-jemison-037f0a/dist/cli.js"
```
PR-ref tests (Group F) additionally require a checked-out clone of a public
GitHub repo with at least one merged PR. Use this repo (qwen-code itself) as
the test target — PR `#4174` (Phase C) is a guaranteed-present reference.
---
## Group A: `--worktree` flag basic forms
**Mode:** headless, `--approval-mode yolo`, `--output-format json`
### A1: bare `--worktree` (auto-slug)
```bash
$QWEN --worktree "say hello and stop" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/a1.out
# A `worktree_started` system event is emitted at startup. The `notice`
# field contains the slug (auto-generated `adj-noun-XXXXXX`) inside the
# rendered text. Use `jq -e` so a missing event is a non-zero exit
# (instead of silent `null`).
jq -e '.[] | select(.type=="system" and .subtype=="worktree_started") | .data.notice | test("\"[a-z]+-[a-z]+-[0-9a-f]{6}\"")' < /tmp/a1.out
# The init system message's `cwd` should also point inside the worktree.
jq -e '.[] | select(.type=="system" and .subtype=="init") | .cwd | test("/\\.qwen/worktrees/[a-z]+-[a-z]+-[0-9a-f]{6}$")' < /tmp/a1.out
ls -d "$TEST_DIR/.qwen/worktrees/"*
```
**Expected (post-impl):**
- `worktree_started` event with `.data.notice` containing the auto slug
- Init `.cwd` ends with `.qwen/worktrees/<auto-slug>`
- Exactly one worktree directory under `.qwen/worktrees/`
- Branch named `worktree-<slug>` exists (`git branch | grep worktree-`)
**Expected (pre-impl baseline):** yargs rejects `--worktree` with
"Unknown argument" error and exit code != 0.
### A2: `--worktree my-feature` (explicit slug)
```bash
$QWEN --worktree my-feature "say hello and stop" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/a2.out
ls -d "$TEST_DIR/.qwen/worktrees/my-feature"
git -C "$TEST_DIR" branch | grep "worktree-my-feature"
```
**Expected (post-impl):** worktree dir `my-feature/` and branch
`worktree-my-feature` both exist.
### A3: `--worktree=my-feature` (= form)
Identical to A2 with `=` form. Cleanup between A2 and A3 required (different
TEST_DIR).
```bash
$QWEN --worktree=my-feature "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/a3.out
```
**Expected (post-impl):** same as A2.
### A4: invalid slug rejected before any git operation
```bash
$QWEN --worktree "../escape" "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/a4.out
echo "exit=$?"
ls "$TEST_DIR/.qwen/worktrees/" 2>/dev/null
```
**Expected (post-impl):**
- Process exits with non-zero status
- Stderr or final result message mentions "invalid slug" / "not allowed"
- `.qwen/worktrees/` directory does not exist (worktree creation never started)
### A5: not a git repository → fail-close
```bash
NON_GIT=$(mktemp -d)
cd "$NON_GIT"
$QWEN --worktree "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/a5.out
echo "exit=$?"
```
**Expected (post-impl):** exit != 0, message mentions "not a git repository"
or "git init".
---
## Group B: cwd + sidecar after `--worktree`
### B1: sidecar written with all six fields
```bash
SESSION_ID=$(uuidgen)
$QWEN --worktree b1-test --session-id "$SESSION_ID" "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/b1.out
SIDECAR=~/.qwen/projects/$PROJECT_ID/chats/$SESSION_ID.worktree.json
jq '.slug, .worktreePath, .worktreeBranch, .originalCwd, .originalBranch, .originalHeadCommit' \
< "$SIDECAR"
```
**Expected:**
- `slug = "b1-test"`
- `worktreePath` ends with `.qwen/worktrees/b1-test`
- `worktreeBranch = "worktree-b1-test"`
- `originalCwd` = `$TEST_DIR` (resolved)
- `originalBranch = "main"`
- `originalHeadCommit` matches `[0-9a-f]{40}`
### B2: `process.cwd()` switched at startup
```bash
$QWEN --worktree b2-test "run the shell tool with command 'pwd', then stop" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/b2.out
# Extract the shell tool's stdout from the user-message tool_result
jq -r '.[] | select(.type=="user") | .message.content[] | select(.tool_use_id != null) | .content' \
< /tmp/b2.out | head -5
```
**Expected (post-impl):** the `pwd` output equals `$TEST_DIR/.qwen/worktrees/b2-test`.
### B3: `Config.targetDir` switched (Footer / status payload)
```bash
$QWEN --worktree b3-test "run the shell tool with command 'pwd && git rev-parse --abbrev-ref HEAD', then stop" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/b3.out
jq -r '.[] | select(.type=="user") | .message.content[] | select(.tool_use_id != null) | .content' \
< /tmp/b3.out
```
**Expected (post-impl):** branch is `worktree-b3-test` AND working directory
is inside the worktree.
---
## Group C: `--worktree` × `--resume` precedence
### C1: `--worktree` wins over saved sidecar (different slug)
```bash
# Run 1: create a session with worktree "first"
SESSION_ID=$(uuidgen)
$QWEN --worktree first --session-id "$SESSION_ID" "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/c1-run1.out
# Run 2: resume the same session but request a different worktree
$QWEN --resume "$SESSION_ID" --worktree second "say hi again" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/c1-run2.out
# Sidecar should now point at "second"
SIDECAR=~/.qwen/projects/$PROJECT_ID/chats/$SESSION_ID.worktree.json
jq -r '.slug' < "$SIDECAR"
# Both worktree dirs should exist on disk (first was never removed, just unlinked)
ls -d "$TEST_DIR/.qwen/worktrees/"*
```
**Expected (post-impl):**
- Sidecar `.slug` = `"second"`
- Both `first/` and `second/` directories exist
- Run 2's stderr or init `worktree_overridden` message mentions "--worktree
overrides the resumed session's worktree"
### C2: stale sidecar (manually deleted dir) + `--worktree` → fresh worktree
```bash
SESSION_ID=$(uuidgen)
$QWEN --worktree c2 --session-id "$SESSION_ID" "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/c2-run1.out
rm -rf "$TEST_DIR/.qwen/worktrees/c2" # simulate user-deleted dir
$QWEN --resume "$SESSION_ID" --worktree c2-fresh "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/c2-run2.out
ls -d "$TEST_DIR/.qwen/worktrees/"*
```
**Expected (post-impl):** only `c2-fresh/` exists; sidecar updated to `c2-fresh`.
---
## Group D: WorktreeExitDialog regression (`--worktree`-started session)
**Mode:** interactive (tmux). Verifies Phase C dialog still triggers when the
worktree was created by the CLI flag rather than `EnterWorktreeTool`.
### D1: 2x Ctrl+C → dialog appears
```bash
tmux new-session -d -s d1 -x 200 -y 50 \
"cd $TEST_DIR && $QWEN --worktree d1-test --approval-mode yolo"
sleep 3
# Verify worktree is active (Footer indicator)
tmux capture-pane -t d1 -p -S -50 | grep -q "⎇ worktree-d1-test"
# Send Ctrl+C twice
tmux send-keys -t d1 C-c
sleep 0.3
tmux send-keys -t d1 C-c
sleep 1
tmux capture-pane -t d1 -p -S -50 | grep -E "Active worktree|Keep worktree|Remove worktree"
tmux kill-session -t d1
```
**Expected (post-impl):** dialog text "Active worktree: \"d1-test\" …" and the
three radio options appear.
### D2: Dialog → Cancel → session stays alive
```bash
tmux new-session -d -s d2 -x 200 -y 50 \
"cd $TEST_DIR && $QWEN --worktree d2-test --approval-mode yolo"
sleep 3
tmux send-keys -t d2 C-c; sleep 0.3; tmux send-keys -t d2 C-c; sleep 1
# Navigate to "Cancel" (third option) and select
tmux send-keys -t d2 Down Down Enter
sleep 1
tmux capture-pane -t d2 -p -S -10 | grep -q "Type your message"
ls -d "$TEST_DIR/.qwen/worktrees/d2-test" # still exists
tmux kill-session -t d2
```
**Expected (post-impl):** prompt input reappears; worktree dir is still on disk.
### D3: Dialog → Remove → worktree + branch + sidecar all gone
```bash
SESSION_ID=$(uuidgen)
tmux new-session -d -s d3 -x 200 -y 50 \
"cd $TEST_DIR && $QWEN --worktree d3-test --session-id $SESSION_ID --approval-mode yolo"
sleep 3
tmux send-keys -t d3 C-c; sleep 0.3; tmux send-keys -t d3 C-c; sleep 1
tmux send-keys -t d3 Down Enter # select "Remove worktree and branch"
sleep 3
tmux kill-session -t d3
ls "$TEST_DIR/.qwen/worktrees/d3-test" 2>/dev/null && echo "FAIL: dir exists"
git -C "$TEST_DIR" branch | grep "worktree-d3-test" && echo "FAIL: branch exists"
test ! -f ~/.qwen/projects/$PROJECT_ID/chats/$SESSION_ID.worktree.json && echo "PASS: sidecar gone"
```
**Expected (post-impl):** dir, branch, and sidecar all removed.
---
## Group E: `worktree.symlinkDirectories`
**Mode:** headless. Settings configured via temp settings file.
### Setup template
```bash
mkdir -p "$TEST_DIR/node_modules"
echo "package.json" > "$TEST_DIR/node_modules/.placeholder"
mkdir -p "$TEST_DIR/.qwen"
cat > "$TEST_DIR/.qwen/settings.json" <<'EOF'
{
"worktree": {
"symlinkDirectories": ["node_modules"]
}
}
EOF
```
### E1: `--worktree` path applies symlink
```bash
$QWEN --worktree e1-test "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /dev/null
ls -la "$TEST_DIR/.qwen/worktrees/e1-test/node_modules"
readlink "$TEST_DIR/.qwen/worktrees/e1-test/node_modules"
```
**Expected (post-impl):** `node_modules` inside the worktree is a symlink
pointing to `$TEST_DIR/node_modules`.
### E2: `EnterWorktreeTool` path applies symlink
```bash
$QWEN "use enter_worktree to create a worktree named e2-test, then stop" \
--approval-mode yolo --output-format json 2>/dev/null > /dev/null
readlink "$TEST_DIR/.qwen/worktrees/e2-test/node_modules"
```
**Expected (post-impl):** same symlink target.
### E3: AgentTool isolation path applies symlink
Requires a sub-agent definition. Use the built-in fork mechanism:
```bash
$QWEN "use the agent tool with subagent_type='general-purpose', isolation='worktree', description='check node_modules', prompt='run pwd and ls -la node_modules then exit'" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/e3.out
# Extract agent worktree dir from result message
jq -r '.[] | select(.type=="assistant") | .message.content[] | select(.type=="tool_use") | .input' \
< /tmp/e3.out | head -5
# After execution find the agent-<7hex> worktree
ls -la "$TEST_DIR/.qwen/worktrees/"agent-*/node_modules 2>/dev/null | head -3
```
**Expected (post-impl):** symlink exists inside the `agent-<hex>` worktree
(unless auto-cleaned because there were no changes — in that case the
"no changes" path doesn't validate symlink behavior, escalate to a forced
change test).
### E4: missing source dir → silently skipped, worktree still created
```bash
cat > "$TEST_DIR/.qwen/settings.json" <<'EOF'
{ "worktree": { "symlinkDirectories": ["does-not-exist"] } }
EOF
$QWEN --worktree e4-test "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/e4.out
ls -d "$TEST_DIR/.qwen/worktrees/e4-test"
ls "$TEST_DIR/.qwen/worktrees/e4-test/does-not-exist" 2>/dev/null && echo "UNEXPECTED"
```
**Expected (post-impl):** worktree directory exists, the missing entry is
not created inside it, process exit = 0.
### E5: existing dest → silently skipped, no overwrite
```bash
# Pre-create a worktree at expected slug then re-create — this is contrived
# because Phase D paths should be fresh, but it exercises the EEXIST guard.
mkdir -p "$TEST_DIR/.qwen/worktrees/e5-test/node_modules"
echo "preexisting" > "$TEST_DIR/.qwen/worktrees/e5-test/node_modules/.marker"
# Force re-creation via EnterWorktreeTool (CLI would refuse "already exists")
$QWEN "use enter_worktree with name='e5-test' to retry" --approval-mode yolo 2>/dev/null
# either: tool errors out cleanly, OR symlink is skipped — both acceptable
test -f "$TEST_DIR/.qwen/worktrees/e5-test/node_modules/.marker" && echo "PASS: not overwritten"
```
**Expected (post-impl):** preexisting `.marker` survives; no symlink replaces
the dir.
### E6: absolute path / `../` → rejected
```bash
cat > "$TEST_DIR/.qwen/settings.json" <<'EOF'
{ "worktree": { "symlinkDirectories": ["/etc", "../escape"] } }
EOF
$QWEN --worktree e6-test "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/e6.out
ls "$TEST_DIR/.qwen/worktrees/e6-test/" | head -10
```
**Expected (post-impl):** worktree exists; neither `etc` nor `escape` linked
inside it; debug log carries warn lines.
---
## Group F: PR reference
**Mode:** headless. Requires `origin` remote pointing at a public GitHub repo.
### Setup template
```bash
# Use qwen-code itself as the test repo
TEST_DIR=$(mktemp -d -t qwen-wt-phd-pr-XXXXXX)
TEST_DIR=$(cd "$TEST_DIR" && pwd -P)
cd "$TEST_DIR"
git clone --depth 1 https://github.com/QwenLM/qwen-code.git .
PROJECT_ID=$(node -e "console.log(process.argv[1].replace(/[^a-zA-Z0-9]/g,'-'))" "$TEST_DIR")
```
### F1: `--worktree=#4174` parses + fetches
```bash
$QWEN --worktree=#4174 "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/f1.out
ls -d "$TEST_DIR/.qwen/worktrees/pr-4174"
git -C "$TEST_DIR/.qwen/worktrees/pr-4174" rev-parse --abbrev-ref HEAD
```
**Expected (post-impl):**
- Worktree dir `pr-4174/` exists
- HEAD branch = `worktree-pr-4174`
- The branch's tip resolves (git log -1) without error
### F2: full URL form
```bash
$QWEN --worktree "https://github.com/QwenLM/qwen-code/pull/4174" "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/f2.out
ls -d "$TEST_DIR/.qwen/worktrees/pr-4174"
```
**Expected (post-impl):** same as F1.
### F3: missing `origin` remote → fail-close
```bash
cd "$TEST_DIR" && git remote remove origin
$QWEN --worktree=#4174 "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/f3.out
echo "exit=$?"
```
**Expected (post-impl):** exit != 0; message mentions `origin` remote.
### F4: invalid PR number → fail-close
```bash
$QWEN --worktree=#999999999 "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/f4.out
echo "exit=$?"
```
**Expected (post-impl):** exit != 0; message mentions "Failed to fetch PR".
30-second timeout cap respected (test runtime < 35s).
### F5: malformed `#abc` falls through to slug validation
```bash
$QWEN --worktree=#abc "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/f5.out
echo "exit=$?"
```
**Expected (post-impl):** treated as literal slug `#abc`, rejected by
`validateUserWorktreeSlug` because `#` is not allowed. Exit != 0.
### F6: PR worktree gets symlinks too (cross-cut with E)
```bash
cat > "$TEST_DIR/.qwen/settings.json" <<'EOF'
{ "worktree": { "symlinkDirectories": ["node_modules"] } }
EOF
mkdir -p "$TEST_DIR/node_modules" && echo x > "$TEST_DIR/node_modules/.marker"
$QWEN --worktree=#4174 "say hi" --approval-mode yolo --output-format json 2>/dev/null > /dev/null
readlink "$TEST_DIR/.qwen/worktrees/pr-4174/node_modules"
```
**Expected (post-impl):** symlink target = `$TEST_DIR/node_modules`.
---
## Group G: Integration + edge cases
### G1: full lifecycle — start → write → Keep → resume
> **Pre-impl note:** Against the baseline this test exits before `sleep 3`
> finishes (yargs rejects `--worktree` immediately and the tmux pane dies).
> The `capture-pane` call then errors with "can't find pane". This is
> expected — record as PASS-by-rejection. Wrap captures with `|| true` for
> the dry-run, or skip G1 entirely in baseline mode.
```bash
SESSION_ID=$(uuidgen)
tmux new-session -d -s g1 -x 200 -y 50 \
"cd $TEST_DIR && $QWEN --worktree g1-test --session-id $SESSION_ID --approval-mode yolo 2>&1 | tee /tmp/g1-stderr.out"
sleep 3
tmux send-keys -t g1 "use the write_file tool to create file 'work.txt' with content 'phase d test'"
sleep 0.3; tmux send-keys -t g1 Enter
sleep 8
tmux send-keys -t g1 C-c; sleep 0.3; tmux send-keys -t g1 C-c; sleep 1
tmux send-keys -t g1 Enter # default = "Keep"
sleep 2
tmux kill-session -t g1
# File survived
cat "$TEST_DIR/.qwen/worktrees/g1-test/work.txt"
# Resume reattaches
tmux new-session -d -s g1b -x 200 -y 50 \
"cd $TEST_DIR && $QWEN --resume $SESSION_ID --approval-mode yolo"
sleep 4
tmux capture-pane -t g1b -p -S -50 | grep -E "⎇ worktree-g1-test|Resumed"
tmux kill-session -t g1b
```
**Expected (post-impl):**
- `work.txt` inside the worktree contains the written content
- Resumed session Footer shows `⎇ worktree-g1-test (g1-test)`
- INFO history item or `<system-reminder>` mentions "Resumed"
### G2: relative path arg resolved before cwd switch
```bash
# Create an mcp config in TEST_DIR and reference it relatively.
# --mcp-config takes a file path; if the test plan path is resolved AFTER
# the --worktree cwd switch, the file won't be found inside the worktree
# and the CLI will error out. If resolved BEFORE the switch (correct), the
# file is loaded from TEST_DIR.
cat > "$TEST_DIR/mcp.json" <<'EOF'
{ "mcpServers": {} }
EOF
cd "$TEST_DIR"
$QWEN --worktree g2-test --mcp-config ./mcp.json "say hi" \
--approval-mode yolo --output-format json 2>/dev/null > /tmp/g2.out
echo "exit=$?"
jq -r '.[] | select(.type=="result") | .result' < /tmp/g2.out | head -3
```
**Expected (post-impl):** exit = 0; the model responds normally (the empty
mcp config means no MCP servers but no error either).
**Expected (pre-impl baseline):** yargs rejects `--worktree` (the test
cannot distinguish "worktree flag missing" from "mcp config resolution
broken" until the flag itself exists).
---
## Run order + parallelism
| Group | Mode | Runtime | Parallel-safe? |
| ----- | ------------ | ------- | ---------------------------- |
| A | headless | ~30s | yes (own TEST_DIR) |
| B | headless | ~20s | yes |
| C | headless | ~40s | yes |
| D | tmux | ~30s | yes (own session name) |
| E | headless | ~60s | yes |
| F | headless+net | ~60s | NO — shares the GitHub clone |
| G | mixed | ~60s | yes |
Run A/B/C/D/E/G in parallel; F serially after the clone setup.
## Reproduction report
### Phase 4 dry-run — baseline `qwen` v0.15.11 (2026-05-20)
Runtime: 3 parallel `test-engineer` agents, ~7 minutes total. Baseline lacks
both Phase D (expected) and Phase A+B (older binary than expected — see
E2/E3 caveat).
| Group | Result | Notes |
| -------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| A1 (bare flag) | ✅ | yargs `Unknown argument: worktree`, exit 1 |
| A2 (explicit slug) | ✅ | same |
| A3 (= form) | ✅ | same |
| A4 (invalid slug) | ✅ | yargs rejects before slug validation |
| A5 (non-git dir) | ✅ | same |
| B1 (sidecar fields) | ✅ | sidecar correctly absent; jq selector valid against sample data |
| B2 (cwd switch) | ✅ | shell-tool `tool_result.content` jq selector verified against real output |
| B3 (targetDir switch) | ✅ | same selector |
| C1 (--worktree beats sidecar) | ✅ | both runs exit 1, no sidecar |
| C2 (stale sidecar + fresh) | ✅ | same |
| E1 (--worktree symlink) | ✅ | flag rejected, no symlink — pre-impl confirmed |
| E2 (EnterWorktree symlink) | ⚠️ N/A | baseline lacks `enter_worktree` tool (older than PR #4073); guard now skips this case |
| E3 (AgentTool isolation symlink) | ⚠️ N/A | baseline `agent` schema silently drops `isolation` param; guard skips |
| E4 (missing source skip) | ✅ | flag rejected |
| E5 (existing dest not overwrite) | ⚠️ trivial | preexisting `.marker` survived but only because tool couldn't run |
| E6 (path traversal reject) | ✅ | flag rejected, no symlinks |
| F1 (--worktree=#4174 fetch) | ✅ | `Unknown argument: worktree`, no network call |
| F2 (full URL form) | ✅ | same |
| F3 (missing origin) | ✅ | rejected before git check |
| F4 (invalid PR number) | ✅ | rejected before fetch |
| F5 (`#abc` malformed) | ✅ | same |
| F6 (PR + symlinkDirs) | ✅ | same |
| G1 (lifecycle tmux) | ⚠️ partial | tmux pane dies on flag rejection; record-by-exit-code works |
| G2 (relative path) | ✅ | (after switching to `--mcp-config ./mcp.json`) yargs rejects worktree first |
**Conclusion:** test scripts are fundamentally sound. 19 / 24 cases cleanly
detect pre-impl baseline; 3 cases (E2/E3/E5) need the baseline to include
Phase A+B (which the local Phase 6 build will provide); 2 cases (G1/G2) had
script bugs that are now fixed. **Ready to proceed to Phase 5
implementation.**
### Phase 6 verification — local build
**Binary**: `node /Users/mochi/code/qwen-code/.claude/worktrees/tender-jemison-037f0a/dist/cli.js`
**Date**: 2026-05-20
**Scope**: Groups A, B, C, E, F, G (6 parallel `test-engineer` agents)
| Group | Result | Notes |
| ---------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A1 (bare flag) | ✅ (with doc tip) | yargs consumes the next positional as the slug value when user passes `qwen --worktree "say hi"`; quickstart now tells users to use `=` form or put the prompt before the flag. Auto-slug feature itself confirmed via `qwen --worktree --approval-mode yolo "say hi"` → slug `bright-elm-8a4c12`, init `.cwd` ends with `.qwen/worktrees/<auto-slug>`. |
| A2 (explicit slug) | ✅ | dir `.qwen/worktrees/my-feature` + branch `worktree-my-feature` |
| A3 (= form) | ✅ | identical to A2 |
| A4 (invalid slug) | ✅ | exit=1, message: `Worktree name may only contain letters, digits, dots, underscores, and hyphens.`, no worktree dir |
| A5 (non-git dir) | ✅ | exit=1, message: `not a git repository. Run \`git init\` first or relaunch from inside one.` |
| B1 (sidecar fields) | ✅ | All 6 fields present and correct; sidecar lives under worktree projectHash as designed |
| B2 (cwd switch) | ✅ | `pwd` inside shell tool returned worktree path exactly |
| B3 (branch + cwd) | ✅ | `pwd` = worktree path, `git rev-parse --abbrev-ref HEAD` = `worktree-b3-test` |
| C1 (cross-slug override) | ❌ → **known limitation** | Sessions are bound to `projectHash(cwd)`; `--worktree second --resume <sid-from-first>` can't find the session. Documented in user docs Limitations. A future Config refactor (anchor storage at repo root) would lift this. |
| C2 (stale sidecar + new worktree) | ❌ → **same root cause** | Same architectural constraint. |
| E1 (`--worktree` symlink) | ✅ | `node_modules` symlinked into the new worktree |
| E2 (`enter_worktree` symlink) | ✅ | same code path via `createUserWorktree` |
| E3 (agent isolation symlink) | ⚠️ test-setup | model committed `node_modules` (because the agent guard refused dirty state); EEXIST guard then correctly skipped the symlink. Code path is correct; for a clean E3 the test plan needs to pre-`.gitignore` `node_modules`. |
| E4 (missing source skip) | ✅ | worktree created, no entry, exit 0 |
| E5 (existing dest no overwrite) | ✅ | preexisting marker survived |
| E6 (absolute / `..` rejected) | ✅ | neither path linked |
| F1 (`--worktree=#4174` fetch) | ✅ | worktree dir `pr-4174/`, branch `worktree-pr-4174`, tip commit `8f4fe8e feat(cli): per-turn /diff…`; local-remote substitute (sandbox blocks real GitHub) |
| F2 (full URL form) | ✅ | same result; URL parsed → PR #4174 → local origin fetch succeeded |
| F3 (missing origin) | ✅ | exit=1 in 2s; message mentions adding `origin` remote |
| F4 (invalid PR #999999999) | ✅ | exit=1 in 2s; "PR does not exist on origin"; well within 35s cap |
| F5 (malformed `#abc`) | ✅ | slug validation rejects `#` |
| F6 (PR worktree + symlinks) | ✅ | symlink `pr-4174/node_modules` → `$TEST_DIR/node_modules` confirmed |
| G1.a (start + write + Keep) | ✅ | TUI flow, Footer indicator, dialog options, file persists |
| G1.b (`--resume … --worktree foo`) | ❌ → **fixed in this PR** | Original: `--worktree: Worktree already exists at …`. Phase 6 fix added the re-attach branch in `setupStartupWorktree`. Verified post-fix via smoke test (`--worktree foo` twice → second emits the `worktree_started` notice, no error) + new unit tests in `worktreeStartup.test.ts`. |
| G2 (relative `--mcp-config`) | ❌ → **fixed in this PR** | Original: exit=52, `Invalid MCP configuration … is not valid JSON`. Phase 6 fix normalizes path-taking argv fields (`mcpConfig`, `openaiLoggingDir`, `jsonFile`, `inputFile`, `telemetryOutfile`, `includeDirectories`) against the launch cwd BEFORE `setupStartupWorktree` chdirs. Verified post-fix via smoke test (`--worktree foo --mcp-config ./mcp.json` → model responds normally). |
**Phase 6 net result:** 22 / 24 cases passed post-fix; 2 cases (C1/C2) hit an
architectural limitation now documented; 1 case (E3) is a test-setup quirk,
not an implementation issue. **Ready for Phase 7 code review.**
### Fix references (Phase 6 fixes that landed in this PR)
| Fix | File | Change |
| ----------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Re-attach to existing worktree (G1.b) | `packages/cli/src/startup/worktreeStartup.ts` | Added pre-create check: if dir is a registered worktree on the expected branch, skip create + chdir |
| `getRegisteredWorktreeBranch()` helper | `packages/core/src/services/gitWorktreeService.ts` | Probes `git rev-parse --abbrev-ref HEAD` against the candidate path |
| Path normalization before chdir (G2) | `packages/cli/src/gemini.tsx` | Resolves `mcpConfig`, `openaiLoggingDir`, `jsonFile`, `inputFile`, `telemetryOutfile`, `includeDirectories` against launch cwd when `--worktree` is set |
| Documentation: yargs flag ordering tip + Limitations update | `docs/users/features/worktree.md` | Quick Start tip + new Limitations bullets (cross-slug, path-arg behavior) |
| Unit tests for re-attach | `packages/cli/src/startup/worktreeStartup.test.ts` | Added 2 tests: happy re-attach + "different branch occupies slot" guard |
**Phase 6 Group F network note**: The sandbox blocks `git fetch` to `https://github.com` with HTTP 403. F1/F2/F4/F6 were retested against a local bare repo (`git init --bare`) seeded with `refs/pull/4174/head` pointing at a commit whose message is `feat(cli): per-turn /diff with interactive dialog (#4277)`. F3 and F5 are network-independent and were verified directly. The local-remote substitute fully exercises the parsing + fetch + worktree-creation code path.
---
## Reproduction report — Phase 4 dry-run (Groups F + G), 2026-05-20
**Binary**: `qwen` (globally installed, v0.15.11 at `/Users/mochi/.nvm/versions/node/v22.21.1/bin/qwen`)
**Override**: `QWEN="qwen"`
### Results table
| Test ID | Result | Evidence | Fix suggestion |
| ------------------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| F1 `--worktree=#4174` | PASS | `Unknown argument: worktree`, exit=1 | None — expected baseline failure |
| F2 `--worktree <url>` | PASS | `Unknown argument: worktree`, exit=1 | None — expected baseline failure |
| F3 missing origin | PASS | `Unknown argument: worktree`, exit=1 — yargs rejected before any git op | None |
| F4 invalid PR #999999999 | PASS | `Unknown argument: worktree`, exit=1 | None |
| F5 malformed `#abc` | PASS | `Unknown argument: worktree`, exit=1 | None |
| F6 PR + symlinkDirs | PASS | `Unknown argument: worktree`, exit=1 | None |
| G1 lifecycle (tmux) | PASS | `Unknown argument: worktree` emitted to stdout captured in `/tmp/g1_raw.out`; tmux session exited immediately, pane was already dead by capture time | SCRIPT-BUG: see note below |
| G2 relative path | PASS | `Unknown arguments: worktree, prompt-file, promptFile`, exit=1 | SCRIPT-BUG: see note below |
### Observed behavior (all cases)
Every invocation of `--worktree` (bare, `=` form, `#<N>` form, full URL, combined with `--prompt-file`) was rejected at the yargs argument-parsing layer with exit code 1 before any application logic ran. The exact error strings are:
- `Unknown argument: worktree` (single unknown arg)
- `Unknown arguments: worktree, prompt-file, promptFile` (G2: both `--worktree` and `--prompt-file` are unknown, listed together)
No git operations, no network calls, no filesystem writes occurred in any test.
### Expected behavior
Identical rejection — this is the correct pre-implementation baseline. All 8 tests PASS in the dry-run sense (the plan correctly detects that the features do not exist).
### Key context
The failure mode is uniformly at the yargs layer, not downstream. This confirms the test plan's detection strategy is sound: once `--worktree` is wired into yargs, these tests will stop failing at this layer and will instead exercise the actual implementation paths (F1-F6 will hit git fetch, G1 will hit the TUI lifecycle, G2 will hit `--prompt-file` resolution).
### SCRIPT-BUG notes for the test plan
**G1 (tmux):** The tmux session command pipes through `tee` with a subshell `echo 'PROC_EXIT='$?` that captures the exit of `tee`, not of `qwen`. When the process exits instantly (as with an Unknown argument error), the session terminates before `sleep 3` finishes and the pane name `g1dry` is gone by the time `tmux capture-pane` runs, producing `can't find pane: g1dry`. Fix: use `|| true` after `tmux capture-pane`, or add a `|| sleep 0` guard; better still, for the baseline-fail case redirect stderr+stdout to a file outside tmux and check the file directly (as done here via `tee /tmp/g1_raw.out`).
**G2 (`--prompt-file`):** The test plan uses `--prompt-file ./relative.txt` as a combined test with `--worktree`. In the baseline, `--prompt-file` is also an unknown argument (it does not exist in v0.15.11 yargs schema either — the flag is `--prompt-interactive` / `-p`). The error lists both unknown args together. The plan should note that `--prompt-file` will need to be implemented alongside `--worktree`, or use an existing flag (e.g. pipe via stdin or use `--prompt`) for the relative-path resolution test.

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,6 @@
export default {
settings: 'Settings',
auth: 'Authentication',
memory: {
display: 'hidden',
},
'qwen-ignore': 'Ignoring Files',
'trusted-folders': 'Trusted Folders',
themes: 'Themes',

View File

@ -143,10 +143,16 @@ Settings are organized into categories. Most settings should be placed within th
| -------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- |
| `model.name` | string | The Qwen model to use for conversations. | `undefined` |
| `model.maxSessionTurns` | number | Maximum number of user/model/tool turns to keep in a session. -1 means unlimited. | `-1` |
| `model.maxWallTimeSeconds` | number | Wall-clock budget for headless / unattended runs, in seconds. `-1` means unlimited. Overridable per-invocation via `--max-wall-time`, which requires a positive duration (`90`, `30s`, `5m`, `1h`, `1.5h`); the minimum is 1 second — sub-second values (`500ms`, `0.5`) are rejected as typos. Omit the flag to fall back to this setting. Aborts with exit code 55 when exceeded. | `-1` |
| `model.maxToolCalls` | number | Cumulative tool-call budget for a run (counts every executed tool, success or failure; `structured_output` under `--json-schema` is exempt). `-1` means unlimited; `0` means "no tool calls allowed". Capped at 1,000,000 to catch typos. Overridable via `--max-tool-calls`. Aborts with exit code 55 when exceeded. | `-1` |
| `model.generationConfig` | object | Advanced overrides passed to the underlying content generator. Supports request controls such as `timeout`, `maxRetries`, `enableCacheControl`, `splitToolMedia` (set `true` for strict OpenAI-compatible servers like LM Studio that reject non-text content on `role: "tool"` messages — splits media into a follow-up user message), `contextWindowSize` (override model's context window size), `modalities` (override auto-detected input modalities), `customHeaders` (custom HTTP headers for API requests), and `extra_body` (additional body parameters for OpenAI-compatible API requests only), along with fine-tuning knobs under `samplingParams` (for example `temperature`, `top_p`, `max_tokens`). Leave unset to rely on provider defaults. | `undefined` |
| `model.chatCompression.contextPercentageThreshold` | number | **REMOVED.** Auto-compaction now uses a three-tier threshold ladder (warn / auto / hard) computed internally from the model's context window via the `computeThresholds()` function — no longer user-configurable. Setting this field in `settings.json` is silently ignored, and a one-line deprecation warning is emitted to stderr at startup. There is currently no replacement for "disable compression entirely" — reactive overflow recovery remains the safety net at the API layer if compression itself fails. (See PR #4345 / `docs/design/auto-compaction-threshold-redesign.md` for the redesign rationale.) | `N/A` |
| `model.chatCompression.contextPercentageThreshold` | number | **REMOVED.** Auto-compaction now uses a three-tier threshold ladder (warn / auto / hard) computed internally from the model's context window via the `computeThresholds()` function — no longer user-configurable. Setting this field in `settings.json` is silently ignored (no startup warning). There is currently no replacement for "disable compression entirely" — reactive overflow recovery remains the safety net at the API layer if compression itself fails. (See PR #4345 / `docs/design/auto-compaction-threshold-redesign.md` for the redesign rationale.) | `N/A` |
| `model.chatCompression.maxRecentFilesToRetain` | number | Number of most-recently-touched files whose current content is restored (embedded if small, otherwise referenced by path) into history after auto-compaction. `0` restores none. Env override: `QWEN_COMPACT_MAX_RECENT_FILES`. | `5` |
| `model.chatCompression.maxRecentImagesToRetain` | number | Number of most-recent images (tool screenshots / user pastes) restored into history after auto-compaction. `0` restores none. Env override: `QWEN_COMPACT_MAX_RECENT_IMAGES`. | `3` |
| `model.chatCompression.enableScreenshotTrigger` | boolean | When `true`, auto-compaction also fires once the number of tool-returned images accumulated in history reaches `screenshotTriggerThreshold`, independent of token usage — aimed at computer-use sessions where frequent screenshots dilute model attention. Counts only images returned inside tool results, not user-pasted images. Env override: `QWEN_COMPACT_SCREENSHOT_TRIGGER` (`1`/`true`/`0`/`false`). | `true` |
| `model.chatCompression.screenshotTriggerThreshold` | number | Tool-returned image count at or above which the screenshot trigger fires (only when `enableScreenshotTrigger`). Compaction resets the count — surviving images are re-embedded as top-level parts, which the trigger doesn't count — so it won't immediately re-fire. Env override: `QWEN_COMPACT_SCREENSHOT_THRESHOLD`. | `50` |
| `model.skipNextSpeakerCheck` | boolean | Skip the next speaker check. | `false` |
| `model.skipLoopDetection` | boolean | Disables loop detection checks. Loop detection prevents infinite loops in AI responses but can generate false positives that interrupt legitimate workflows. Enable this option if you experience frequent false positive loop detection interruptions. | `false` |
| `model.skipLoopDetection` | boolean | Disables streaming loop detection checks. Defaults to `true` (loop detection is skipped) to avoid false positives interrupting legitimate workflows. Set to `false` to re-enable streaming loop detection — useful as a guardrail in headless / non-interactive runs where stuck repetition can otherwise waste budget. | `true` |
| `model.skipStartupContext` | boolean | Skips sending the startup workspace context (environment summary and acknowledgement) at the beginning of each session. Enable this if you prefer to provide context manually or want to save tokens on startup. | `false` |
| `model.enableOpenAILogging` | boolean | Enables logging of OpenAI API calls for debugging and analysis. When enabled, API requests and responses are logged to JSON files. | `false` |
| `model.openAILoggingDir` | string | Custom directory path for OpenAI API logs. If not specified, defaults to `logs/openai` in the current working directory. Supports absolute paths, relative paths (resolved from current working directory), and `~` expansion (home directory). | `undefined` |
@ -272,7 +278,8 @@ If you are experiencing performance issues with file searching (e.g., with `@` c
| Setting | Type | Description | Default |
| -------------------------------- | ------- | --------------------------------------------------------------------------------- | ------- |
| `memory.enableManagedAutoMemory` | boolean | Enable background extraction of memories from conversations. | `true` |
| `memory.enableManagedAutoDream` | boolean | Enable automatic consolidation (deduplication and cleanup) of collected memories. | `false` |
| `memory.enableManagedAutoDream` | boolean | Enable automatic consolidation (deduplication and cleanup) of collected memories. | `true` |
| `memory.enableAutoSkill` | boolean | Enable background review for reusable project skills after tool-heavy sessions. | `true` |
See [Memory](../features/memory) for details on how auto-memory works and how to use the `/memory`, `/remember`, and `/dream` commands.
@ -703,7 +710,9 @@ Qwen Code can execute potentially unsafe operations (like shell commands and fil
- Using `--sandbox` or `-s` flag.
- Setting `QWEN_SANDBOX` environment variable.
- Sandbox is enabled when using `--yolo` or `--approval-mode=yolo` by default.
- Setting `tools.sandbox` in settings.
> ⚠️ **`--yolo` does _not_ automatically enable a sandbox.** YOLO mode only auto-approves tool calls; sandboxing must still be opted into via `--sandbox`, `QWEN_SANDBOX`, or `tools.sandbox`. In headless / non-interactive runs with `--yolo` (or `--approval-mode=yolo`) and no sandbox, the model can execute shell, write, and edit tools at the current process's privilege level — Qwen Code prints a warning to stderr in that case. Suppress with `QWEN_CODE_SUPPRESS_YOLO_WARNING=1` once you've reviewed the trade-off.
By default, it uses a pre-built `qwen-code-sandbox` Docker image.

View File

@ -16,6 +16,7 @@ export default {
},
'approval-mode': 'Approval Mode',
'auto-mode': 'Auto Mode',
worktree: 'Worktrees',
mcp: 'MCP',
lsp: 'LSP (Language Server Protocol)',
'token-caching': 'Token Caching',

View File

@ -3,5 +3,6 @@ export default {
telegram: 'Telegram',
weixin: 'WeChat',
dingtalk: 'DingTalk',
feishu: 'Feishu',
plugins: 'Plugins',
};

View File

@ -0,0 +1,170 @@
# Feishu (Lark)
This guide covers setting up a Qwen Code channel on Feishu (飞书) / Lark.
## Prerequisites
- A Feishu organization account
- A Feishu application with App ID and App Secret (see below)
## Creating an Application
1. Go to the [Feishu Open Platform](https://open.feishu.cn)
2. Create a new application (or use an existing one)
3. Under the application, enable the **Bot** capability (添加应用能力 → 机器人)
4. In **Event Subscriptions** (事件与回调), select **Long Connection** (使用长连接接收事件)
5. Add the event `im.message.receive_v1` (接收消息)
6. Note the **App ID** (Client ID) and **App Secret** (Client Secret) from the application credentials page
### Required Permissions
Enable the following permissions under **Permissions & Scopes** (权限管理):
- `im:message` — Read and send messages
- `im:message:send_as_bot` — Send messages as bot
- `im:resource` — Access message resources (images, files)
### Publish the Application
After configuring permissions and events, create a version and publish it. The bot won't work until the application is published and approved.
## Configuration
Add the channel to `~/.qwen/settings.json`:
```json
{
"channels": {
"my-feishu": {
"type": "feishu",
"clientId": "<your-app-id>",
"clientSecret": "<your-app-secret>",
"senderPolicy": "open",
"sessionScope": "user",
"cwd": "/path/to/your/project",
"groupPolicy": "open",
"collapsible": true,
"groups": {
"*": { "requireMention": true }
}
}
}
}
```
### Configuration Options
| Option | Description |
| ---------------------- | ------------------------------------------------------------------- |
| `clientId` | Feishu App ID |
| `clientSecret` | Feishu App Secret |
| `collapsible` | Collapse long responses into expandable sections (default: `false`) |
| `collapsibleThreshold` | Character threshold for collapsing (default: `500`) |
| `webhookPort` | If set, use HTTP webhook mode instead of WebSocket |
| `verificationToken` | Verification token for webhook mode |
| `encryptKey` | Encrypt key for webhook mode |
## Running
```bash
# Start only the Feishu channel
qwen channel start my-feishu
# Or start all configured channels together
qwen channel start
```
Open Feishu and send a message to the bot. You should see a streaming interactive card with the response.
## Connection Modes
### WebSocket (Default)
WebSocket mode uses an outbound long connection — no public URL or server is needed. This is the recommended mode for most deployments.
### Webhook
If you need webhook mode (e.g., for shared applications), set `webhookPort` in your config:
```json
{
"channels": {
"my-feishu": {
"type": "feishu",
"webhookPort": 9321,
"verificationToken": "<from-feishu-console>",
"encryptKey": "<from-feishu-console>"
}
}
}
```
Then set the request URL in Feishu Open Platform to `http://<your-server>:9321`.
## Group Chats
Feishu bots work in both DM and group conversations. To enable group support:
1. Set `groupPolicy` to `"allowlist"` or `"open"` in your channel config
2. Add the bot to a Feishu group
3. @mention the bot in the group to trigger a response
By default, the bot requires an @mention in group chats (`requireMention: true`). Set `"requireMention": false` for a specific group to make it respond to all messages.
## Features
### Interactive Card Streaming
Responses are rendered as Feishu interactive cards with real-time streaming updates. The card shows a "generating" indicator while the response is being produced, and a **Stop** button to cancel generation.
### Quote/Reply Context
When you reply to (quote) a message, the quoted content is automatically included as context for the agent. This works for:
- Text and rich-text messages
- Interactive cards (bot's previous responses)
### Images and Files
You can send photos and documents to the bot:
- **Images:** Analyzed using multimodal vision capabilities
- **Files:** Downloaded and saved locally for the agent to read
### Concurrent Messages
Multiple users can send messages simultaneously in the same group chat. Each message gets its own independent card and response — they don't interfere with each other.
## Key Differences from DingTalk
- **Response format:** Uses Feishu interactive cards (v2 schema) with native markdown rendering, including tables
- **Streaming:** Card content is updated in-place with throttled PATCH requests (1.5s interval)
- **Connection:** WebSocket via `@larksuiteoapi/node-sdk` — same outbound-only model, no public URL needed
- **Working indicator:** An "OnIt" emoji reaction is added while processing
- **Quote context:** Supports quoting both text messages and interactive cards
## Troubleshooting
### Bot doesn't connect
- Verify your App ID and App Secret are correct
- Make sure **Long Connection** is selected in Event Subscriptions
- Check that the `im.message.receive_v1` event is subscribed
- Check the terminal output for connection errors
### Bot doesn't respond in groups
- Check that `groupPolicy` is set to `"allowlist"` or `"open"` (default is `"disabled"`)
- Make sure you @mention the bot in the group message
- Verify the bot has been added to the group
### Card stays in "generating" state
- This usually indicates the response completed but the final card update failed
- Check terminal logs for API errors (rate limiting, card size limits)
- Very long responses with many tables may hit Feishu's card element limits
### Quote doesn't include card content
- The bot reads card content via the `card_msg_content_type=user_card_content` API parameter
- Ensure the bot has `im:message` permission to read messages

View File

@ -238,9 +238,41 @@ Key command-line options for headless usage:
| `--approval-mode` | Set approval mode | `qwen -p "query" --approval-mode auto_edit` |
| `--continue` | Resume the most recent session for this project | `qwen --continue -p "Pick up where we left off"` |
| `--resume [sessionId]` | Resume a specific session (or choose interactively) | `qwen --resume 123e... -p "Finish the refactor"` |
| `--max-session-turns` | Cap the number of user/model/tool turns in the run | `qwen -p "..." --max-session-turns 30` |
| `--max-wall-time` | Wall-clock budget; accepts `90` (s), `30s`, `5m`, `1h`, `1.5h` | `qwen -p "..." --max-wall-time 10m` |
| `--max-tool-calls` | Cumulative tool-call budget for the run | `qwen -p "..." --max-tool-calls 50` |
For complete details on all available configuration options, settings files, and environment variables, see the [Configuration Guide](../configuration/settings).
## Safety in unattended runs
Headless / CI runs combined with `--yolo` (or `--approval-mode=yolo`) auto-approve every tool call, including `shell`, `write`, and `edit`. **`--yolo` does not enable a sandbox** — those tools run at the host process's privilege level. When Qwen Code detects this combination with no sandbox configured, it prints a one-line warning to stderr at startup. Suppress the warning with `QWEN_CODE_SUPPRESS_YOLO_WARNING=1` once you've reviewed the trade-off.
### Run-level budgets
Qwen Code can abort an unattended run when it crosses one of the following thresholds. Each is `-1` (unlimited) by default; setting any one is enough to bound runaway behavior. They are enforced cooperatively against the same `AbortController` that already carries SIGINT, so a budget abort emits a structured `FatalBudgetExceededError` (exit code **55**) — distinct from the turn-cap exit code 53 and SIGINT's 130 so CI scripts can branch on the reason.
| Flag | Settings key | What it bounds |
| --------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--max-wall-time` | `model.maxWallTimeSeconds` | Wall-clock duration of the whole run. Flag accepts `90` (s), `30s`, `5m`, `1h`, `1.5h` (fractional units supported). Minimum 1s — sub-second values are rejected as typos. Settings is seconds. |
| `--max-tool-calls` | `model.maxToolCalls` | Cumulative top-level tool calls dispatched by the main run loop (counts successes _and_ failures — the model still consumes tokens on errors). See "Scope" below for subagent / structured-output exemptions. |
| `--max-session-turns` | `model.maxSessionTurns` | Number of user/model/tool turns; pre-existing. Exits with code 53 on overrun (distinct from budget exit 55). |
#### Scope
- **`--max-tool-calls` counts top-level dispatches only.** When the model calls the `agent` tool, the dispatch counts as **1**; inner tool calls performed by the spawned subagent are **not** counted. A model that funnels work through subagents can do unbounded inner work under a small top-level budget. Combine with `--exclude-tools agent` if you need a tighter cap.
- **`structured_output` is exempt from `--max-tool-calls`.** Under `--json-schema`, the model's terminal `structured_output` call is the "I'm done" contract, not real work — it doesn't count against `--max-tool-calls` so a budget-edge completion isn't aborted as a false positive. The exemption is unconditional (including failed Ajv validations), so a model stuck in a malformed-output retry loop is NOT bounded by `--max-tool-calls`; combine with `--max-session-turns` or `--max-wall-time` to cap retries.
- **`structured_output` is NOT exempt from `--max-session-turns`.** That counter is pre-existing and bumps for every turn including the terminal contract. Size `--max-session-turns` to `N+1` if you want to allow `N` real-work turns under `--json-schema`.
- **Single-shot vs `--input-format stream-json`:** in stream-json input mode the daemon resets the budget counters at the start of every user message; the budget is per-message, not per-process.
- **`qwen serve` / ACP sessions:** the daemon ACP session path does NOT currently consult `--max-wall-time` / `--max-tool-calls` from settings.json. These budgets only apply to single-shot `qwen -p` runs and to `--input-format stream-json` sessions. (`qwen serve` does emit the YOLO-no-sandbox warning at boot if `tools.approvalMode: 'yolo'` is set in settings.)
### Recommended combinations
- **Trusted, isolated environment (ephemeral CI runner, container):** `qwen -p "..." --yolo --max-session-turns N --max-wall-time 10m --output-format json`. Pin a turn budget and a wall-clock budget so a stuck agent can't burn through your CI minutes, and capture `--output-format json` for post-run usage / tool-call auditing.
- **Local machine or shared infra:** also pass `--sandbox` (or set `QWEN_SANDBOX=1`) so shell / write / edit tools run inside the sandbox image.
- **Long-running CI with retry-on-rate-limit:** combine `QWEN_CODE_UNATTENDED_RETRY=1` with `--max-wall-time`. The retry env keeps the run alive past transient 429 / 529 responses; the wall-clock budget ensures a persistently-failing provider can't extend the job indefinitely.
- **Bounded auditing / exploration:** for read-only tasks, `--max-tool-calls 25` caps how aggressively the model can grep / read. Combine with `--exclude-tools shell,write,edit` to make the bound meaningful.
## Examples
### Code review

View File

@ -0,0 +1,345 @@
# Worktrees
> Isolate experimental work in a temporary [git worktree](https://git-scm.com/docs/git-worktree) without leaving your current session. Useful when the model is about to make wide-ranging edits you want to keep separate from your main checkout, or when you want a subagent to work in a sandbox of its own.
## Quick Start
### Start the session inside a worktree (`--worktree` flag)
If you know up front that the entire session should run inside a worktree, pass `--worktree` at launch:
```bash
# Auto-generated slug (e.g. tender-jemison-037f0a)
qwen --worktree
# Explicit name
qwen --worktree my-feature
# `=` form (recommended when also passing a positional prompt — see tip below)
qwen --worktree=my-feature
# PR reference — fetches refs/pull/<N>/head from `origin`
qwen --worktree=#4174
qwen --worktree https://github.com/QwenLM/qwen-code/pull/4174
# Continue a previous --worktree session — re-attaches to the existing dir
qwen --resume <session-id> --worktree=my-feature
```
> **Tip — bare `--worktree` followed by a positional prompt is ambiguous.** Because `--worktree` takes an optional value, `qwen --worktree "say hi"` makes yargs consume `"say hi"` as the slug (and reject it because of the space). Use one of:
>
> - `qwen --worktree=my-feature "say hi"` (always works — explicit slug via `=`)
> - `qwen "say hi" --worktree` (positional first, flag at the end → auto slug)
> - `qwen --worktree --approval-mode yolo "say hi"` (any flag between them anchors the bare form)
> **Tip — `qwen --resume --worktree foo` (no session ID) shows an empty picker on first use.** The picker scopes to the chosen worktree's session storage; sessions started outside that worktree are not listed. To resume a session that was started inside `foo`, use `qwen --resume <id> --worktree foo` directly — the CLI re-attaches to the existing `foo/` directory rather than re-creating it.
`process.cwd()` and the model's workspace are switched to the worktree before the first turn runs. Exit with `Ctrl+C` twice and the [Exit Dialog](#exit-dialog-ctrlc--ctrld) prompts to keep or remove the worktree.
The `--worktree` flag cannot be combined with `--acp`/`--experimental-acp` — for ACP hosts (like Zed), pass the worktree path as the `cwd` of the `loadSession`/`newSession` request instead.
### Or ask mid-session
Alternatively, ask Qwen Code in plain language to create a worktree from inside an existing session:
```text
> start a worktree called experiment-a
Worktree experiment-a created on branch worktree-experiment-a
.qwen/worktrees/experiment-a
```
From this point on, the model routes every file edit and shell command through `.qwen/worktrees/experiment-a/`. Your original working directory is untouched.
When you are done:
```text
> exit the worktree and remove it
Removed worktree experiment-a (branch worktree-experiment-a)
```
If you want to come back later, ask to exit with the worktree kept on disk instead:
```text
> exit the worktree but keep it
Kept worktree experiment-a at .qwen/worktrees/experiment-a
```
## When Worktrees Are Used
Worktrees are activated in four independent paths:
| Trigger | What happens |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| You launch with `--worktree` | The CLI creates the worktree before any model turn runs and chdirs the session into it. PR forms (`#N`, full URL) fetch first. |
| You explicitly ask for a worktree mid-session | Model calls `enter_worktree`; subsequent file edits go inside it. |
| You explicitly ask to leave | Model calls `exit_worktree` with `keep` or `remove`. |
| Model spawns a sub-agent with isolation enabled | A throwaway worktree (`agent-<hex>`) is created automatically and cleaned up if the agent has no diffs. |
The two mid-session tools (`enter_worktree` / `exit_worktree`) are deliberately gated behind explicit phrasing — saying "fix this bug" or "create a branch" will **not** trigger them. You must say something like "use a worktree", "start a worktree", or "in a worktree". The `--worktree` CLI flag has no such guard; it always creates one when present.
## What Gets Created
Every Qwen-managed worktree is placed under your project's `.qwen` directory:
```
<repoRoot>/.qwen/worktrees/<slug>/ # Working directory
↳ branch worktree-<slug> # Created off your current branch
```
- **Slug** — letters, digits, dot, underscore, hyphen; max 64 chars. If you don't specify a name, an `<adjective>-<noun>-<6hex>` slug is auto-generated (e.g. `tender-jemison-037f0a`). PR references produce `pr-<N>`.
- **Branch** — always `worktree-<slug>`, branched from whichever branch you have checked out when you ask for the worktree (not necessarily the main working tree's `HEAD`). For PR worktrees the branch is `worktree-pr-<N>` and is based on `FETCH_HEAD` (the PR's tip on the GitHub side) rather than your local branch.
- **Hooks** — the worktree's `core.hooksPath` is automatically pointed at the main repo's `.husky/` (preferred) or `.git/hooks/` so commits inside the worktree still trigger your existing pre-commit / commit-msg hooks.
- **Optional symlinks** — directories listed in `worktree.symlinkDirectories` (see [Settings](#settings)) are symlinked from the main repo into the new worktree so heavy dirs like `node_modules` can be reused without reinstalling.
The general-purpose worktree path is **not configurable** — it must live under `<repoRoot>/.qwen/worktrees/` so the CLI can find it on restart and on stale-cleanup sweeps. (The unrelated `agents.arena.worktreeBaseDir` setting controls only [Agent Arena](./arena.md) worktrees, which use a separate path tree under `~/.qwen/arena/`.)
## Footer and Status Line
When a worktree is active, the Footer shows a dim indicator on its own row:
```
⎇ worktree-experiment-a (experiment-a)
```
If you use a [custom status line script](./status-line.md), it also receives a `worktree` object in the JSON payload piped to stdin:
```json
{
"worktree": {
"name": "experiment-a",
"path": "/path/to/repo/.qwen/worktrees/experiment-a",
"branch": "worktree-experiment-a",
"original_cwd": "/path/to/repo",
"original_branch": "main"
}
}
```
The payload field is present **only** when a worktree is active, so a `null`-check (`input.worktree?.name`) is enough.
If your custom status line already renders worktree info, you can hide the built-in Footer row to avoid duplication — see [Settings](#settings) below.
## Exit Dialog (Ctrl+C / Ctrl+D)
Pressing the quit shortcut twice while a worktree is active opens the **Worktree Exit Dialog** instead of closing the CLI:
```
⎇ Active worktree: "experiment-a" (worktree-experiment-a)
• 2 new commit(s) on worktree-experiment-a
• 3 uncommitted file(s)
Removing the worktree will discard everything above.
What would you like to do?
○ Keep worktree (exit without deleting)
○ Remove worktree and branch (discards 2 commit(s), 3 file(s))
○ Cancel (stay in session)
```
The dialog inspects the worktree on open (`git status --porcelain` + `git rev-list <baseHEAD>..HEAD`) and surfaces both counts so you know exactly what you'd be discarding. `ESC` cancels.
If `git status` itself fails (e.g. corrupt index, worktree directory was removed under the CLI), the dialog shows a `⚠ Could not measure worktree state` warning and the counts may be unreliable — choose **Keep** or **Cancel** until you've diagnosed the underlying repo problem.
## `--resume` Restore
The active worktree binding is persisted to a sidecar file alongside your session transcript:
```
<chatsDir>/<sessionId>.worktree.json
```
When you launch the CLI with `--resume <sessionId>` (or pick the session from `/resume`), three things happen consistently across **interactive TUI**, **headless `-p`**, and **ACP/Zed** modes:
1. The sidecar is loaded and the worktree directory is verified to still exist on disk.
2. If alive, the model receives a one-shot reminder on its very next prompt:
```
[Resumed] Active worktree: "<slug>" at <path> (branch: <branch>). Continue using this path for all file operations.
```
3. If the worktree directory was deleted between sessions, the stale sidecar is cleaned up automatically — no error, the resume just continues without worktree context.
Each mode chooses its own injection mechanism, but the user-visible behavior is identical:
| Mode | Mechanism |
| ----------------- | ------------------------------------------------------------------------------------------------------ |
| Interactive (TUI) | `INFO` history item + system-reminder prefix on the next user prompt. |
| Headless (`-p`) | `<system-reminder>` prefix on the prompt + `worktree_restored` JSON system event in the output stream. |
| ACP (e.g. Zed) | Pending notice attached to the next `prompt()` call. |
The model is **not** automatically `chdir`'d into the worktree — the reminder is what keeps it routing edits through the worktree path.
## Sub-Agent Isolation
The `agent` tool accepts an optional `isolation: "worktree"` parameter. When set, Qwen Code creates an ephemeral worktree at `<repoRoot>/.qwen/worktrees/agent-<7hex>/` before the sub-agent starts, and:
- **No changes** → the worktree is automatically removed when the agent finishes.
- **Has changes** → the worktree is preserved; its path and branch are appended to the agent's result, e.g.
```
…agent output…
[worktree preserved: /path/to/.qwen/worktrees/agent-3f2a1b9 (branch worktree-agent-3f2a1b9)]
```
Review the diff and merge or delete it manually.
Two constraints:
- `isolation: "worktree"` requires a `subagent_type` — forked sub-agents (no `subagent_type`) reuse the parent's full conversation context, so isolating them would split intent from working tree.
- Background agents (`run_in_background: true`) work fine with isolation; the cleanup runs when the agent reports completion.
### Automatic Stale Cleanup
Ephemeral agent worktrees that survived a crash or `--no-cleanup` shutdown are reaped on every CLI startup, with conservative fail-closed rules:
| Guard | Behavior |
| -------------------------------------- | ---------------------------------------------- |
| Slug must match `agent-<7hex>` pattern | Named worktrees you created are never touched. |
| Directory `mtime` > 30 days | Newer entries are skipped. |
| Any uncommitted tracked change | Skip the entry (don't delete). |
| Any commit not reachable from a remote | Skip the entry (don't delete). |
| Any error reading git state | Skip the entry (don't delete). |
Named user worktrees (`enter_worktree` slugs) are **never** auto-cleaned — you keep them around until you ask to remove them.
## Safety Guards on `exit_worktree action="remove"`
Three independent guards trigger before the directory and branch are deleted:
1. **Session ownership** — each worktree carries a sidecar marker with the session ID that created it. A different session trying to remove it is refused with a clear error pointing at `git worktree remove` for the manual escape hatch.
2. **Dirty working tree** — uncommitted tracked or untracked changes block removal. Pass `discard_changes: true` to override. (Bypass requires explicit user confirmation — `action: "remove"` is never auto-approved in AUTO_EDIT mode.)
3. **Unmerged commits** — commits on `worktree-<slug>` that no other local branch or remote ref points at block removal unconditionally; there is no "discard commits" flag because losing committed work is rarely what users mean. Merge, push, or rename the branch elsewhere first.
The same three guards apply to the `WorktreeExitDialog → Remove` button.
## Settings
Two settings shape the general-purpose worktree experience:
| Key | Type | Default | Effect |
| --------------------------------- | ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ui.hideBuiltinWorktreeIndicator` | boolean | `false` | Hides the built-in `⎇ worktree-… (…)` Footer row. The `worktree` field is still delivered to custom status line scripts. Set to `true` only if your status line already renders the worktree — otherwise you lose all UI affordance. |
| `worktree.symlinkDirectories` | `string[]` | `undefined` | Directories under the main repo to symlink into every general-purpose worktree on creation. Paths are relative to the repo root; absolute paths and any entry containing `..` are rejected. Missing sources and existing destinations are silently skipped (no overwrite). |
Example:
```jsonc
// ~/.qwen/settings.json or <repo>/.qwen/settings.json
{
"worktree": {
"symlinkDirectories": ["node_modules", ".turbo", "dist"],
},
}
```
Applies to ALL worktree-creation paths: `--worktree` flag, `enter_worktree` tool, and `agent isolation: "worktree"`.
Settings unrelated to general worktrees but worth knowing about:
- `agents.arena.worktreeBaseDir` — controls **Agent Arena** worktree placement (default `~/.qwen/arena`). Does not affect general-purpose worktrees, which always live under `<repoRoot>/.qwen/worktrees/`.
There is no schema for `worktree.sparsePaths` yet — that's a roadmap item (see [Limitations](#limitations)).
## Tool Reference
### `enter_worktree`
```json
{ "name": "experiment-a" }
```
| Field | Type | Required | Notes |
| ------ | ------ | -------- | ------------------------------------------------------------------------------------------ |
| `name` | string | no | Slug. Letters, digits, dot, underscore, hyphen; max 64 chars. Auto-generated when omitted. |
Refuses to run when:
- The CLI is not in a git repository.
- The current working directory is already inside `.qwen/worktrees/` (no nested worktrees).
### `exit_worktree`
```json
{ "name": "experiment-a", "action": "remove", "discard_changes": false }
```
| Field | Type | Required | Notes |
| ----------------- | ---------------------- | ------------------------------------- | ------------------------------------------------------------------ |
| `name` | string | yes | Must match the slug used in `enter_worktree`. |
| `action` | `"keep"` \| `"remove"` | yes | `keep` preserves dir + branch; `remove` deletes both. |
| `discard_changes` | boolean | only when `action="remove"` and dirty | Overrides the dirty-tree guard. Has no effect for `action="keep"`. |
`action: "remove"` always prompts for confirmation, including under `AUTO_EDIT` approval mode — it is treated as a destructive shell operation, not an info-only tool.
### `agent` — `isolation` parameter
```json
{
"subagent_type": "my-agent",
"description": "…",
"prompt": "…",
"isolation": "worktree"
}
```
| Field | Type | Required | Notes |
| ----------- | ------------ | -------- | ------------------------------------------------------------------------------------------------- |
| `isolation` | `"worktree"` | no | Runs the agent in a fresh `agent-<7hex>` worktree. Requires `subagent_type` to be set (no forks). |
See [Sub-Agents](./sub-agents.md) for the rest of the agent tool reference.
## CLI Reference
### `--worktree [name | #N | url]`
```bash
qwen --worktree # auto-generate slug
qwen --worktree my-feature # explicit slug
qwen --worktree=my-feature # = form
qwen --worktree=#123 # PR reference
qwen --worktree https://github.com/owner/repo/pull/123 # PR URL
```
| Input | Result |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Bare flag (no value) | Auto slug `<adjective>-<noun>-<6hex>`, branch `worktree-<slug>`, base = current branch. |
| Plain slug | Branch `worktree-<slug>`, base = current branch. Slug validation: letters/digits/dot/underscore/hyphen, max 64 chars. |
| `#N` or `<github-url>/pull/N` | Slug `pr-<N>`, branch `worktree-pr-<N>`, base = `FETCH_HEAD` after `git fetch origin pull/<N>/head` (30s timeout). |
`--worktree` cannot be combined with `--acp` / `--experimental-acp`.
When `--worktree` is combined with `--resume <session-id>`, the worktree wins: the resumed session's saved worktree (if any) is overridden and a stderr line + first-prompt reminder report the override.
For interactive (TUI) and headless (`-p`) modes the worktree is automatically created and the session chdirs into it before the first turn.
PR-fetch failure modes (exit code != 0, no worktree created):
| Cause | Message excerpt |
| ----------------------------- | ---------------------------------------------------------- |
| Missing `origin` remote | `requires an "origin" remote that points at GitHub` |
| PR doesn't exist on origin | `Failed to fetch PR #<N>: the PR does not exist on origin` |
| 30s network timeout | `Failed to fetch PR #<N>: timed out after 30s` |
| PR number out of range / zero | `Invalid PR number` |
## Limitations
The following items are intentionally not implemented in the current phase:
- **No sparse checkout.** Large monorepos check out the full tree. (`worktree.sparsePaths` is a roadmap item.)
- **No tmux integration.** The CLI does not spawn worktree sessions in new tmux windows.
- **Worktrees are separate "projects" for session storage.** Sessions started with `--worktree foo` are saved under that worktree's chats dir; to resume them later you must pass `--worktree foo` again. Sessions started without `--worktree` are saved under the main checkout and won't appear in the worktree's resume picker.
- **No cross-slug session override.** `qwen --resume <sid> --worktree second` where `<sid>` was created with `--worktree first` will fail to find the session — sessions and worktrees are tightly bound by `projectHash(cwd)`. To switch worktrees on an existing session you must exit, then re-launch with the new `--worktree` and a fresh prompt. A future architectural change (anchoring storage at the repo root instead of `cwd`) would lift this constraint.
- **Mid-session `enter_worktree` does NOT switch `process.cwd()` or `Config.targetDir`.** That tool uses the model-context-only convention (see [Sub-Agents](./sub-agents.md)). Only the startup `--worktree` flag actually switches the process working directory.
- **Relative paths in other arg fields are resolved BEFORE the worktree chdir.** Path-taking flags (`--mcp-config`, `--openai-logging-dir`, `--json-file`, `--input-file`, `--telemetry-outfile`, `--include-directories`) are normalized to absolute paths against the launch cwd when `--worktree` is set. Other path-shaped argv fields not in this list still resolve against the worktree cwd — use absolute paths to be safe.
Track the roadmap in `docs/design/worktree.md`.
## Troubleshooting
**The Footer shows no worktree indicator even though I just created one.**
Check that `ui.hideBuiltinWorktreeIndicator` is not set to `true`. Also confirm the slug is non-empty in the tool's success message.
**`--resume` does not restore my worktree.**
Check `<chatsDir>/<sessionId>.worktree.json` exists. The CLI deletes the sidecar automatically when the worktree directory is gone, so a missing sidecar plus a missing directory is the normal "no worktree to restore" state — not a bug. Run with `--debug` and grep for `restoreWorktreeContext` to see the reason.
**`exit_worktree` says "created by a different session".**
This is the session-ownership guard. Resume the original session and exit from there, or run the suggested `git worktree remove …` command manually.
**Stale `agent-<hex>` worktrees keep piling up.**
The 30-day cutoff is conservative; sweep manually with `git worktree list && git worktree remove <path>`, or wait — the next CLI startup after the 30-day mark will reap them as long as they are clean and pushed.

View File

@ -0,0 +1,120 @@
# AbortController refactor — verification plan
Scenarios used to validate the change manually before opening the PR. Each
scenario captures its tmux pane via `tmux pipe-pane -o 'cat >> <log>'`.
## Setup once
```sh
# Point WT at your local checkout of the branch under review.
WT=/path/to/qwen-code/worktree
LOGDIR=$WT/docs/verification/abort-controller-refactor/logs
mkdir -p "$LOGDIR"
# Build the CLI once (skip sandbox image, skip vscode).
( cd "$WT" && npm run build:packages )
```
## Scenarios
For each scenario:
```sh
tmux new-session -d -s qwen-verify-XX
tmux pipe-pane -t qwen-verify-XX -o "cat >> $LOGDIR/XX-name.log"
tmux send-keys -t qwen-verify-XX "cd /path/to/your/test/workspace && exec node $WT/packages/cli/dist/index.js" C-m
tmux attach -t qwen-verify-XX
```
Then drive the session manually per the matrix below. Hit `C-b d` to detach
when done; `tmux kill-session -t qwen-verify-XX` to stop the pane.
### 00 — Baseline (PRE-fix)
- **Setup:** check out `main`, build, run with `NODE_OPTIONS=--trace-warnings`.
- **Input:** long 50-round mixed-tool session (shell + edit + grep + agent).
- **Expected:** after ~30–40 rounds, `MaxListenersExceededWarning: ... 1500+ abort listeners added to [AbortSignal]` printed to stderr.
- **Log:** `00-baseline-reproduction.log`.
### 01 — Long-session, DEBUG mode (this branch)
- **Setup:** `NODE_OPTIONS=--trace-warnings DEBUG=1 qwen`.
- **Input:** same 50-round script as #00.
- **Expected:** no `MaxListenersExceededWarning` printed; any other warnings still print.
- **Log:** `01-long-session-debug.log`.
### 02 — Long-session, prod mode (this branch)
- **Setup:** `qwen` (no debug env).
- **Input:** same 50-round script.
- **Expected:** clean output; a temporary `console.error` probe inside the handler (added then removed) confirms the filter fires.
- **Log:** `02-long-session-prod.log`.
### 03 — Ctrl-C mid-stream abort
- **Setup:** this branch, interactive.
- **Input:** ask for a long generation (>30s); press Ctrl-C mid-stream.
- **Expected:** stream stops within ~200ms, "Cancelled" banner shown, next prompt accepts input. `process._getActiveHandles()` count returns to baseline (use `:debug handles`).
- **Log:** `03-ctrlc-streaming.log`.
### 04 — Cancel long-running shell
- **Setup:** this branch.
- **Input:** run `sleep 60` via the shell tool; cancel mid-execution.
- **Expected:** child process killed (verify with `pgrep -f sleep` returning empty), tool result shows cancellation, agent accepts next prompt.
- **Log:** `04-shell-cancel.log`.
### 05 — Subagent cancellation
- **Setup:** this branch.
- **Input:** spawn a long agent task via the agent tool; cancel from parent.
- **Expected:** subagent's in-flight tool calls abort, subagent's model stream stops, parent receives cancellation event.
- **Log:** `05-subagent-cancel.log`.
### 06 — Headless / non-interactive abort
- **Setup:** `qwen --prompt "do a long task"`; send `SIGINT` from outside via `kill -INT <pid>`.
- **Expected:** clean shutdown, exit code 130, no warnings.
- **Log:** `06-headless-abort.log`.
### 07 — Background agent flow
- **Setup:** interactive.
- **Input:** spawn a background agent (`run_in_background: true`); let it complete; spawn a second one; cancel the second mid-flight.
- **Expected:** first agent completes normally; second aborts cleanly; no listener leak across the two.
- **Log:** `07-background-agent.log`.
### 08 — Memory baseline
- **Setup:** `qwen --inspect`, attach Chrome devtools.
- **Input:** 100-round session.
- **Expected:** heap snapshots at round 0/50/100. `AbortSignal` instance count and per-signal listener count stable (no monotonic growth).
- **Log:** `08-memory-snapshots/`.
### 09 — Existing combinedAbortSignal consumer
- **Setup:** trigger an HTTP hook with both an external signal and timeout.
- **Input:** (a) cancel external signal mid-hook; (b) let timeout fire in a separate run.
- **Expected:** hook aborts cleanly in both cases; deprecation shim path is exercised.
- **Log:** `09-http-hook-shim.log`.
## Automated (non-interactive) verifications
The automated checks below were run during development and recorded in
`automated-results.md`:
- All abortController unit tests pass (`abortController.test.ts`, 26 tests; 1 GC test skipped under non-`--expose-gc`).
- All warningHandler tests pass (`warningHandler.test.ts`, 13 tests including a spawned-child stderr integration test).
- All `combineAbortSignals` consumer tests pass (`httpHookRunner.test.ts`); the deprecated `createCombinedAbortSignal` shim plus its own test file were removed once the lone caller migrated.
- All agent runtime / followup / openaiContentGenerator / hooks tests pass.
- Migration scope (intentional): only the agent-runtime parent→child chain (`agent-interactive.ts`, `agent-core.ts`, `agent-headless.ts`) plus `promptHookRunner.ts` (real cleanup leak) was switched to the helper. Independent short-lived controllers (per-shell-command, per-fetch, per-recall, etc.) stay on raw `new AbortController()` — they're GC'd quickly and don't accumulate listeners on a long-lived parent. See `migration-completeness.txt` for the captured grep + rationale.
- TypeScript strict-mode typecheck passes for both `packages/core` and `packages/cli`.
- Prettier check passes on all modified files.
See `automated-results.md` for the actual command output.
## How to capture the artifacts for the PR body
After running each scenario, attach the transcript file (or relevant excerpt)
to the PR. For #08 (memory), export the heap snapshots and include the
listener-count delta between snapshots.

View File

@ -0,0 +1,139 @@
# Automated verification results
Captured 2026-05-20 during the AbortController refactor.
## 1. Listener-accumulation reproducer
Direct simulation of the listener-accumulation pattern observed in long
sessions (1500+ abort listeners on a single AbortSignal). The script lives
at `listener-accumulation-repro.mjs`.
```text
$ node docs/verification/abort-controller-refactor/listener-accumulation-repro.mjs
Simulating 2000 rounds for each pattern.
OLD pattern listener count on long-lived parent: 2000
NEW pattern listener count on long-lived parent: 0
PASS: OLD pattern accumulated >1500 listeners (reproduces the bug).
PASS: NEW pattern kept listener count at 0 — the helper prevents accumulation.
```
This is a self-contained proof: the OLD pattern (raw `addEventListener`
without `{once:true}` or reverse cleanup) accumulates 2000 listeners over
2000 rounds — well past the 1500 threshold the user observed. The NEW
pattern (`createChildAbortController` from `packages/core/src/utils/abortController.ts`)
keeps the parent listener count at 0 across 2000 rounds because each child's
reverse-cleanup listener removes the parent listener when the child aborts.
## 2. Migration scope (intentional)
Only the agent-runtime parent→child chain that actually accumulates listeners
on a long-lived parent signal is migrated to the helper:
- `packages/core/src/agents/runtime/agent-interactive.ts` (master + per-message round)
- `packages/core/src/agents/runtime/agent-core.ts` (per-iteration round + waitForExternalInputs + processFunctionCalls try/finally)
- `packages/core/src/agents/runtime/agent-headless.ts` (external → execution)
- `packages/core/src/hooks/promptHookRunner.ts` (had a real cleanup leak: manual addEventListener without `{once:true}` and never removed)
Plus three `{once:true}`-only fixes (no helper switch, just defensive
correctness):
- `packages/core/src/hooks/hookRunner.ts`
- `packages/core/src/hooks/functionHookRunner.ts`
- `packages/core/src/confirmation-bus/message-bus.ts`
Independent short-lived controllers (per-shell-command in `tools/shell.ts`,
per-monitor in `tools/monitor.ts`, per-arena-session in
`agents/arena/ArenaManager.ts`, per-recall in `core/client.ts`,
per-fetch in `utils/fetch.ts`, per-dream / per-title / per-judge / per-resume,
etc.) stay on raw `new AbortController()` — they're GC'd at end of use and
do not accumulate on a long-lived parent.
See `migration-completeness.txt` for the actual grep + rationale.
## 3. Affected test suites
All 71 affected test files / 2085 tests pass (3 skipped — 1 is the GC test
that requires `--expose-gc`, 2 are pre-existing skips in the headless suite).
```text
Test Files 71 passed (71)
Tests 2085 passed | 3 skipped (2088)
Duration 16.71s
```
Coverage:
- `packages/core/src/utils/abortController.test.ts` — 26 tests: factory cap (default + custom), child propagation, reverse cleanup, fast path, undefined parent, custom-maxListeners passthrough, `combineAbortSignals` semantics (incl. cleanup-cancels-timeout, timeout-cleans-input-listeners, `timeoutMs <= 0` boundary, mid-iteration defensive check), GC safety (best-effort).
- `packages/cli/src/utils/warningHandler.test.ts` — 13 tests: idempotency, AbortSignal suppression (including `[AbortSignal{...}]` shape), generic EventTarget NOT suppressed, debug-mode passthrough, fan-out to prior listeners, spawned-child end-to-end stderr integration.
- `packages/core/src/hooks/httpHookRunner.test.ts` — covers the migrated `combineAbortSignals` consumer (the deprecated `createCombinedAbortSignal` shim plus its test file were removed once the lone caller migrated).
- `packages/core/src/agents/runtime/{agent-core,agent-interactive,agent-headless,agent-context,agent-statistics}.test.ts` — 102 tests covering the high-impact migrated files.
- `packages/core/src/core/openaiContentGenerator/**` — 280+ tests including the pipeline that lost the `raiseAbortListenerCap` band-aid.
- `packages/core/src/followup/**` — 100+ tests including the migrated speculation controller.
- `packages/core/src/tools/agent/**`, `packages/core/src/tools/shell.test.ts`, `packages/core/src/services/**`, `packages/core/src/hooks/**`, `packages/core/src/confirmation-bus/**` — all migrated tool/hook/service files.
## 4. TypeScript strict-mode typecheck
```sh
$ node_modules/.bin/tsc -p packages/core/tsconfig.json --noEmit
(no output, exit 0)
$ node_modules/.bin/tsc -p packages/cli/tsconfig.json --noEmit
(no output, exit 0)
```
## 5. Prettier formatting
```sh
$ node_modules/.bin/prettier --check packages/core/src/agents/runtime/agent-core.ts \
packages/core/src/agents/runtime/agent-headless.ts \
packages/cli/src/utils/warningHandler.ts \
packages/cli/src/utils/warningHandler.test.ts \
packages/core/src/utils/abortController.ts \
packages/core/src/utils/abortController.test.ts
Checking formatting...
All matched files use Prettier code style!
```
## 6. Build + binary smoke test
```sh
$ npm run build:packages
(succeeds for all 5 workspace packages)
$ NODE_OPTIONS=--trace-warnings node packages/cli/dist/index.js --version
0.15.11
EXIT=0
$ node packages/cli/dist/index.js --help
Usage: qwen [options] [command]
...
```
No warnings emitted during boot with `--trace-warnings`.
## 7. Codex independent review
Two full passes via the `codex:codex-rescue` agent (independent context each
time). First pass surfaced 3 issues — all addressed in subsequent commits:
1. **Throw between controller creation and explicit abort leaks listener** in
`agent-core.ts`'s per-iteration body and `agent-headless.ts`'s
pre-try-block setup. Fixed by wrapping each in `try { ... } finally {
abortController.abort(); }`.
2. **Warning suppressor regex `EventTarget` too broad**. Tightened to match
only `AbortSignal` (any shape Node ≥20 produces).
3. **`process.removeAllListeners('warning')` strips third-party listeners**.
Removed — rely on Node's "no listeners → default printer fires" semantics
so adding our handler implicitly disables the default print path while
keeping third-party telemetry listeners intact.
Second pass confirmed all fixes correct, no further blockers.
## What remains for interactive verification
The scenarios in `README.md` numbered 00–09 require a real interactive
session against the model API (long mixed-tool conversations, Ctrl-C
mid-stream, subagent cancellation, heap snapshots). Those are documented
for human execution and the transcripts should be attached to the PR body
when run.

View File

@ -0,0 +1,107 @@
#!/usr/bin/env node
/**
* Direct simulation of the listener-accumulation pattern the agent runtime
* exhibits in long sessions. Builds a deep parent → child chain to a depth
* the user observed (>1500 listeners) and asserts:
*
* 1. The OLD pattern (plain new AbortController + manual addEventListener
* without {once:true} or reverse cleanup) accumulates listeners on the
* long-lived parent — reproducing the warning.
*
* 2. The NEW pattern (createChildAbortController from the helper) keeps the
* parent listener count bounded by 1, regardless of how many short-lived
* children come and go.
*
* Run:
* node docs/verification/abort-controller-refactor/listener-accumulation-repro.mjs
*/
import { getEventListeners, setMaxListeners } from 'node:events';
// Inline copy of the production helper (packages/core/src/utils/abortController.ts)
// so this script has no build-step dependency on @qwen-code/qwen-code-core.
// Kept in sync — the child is held STRONGLY by the parent's listener closure
// (no WeakRef on child) so propagation works even when a caller drops the
// controller and keeps only the signal. WeakRef is used only on the PARENT,
// to keep child cleanup from pinning a long-lived parent in memory.
function createAbortController(maxListeners = 50) {
const c = new AbortController();
setMaxListeners(maxListeners, c.signal);
return c;
}
function createChildAbortController(parent) {
const child = createAbortController();
if (!parent) return child;
const parentSignal = parent.signal ?? parent;
if (parentSignal.aborted) {
child.abort(parentSignal.reason);
return child;
}
const weakParent = new WeakRef(parentSignal);
const handler = () => {
child.abort(weakParent.deref()?.reason);
};
parentSignal.addEventListener('abort', handler, { once: true });
child.signal.addEventListener(
'abort',
() => {
weakParent.deref()?.removeEventListener('abort', handler);
},
{ once: true },
);
return child;
}
const ROUNDS = 2000;
console.log(`Simulating ${ROUNDS} rounds for each pattern.\n`);
// ─── OLD pattern: plain new AbortController + manual addEventListener ───
const oldParent = new AbortController();
setMaxListeners(0, oldParent.signal); // disable warning so we can measure cleanly
for (let i = 0; i < ROUNDS; i++) {
const child = new AbortController();
// No {once:true}, no reverse cleanup — accumulates on oldParent.
oldParent.signal.addEventListener('abort', () => child.abort());
}
const oldCount = getEventListeners(oldParent.signal, 'abort').length;
// ─── NEW pattern: createChildAbortController ───
const newParent = createAbortController();
for (let i = 0; i < ROUNDS; i++) {
const child = createChildAbortController(newParent);
child.abort(); // simulate end-of-round cleanup via try/finally
}
const newCount = getEventListeners(newParent.signal, 'abort').length;
console.log(`OLD pattern listener count on long-lived parent: ${oldCount}`);
console.log(`NEW pattern listener count on long-lived parent: ${newCount}`);
const expectations = {
oldShouldExceed: 1500,
newMustBe: 0,
};
let pass = true;
if (oldCount <= expectations.oldShouldExceed) {
console.error(
`FAIL: OLD pattern should accumulate >${expectations.oldShouldExceed} listeners; got ${oldCount}`,
);
pass = false;
} else {
console.log(
`PASS: OLD pattern accumulated >${expectations.oldShouldExceed} listeners (reproduces the bug).`,
);
}
if (newCount !== expectations.newMustBe) {
console.error(
`FAIL: NEW pattern must have exactly ${expectations.newMustBe} listeners; got ${newCount}`,
);
pass = false;
} else {
console.log(
`PASS: NEW pattern kept listener count at ${expectations.newMustBe} — the helper prevents accumulation.`,
);
}
process.exit(pass ? 0 : 1);

View File

@ -0,0 +1,28 @@
$ grep -rn "new AbortController" packages/core/src --include="*.ts" \
| grep -v test | grep -v abortController.ts
# Scoped to the nested parent→child chain that actually accumulates listeners
# (the agent-runtime loop in long sessions, plus promptHookRunner which had a
# real cleanup leak). Independent short-lived controllers (per-shell-command,
# per-fetch, per-recall, per-arena-session etc.) intentionally stay on raw
# `new AbortController()` — they're GC'd at the end of their use and do not
# accumulate listeners on a long-lived parent signal.
packages/core/src/followup/speculation.ts:100: const abortController = new AbortController();
packages/core/src/tools/agent/agent.ts:1722: const bgAbortController = new AbortController();
packages/core/src/tools/agent/agent.ts:2116: const fgAbortController = new AbortController();
packages/core/src/tools/shell.ts:1514: const promoteAbortController = new AbortController();
packages/core/src/tools/shell.ts:2364: const entryAc = new AbortController();
packages/core/src/tools/shell.ts:2772: const entryAc = new AbortController();
packages/core/src/tools/monitor.ts:306: const entryAc = new AbortController();
packages/core/src/core/client.ts:1199: const controller = new AbortController();
packages/core/src/memory/manager.ts:936: const abortController = new AbortController();
packages/core/src/goals/goalHook.ts:70: const judgeController = new AbortController();
packages/core/src/goals/goalHook.ts:169: const signal = context?.signal ?? new AbortController().signal;
packages/core/src/agents/arena/ArenaManager.ts:305: this.masterAbortController = new AbortController();
packages/core/src/agents/arena/ArenaManager.ts:817: abortController: new AbortController(),
packages/core/src/agents/background-agent-resume.ts:421: abortController: new AbortController(),
packages/core/src/agents/background-agent-resume.ts:493: const bgAbortController = new AbortController();
packages/core/src/agents/background-agent-resume.ts:922: abortController: new AbortController(),
packages/core/src/utils/fetch.ts:64: const controller = new AbortController();
packages/core/src/services/chatRecordingService.ts:963: const controller = new AbortController();
packages/core/src/services/chatCompressionService.ts:387: abortSignal: signal ?? new AbortController().signal,

View File

@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Scenario 02-lite — single real-Qwen prompt under --trace-warnings.
# Demonstrates the steady-state path emits no MaxListenersExceededWarning.
set -uo pipefail
WT="${WT:-$(git rev-parse --show-toplevel)}"
LOG="$WT/docs/verification/abort-controller-refactor/logs/02-lite-short-prompt.log"
mkdir -p "$(dirname "$LOG")"
NODE_OPTIONS=--trace-warnings node "$WT/packages/cli/dist/index.js" \
--prompt "Reply with exactly 'OK' and nothing else." > "$LOG" 2>&1 &
PID=$!
for i in $(seq 1 90); do
if ! kill -0 $PID 2>/dev/null; then break; fi
sleep 1
done
if kill -0 $PID 2>/dev/null; then kill -9 $PID; echo "TIMEOUT"; exit 1; fi
wait $PID 2>/dev/null
EC=$?
echo "EXIT=$EC"
echo "MaxListenersExceededWarning count: $(grep -c MaxListenersExceededWarning "$LOG")"
echo "--- log ---"
cat "$LOG"

View File

@ -0,0 +1,18 @@
#!/usr/bin/env bash
# Scenario 06 — headless --prompt + SIGINT. Verifies the agent shuts down
# cleanly when an external signal aborts the in-flight stream.
set -uo pipefail
WT="${WT:-$(git rev-parse --show-toplevel)}"
LOG="$WT/docs/verification/abort-controller-refactor/logs/06-headless-sigint.log"
mkdir -p "$(dirname "$LOG")"
NODE_OPTIONS=--trace-warnings node "$WT/packages/cli/dist/index.js" \
--prompt "Please write a detailed essay about the history of distributed systems, at least 500 words." > "$LOG" 2>&1 &
PID=$!
sleep 6
kill -INT $PID
wait $PID 2>/dev/null
EC=$?
echo "EXIT_CODE=$EC (expected 130)"
echo "MaxListenersExceededWarning count: $(grep -c MaxListenersExceededWarning "$LOG")"

View File

@ -0,0 +1,2 @@
0.15.11
EXIT=0

View File

@ -0,0 +1,10 @@
✓ |@qwen-code/qwen-code-core| src/core/openaiContentGenerator/provider/minimax.test.ts (9 tests) 2ms
✓ |@qwen-code/qwen-code-core| src/followup/suggestionGenerator.test.ts (16 tests) 2ms
✓ |@qwen-code/qwen-code-core| src/followup/speculation.test.ts (7 tests) 2ms
✓ |@qwen-code/qwen-code| src/utils/warningHandler.test.ts (9 tests) 5ms
Test Files 71 passed (71)
Tests 2085 passed | 3 skipped (2088)
Start at 02:35:37
Duration 16.71s (transform 1.77s, setup 92ms, collect 14.79s, tests 3.03s, environment 319ms, prepare 2.20s)

View File

@ -191,7 +191,14 @@ export default tseslint.config(
},
// extra settings for scripts that we run directly with node
{
files: ['./scripts/**/*.js', './scripts/**/*.mjs', 'esbuild.config.js', 'packages/*/scripts/**/*.js'],
files: [
'./scripts/**/*.js',
'./scripts/**/*.mjs',
'esbuild.config.js',
'packages/*/scripts/**/*.js',
// Verification reproducer scripts under docs/ also run with `node`.
'docs/**/*.mjs',
],
languageOptions: {
globals: {
...globals.node,

121
package-lock.json generated
View File

@ -1,18 +1,19 @@
{
"name": "@qwen-code/qwen-code",
"version": "0.16.1",
"version": "0.17.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@qwen-code/qwen-code",
"version": "0.16.1",
"version": "0.17.0",
"workspaces": [
"packages/*",
"packages/channels/base",
"packages/channels/telegram",
"packages/channels/weixin",
"packages/channels/dingtalk",
"packages/channels/feishu",
"packages/channels/plugin-example"
],
"dependencies": {
@ -2051,6 +2052,21 @@
"integrity": "sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==",
"license": "MIT"
},
"node_modules/@larksuiteoapi/node-sdk": {
"version": "1.65.0",
"resolved": "https://registry.npmjs.org/@larksuiteoapi/node-sdk/-/node-sdk-1.65.0.tgz",
"integrity": "sha512-SkMeiFvi4mMVGrmBBh50vWPOgAvfbcpdcAW+iryheFFHUmji49aDch/YtxsKGFtzFlL/rseQXFzNFL8+LdQQ5Q==",
"license": "MIT",
"dependencies": {
"axios": "~1.13.3",
"lodash.identity": "^3.0.0",
"lodash.merge": "^4.6.2",
"lodash.pickby": "^4.6.0",
"protobufjs": "^7.2.6",
"qs": "^6.14.2",
"ws": "^8.19.0"
}
},
"node_modules/@lydell/node-pty": {
"version": "1.2.0-beta.10",
"resolved": "https://registry.npmjs.org/@lydell/node-pty/-/node-pty-1.2.0-beta.10.tgz",
@ -2561,6 +2577,22 @@
"@opentelemetry/api": "^1.3.0"
}
},
"node_modules/@opentelemetry/instrumentation-undici": {
"version": "0.14.0",
"resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-undici/-/instrumentation-undici-0.14.0.tgz",
"integrity": "sha512-2HN+7ztxAReXuxzrtA3WboAKlfP5OsPA57KQn2AdYZbJ3zeRPcLXyW4uO/jpLE6PLm0QRtmeGCmfYpqRlwgSwg==",
"license": "Apache-2.0",
"dependencies": {
"@opentelemetry/core": "^2.0.0",
"@opentelemetry/instrumentation": "^0.203.0"
},
"engines": {
"node": "^18.19.0 || >=20.6.0"
},
"peerDependencies": {
"@opentelemetry/api": "^1.7.0"
}
},
"node_modules/@opentelemetry/otlp-exporter-base": {
"version": "0.203.0",
"resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.203.0.tgz",
@ -2918,6 +2950,10 @@
"resolved": "packages/channels/dingtalk",
"link": true
},
"node_modules/@qwen-code/channel-feishu": {
"resolved": "packages/channels/feishu",
"link": true
},
"node_modules/@qwen-code/channel-plugin-example": {
"resolved": "packages/channels/plugin-example",
"link": true
@ -10082,27 +10118,6 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/ink/node_modules/ws": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
"integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/internal-slot": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
@ -11356,11 +11371,22 @@
"integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==",
"license": "MIT"
},
"node_modules/lodash.identity": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/lodash.identity/-/lodash.identity-3.0.0.tgz",
"integrity": "sha512-AupTIzdLQxJS5wIYUQlgGyk2XRTfGXA+MCghDHqZk0pzUNYvd3EESS6dkChNauNYVIutcb0dfHw1ri9Q1yPV8Q==",
"license": "MIT"
},
"node_modules/lodash.merge": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
"integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/lodash.pickby": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/lodash.pickby/-/lodash.pickby-4.6.0.tgz",
"integrity": "sha512-AZV+GsS/6ckvPOVQPXSiFFacKvKB4kOQu6ynt9wz0F3LO4R9Ij4K1ddYsIytDpSgLz88JHd9P+oaLeej5/Sl7Q==",
"license": "MIT"
},
"node_modules/log-update": {
@ -16790,9 +16816,9 @@
"license": "ISC"
},
"node_modules/ws": {
"version": "8.18.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
@ -17054,7 +17080,7 @@
},
"packages/acp-bridge": {
"name": "@qwen-code/acp-bridge",
"version": "0.16.1",
"version": "0.17.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1",
"@qwen-code/qwen-code-core": "file:../core"
@ -17069,7 +17095,7 @@
},
"packages/channels/base": {
"name": "@qwen-code/channel-base",
"version": "0.16.1",
"version": "0.17.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1"
},
@ -17079,7 +17105,7 @@
},
"packages/channels/dingtalk": {
"name": "@qwen-code/channel-dingtalk",
"version": "0.16.1",
"version": "0.17.0",
"dependencies": {
"@qwen-code/channel-base": "file:../base",
"dingtalk-stream-sdk-nodejs": "^2.0.4"
@ -17088,9 +17114,20 @@
"typescript": "^5.0.0"
}
},
"packages/channels/feishu": {
"name": "@qwen-code/channel-feishu",
"version": "0.17.0",
"dependencies": {
"@larksuiteoapi/node-sdk": "^1.45.0",
"@qwen-code/channel-base": "file:../base"
},
"devDependencies": {
"typescript": "^5.0.0"
}
},
"packages/channels/plugin-example": {
"name": "@qwen-code/channel-plugin-example",
"version": "0.16.1",
"version": "0.17.0",
"dependencies": {
"@qwen-code/channel-base": "file:../base",
"ws": "^8.18.0"
@ -17104,7 +17141,7 @@
},
"packages/channels/telegram": {
"name": "@qwen-code/channel-telegram",
"version": "0.16.1",
"version": "0.17.0",
"dependencies": {
"@qwen-code/channel-base": "file:../base",
"grammy": "^1.41.1",
@ -17117,7 +17154,7 @@
},
"packages/channels/weixin": {
"name": "@qwen-code/channel-weixin",
"version": "0.16.1",
"version": "0.17.0",
"dependencies": {
"@qwen-code/channel-base": "file:../base"
},
@ -17127,7 +17164,7 @@
},
"packages/cli": {
"name": "@qwen-code/qwen-code",
"version": "0.16.1",
"version": "0.17.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1",
"@google/genai": "1.30.0",
@ -17136,6 +17173,7 @@
"@qwen-code/acp-bridge": "file:../acp-bridge",
"@qwen-code/channel-base": "file:../channels/base",
"@qwen-code/channel-dingtalk": "file:../channels/dingtalk",
"@qwen-code/channel-feishu": "file:../channels/feishu",
"@qwen-code/channel-telegram": "file:../channels/telegram",
"@qwen-code/channel-weixin": "file:../channels/weixin",
"@qwen-code/qwen-code-core": "file:../core",
@ -17549,7 +17587,7 @@
},
"packages/core": {
"name": "@qwen-code/qwen-code-core",
"version": "0.16.1",
"version": "0.17.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^0.36.1",
@ -17564,6 +17602,7 @@
"@opentelemetry/exporter-trace-otlp-grpc": "^0.203.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.203.0",
"@opentelemetry/instrumentation-http": "^0.203.0",
"@opentelemetry/instrumentation-undici": "^0.14.0",
"@opentelemetry/sdk-node": "^0.203.0",
"@types/html-to-text": "^9.0.4",
"@xterm/headless": "5.5.0",
@ -20397,7 +20436,7 @@
},
"packages/vscode-ide-companion": {
"name": "qwen-code-vscode-ide-companion",
"version": "0.16.1",
"version": "0.17.0",
"license": "LICENSE",
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1",
@ -20534,7 +20573,7 @@
},
"packages/web-templates": {
"name": "@qwen-code/web-templates",
"version": "0.16.1",
"version": "0.17.0",
"devDependencies": {
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
@ -20941,9 +20980,9 @@
}
},
"packages/web-templates/node_modules/@types/react": {
"version": "18.3.28",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",
"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",
"version": "18.3.29",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.29.tgz",
"integrity": "sha512-ch0qJdr2JY0r04NXSprbK6TXOgnaJ1Tz23fm5W+z0/CBah6BSBc3n96h7K9GOtwh0HrilNWHIBzE1Ko4Dcw/Wg==",
"dev": true,
"license": "MIT",
"dependencies": {
@ -21062,7 +21101,7 @@
},
"packages/webui": {
"name": "@qwen-code/webui",
"version": "0.16.1",
"version": "0.17.0",
"license": "MIT",
"dependencies": {
"markdown-it": "^14.1.0"

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/qwen-code",
"version": "0.16.1",
"version": "0.17.0",
"engines": {
"node": ">=22.0.0"
},
@ -11,6 +11,7 @@
"packages/channels/telegram",
"packages/channels/weixin",
"packages/channels/dingtalk",
"packages/channels/feishu",
"packages/channels/plugin-example"
],
"repository": {
@ -18,7 +19,7 @@
"url": "git+https://github.com/QwenLM/qwen-code.git"
},
"config": {
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.16.1"
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.17.0"
},
"scripts": {
"start": "cross-env node scripts/start.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/acp-bridge",
"version": "0.16.1",
"version": "0.17.0",
"description": "Shared ACP bridge primitives (EventBus, AcpChannel, in-memory channel, PermissionMediator interface) used by qwen serve, channels, IDE, TUI, and remote-control adapters.",
"repository": {
"type": "git",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-base",
"version": "0.16.1",
"version": "0.17.0",
"description": "Base channel infrastructure for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-dingtalk",
"version": "0.16.1",
"version": "0.17.0",
"description": "DingTalk channel adapter for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -0,0 +1,27 @@
{
"name": "@qwen-code/channel-feishu",
"version": "0.17.0",
"description": "Feishu (Lark) channel adapter for Qwen Code",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsc --build"
},
"dependencies": {
"@qwen-code/channel-base": "file:../base",
"@larksuiteoapi/node-sdk": "^1.45.0"
},
"devDependencies": {
"typescript": "^5.0.0"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,968 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { FeishuChannel } from './FeishuAdapter.js';
import type { ChannelConfig, AcpBridge } from '@qwen-code/channel-base';
function createMockBridge(): AcpBridge {
return {
prompt: vi.fn().mockResolvedValue(undefined),
cancelSession: vi.fn().mockResolvedValue(undefined),
on: vi.fn(),
off: vi.fn(),
} as unknown as AcpBridge;
}
function createConfig(overrides?: Partial<ChannelConfig>): ChannelConfig {
return {
type: 'feishu',
token: '',
clientId: 'test_app_id',
clientSecret: 'test_app_secret',
senderPolicy: 'open',
allowedUsers: [],
sessionScope: 'user',
cwd: '/tmp',
groupPolicy: 'open',
groups: { '*': { requireMention: true } },
...overrides,
};
}
function createChannel(
configOverrides?: Partial<ChannelConfig>,
): FeishuChannel {
const config = createConfig(configOverrides);
const bridge = createMockBridge();
return new FeishuChannel('test', config, bridge);
}
// Access private methods for unit testing
function getPrivateMethod<T>(instance: unknown, method: string): T {
return (instance as Record<string, unknown>)[method] as T;
}
describe('FeishuChannel', () => {
describe('constructor', () => {
it('throws if clientId is missing', () => {
expect(() => createChannel({ clientId: undefined })).toThrow(
/requires clientId/,
);
});
it('throws if clientSecret is missing', () => {
expect(() => createChannel({ clientSecret: undefined })).toThrow(
/requires clientId.*clientSecret/,
);
});
});
describe('extractContent', () => {
let channel: FeishuChannel;
let extractContent: (
messageType: string,
contentJson: string,
) => {
text: string;
imageKey?: string;
fileKey?: string;
fileName?: string;
};
beforeEach(() => {
channel = createChannel();
extractContent = getPrivateMethod<
(
messageType: string,
contentJson: string,
) => {
text: string;
imageKey?: string;
fileKey?: string;
fileName?: string;
}
>(channel, 'extractContent').bind(channel);
});
it('handles text messages', () => {
const result = extractContent('text', JSON.stringify({ text: 'hello' }));
expect(result.text).toBe('hello');
});
it('handles post messages with nested paragraphs', () => {
const post = {
zh_cn: {
title: 'Post Title',
content: [
[
{ tag: 'text', text: 'Line 1 ' },
{ tag: 'a', text: 'link' },
],
[{ tag: 'text', text: 'Line 2' }],
],
},
};
const result = extractContent('post', JSON.stringify(post));
expect(result.text).toContain('Post Title');
expect(result.text).toContain('Line 1 link');
expect(result.text).toContain('Line 2');
});
it('handles image messages', () => {
const result = extractContent(
'image',
JSON.stringify({ image_key: 'img_key_123' }),
);
expect(result.text).toBe('(image)');
expect(result.imageKey).toBe('img_key_123');
});
it('handles file messages', () => {
const result = extractContent(
'file',
JSON.stringify({ file_key: 'file_key_456', file_name: 'doc.pdf' }),
);
expect(result.text).toBe('(file: doc.pdf)');
expect(result.fileKey).toBe('file_key_456');
expect(result.fileName).toBe('doc.pdf');
});
it('handles audio messages', () => {
const result = extractContent('audio', JSON.stringify({}));
expect(result.text).toBe('(audio)');
});
it('handles media (video) messages', () => {
const result = extractContent(
'media',
JSON.stringify({ file_key: 'vid_key', file_name: 'video.mp4' }),
);
expect(result.text).toBe('(video)');
expect(result.fileKey).toBe('vid_key');
expect(result.fileName).toBe('video.mp4');
});
it('returns empty text for unknown types', () => {
const result = extractContent('sticker', JSON.stringify({}));
expect(result.text).toBe('');
});
it('handles malformed JSON gracefully', () => {
const result = extractContent('text', 'not valid json');
expect(result.text).toBe('');
});
it('handles empty content', () => {
const result = extractContent('text', JSON.stringify({}));
expect(result.text).toBe('');
});
});
describe('extractCardText', () => {
let channel: FeishuChannel;
let extractCardText: (card: Record<string, unknown>) => string | undefined;
beforeEach(() => {
channel = createChannel();
extractCardText = getPrivateMethod<
(card: Record<string, unknown>) => string | undefined
>(channel, 'extractCardText').bind(channel);
});
it('extracts markdown from v2 card format (body.elements)', () => {
const card = {
body: {
elements: [
{ tag: 'markdown', content: 'Hello world' },
{ tag: 'markdown', content: 'Second block' },
],
},
};
const result = extractCardText(card);
expect(result).toContain('Hello world');
expect(result).toContain('Second block');
});
it('extracts from collapsible_panel in v2 format', () => {
const card = {
body: {
elements: [
{ tag: 'markdown', content: 'Preview' },
{
tag: 'collapsible_panel',
elements: [{ tag: 'markdown', content: 'Hidden content' }],
},
],
},
};
const result = extractCardText(card);
expect(result).toContain('Preview');
expect(result).toContain('Hidden content');
});
it('extracts from v1/API format (flat elements array)', () => {
const card = {
title: 'Card Title',
elements: [{ tag: 'markdown', content: 'Body text' }],
};
const result = extractCardText(card);
expect(result).toContain('Card Title');
expect(result).toContain('Body text');
});
it('strips streaming indicator', () => {
const card = {
body: {
elements: [{ tag: 'markdown', content: 'Content\n---\n*生成中...*' }],
},
};
const result = extractCardText(card);
expect(result).not.toContain('生成中');
expect(result).toBe('Content');
});
it('returns undefined for empty card', () => {
const result = extractCardText({});
expect(result).toBeUndefined();
});
it('filters fallback text', () => {
const card = {
elements: [
[{ tag: 'text', text: '请升级至最新版本客户端,以查看内容' }],
],
};
const result = extractCardText(card);
expect(result).toBeUndefined();
});
});
describe('state machine: dedup', () => {
let channel: FeishuChannel;
let seenMessages: Map<string, number>;
beforeEach(() => {
channel = createChannel();
seenMessages = getPrivateMethod(channel, 'seenMessages');
});
it('deduplicates messages with same ID within TTL', () => {
seenMessages.set('msg_1', Date.now());
// Simulate calling onMessage with same ID — it should be skipped
const onMessage = getPrivateMethod<(data: unknown) => void>(
channel,
'onMessage',
).bind(channel);
// Mock fetchBotInfo result
(channel as unknown as Record<string, unknown>)['botOpenId'] = 'bot_123';
onMessage({
message: {
message_id: 'msg_1',
chat_id: 'chat_1',
chat_type: 'p2p',
message_type: 'text',
content: JSON.stringify({ text: 'hello' }),
},
sender: {
sender_id: { open_id: 'user_1' },
sender_type: 'user',
},
});
// Should not create a card session since it's a duplicate
const cardSessions = getPrivateMethod<Map<string, unknown>>(
channel,
'cardSessions',
);
expect(cardSessions.has('msg_1')).toBe(false);
});
it('allows message after TTL expiry', () => {
// Set a message that expired 6 minutes ago
const DEDUP_TTL_MS = 5 * 60 * 1000;
seenMessages.set('msg_old', Date.now() - DEDUP_TTL_MS - 1000);
// Simulate the cleanup timer logic
const now = Date.now();
for (const [id, ts] of seenMessages) {
if (now - ts > DEDUP_TTL_MS) {
seenMessages.delete(id);
}
}
expect(seenMessages.has('msg_old')).toBe(false);
});
});
describe('state machine: cleanupCard', () => {
let channel: FeishuChannel;
let cleanupCard: (inboundMsgId: string) => void;
beforeEach(() => {
channel = createChannel();
cleanupCard = getPrivateMethod<(id: string) => void>(
channel,
'cleanupCard',
).bind(channel);
});
it('cleans up all maps for a given inbound message', () => {
const cardSessions = getPrivateMethod<Map<string, unknown>>(
channel,
'cardSessions',
);
const sessionToInboundMsg = getPrivateMethod<Map<string, string>>(
channel,
'sessionToInboundMsg',
);
const msgToQuestion = getPrivateMethod<Map<string, string>>(
channel,
'msgToQuestion',
);
const msgToSenderName = getPrivateMethod<Map<string, string>>(
channel,
'msgToSenderName',
);
// Populate all maps
cardSessions.set('msg_1', {
messageId: 'card_1',
created: true,
creating: false,
stopped: false,
accumulatedText: 'test',
lastUpdateAt: Date.now(),
});
sessionToInboundMsg.set('session_1', 'msg_1');
msgToQuestion.set('msg_1', 'question?');
msgToSenderName.set('msg_1', '<at>user</at>');
cleanupCard('msg_1');
expect(cardSessions.has('msg_1')).toBe(false);
expect(sessionToInboundMsg.has('session_1')).toBe(false);
expect(msgToQuestion.has('msg_1')).toBe(false);
expect(msgToSenderName.has('msg_1')).toBe(false);
});
it('clears pending timer on cleanup', () => {
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
const clearTimeoutSpy = vi.spyOn(global, 'clearTimeout');
const timer = setTimeout(() => {}, 10000);
cardSessions.set('msg_2', {
messageId: 'card_2',
created: true,
creating: false,
stopped: false,
accumulatedText: '',
lastUpdateAt: Date.now(),
pendingUpdateTimer: timer,
});
cleanupCard('msg_2');
expect(clearTimeoutSpy).toHaveBeenCalledWith(timer);
expect(cardSessions.has('msg_2')).toBe(false);
clearTimeoutSpy.mockRestore();
});
});
describe('state machine: stop button during card creation', () => {
let channel: FeishuChannel;
beforeEach(() => {
channel = createChannel();
});
it('marks card as stopped even when still creating', async () => {
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
// Simulate card in "creating" state
cardSessions.set('inbound_1', {
messageId: 'card_1',
created: false,
creating: true,
stopped: false,
accumulatedText: 'partial text',
lastUpdateAt: Date.now(),
});
// Mock bridge
const bridge = getPrivateMethod<AcpBridge>(channel, 'bridge');
const cancelSessionSpy = vi
.spyOn(bridge, 'cancelSession')
.mockResolvedValue(undefined);
// Mock updateCard to not actually call HTTP
const updateCardMock = vi.fn().mockResolvedValue(true);
(channel as unknown as Record<string, unknown>)['updateCard'] =
updateCardMock;
// Simulate sessionToInboundMsg mapping
const sessionToInboundMsg = getPrivateMethod<Map<string, string>>(
channel,
'sessionToInboundMsg',
);
sessionToInboundMsg.set('session_abc', 'inbound_1');
// Simulate msgToSenderId mapping (fail-closed auth check)
const msgToSenderId = getPrivateMethod<Map<string, string>>(
channel,
'msgToSenderId',
);
msgToSenderId.set('inbound_1', 'user_open_id');
// Call onCardAction with stop
const onCardAction = getPrivateMethod<
(data: Record<string, unknown>) => boolean
>(channel, 'onCardAction').bind(channel);
onCardAction({
action: { value: { action: 'stop' } },
context: { open_message_id: 'card_1' },
operator: { open_id: 'user_open_id' },
});
const state = cardSessions.get('inbound_1') as
| Record<string, unknown>
| undefined;
// cancelling is set synchronously (stopped is deferred until cancelSession resolves)
expect(state?.['cancelling']).toBe(true);
// Wait for async handleStop to complete — stopped is set after cancelSession resolves
await vi.waitFor(() => {
expect(state?.['stopped']).toBe(true);
});
expect(cancelSessionSpy).toHaveBeenCalledWith('session_abc');
expect(state?.['cancelling']).toBe(false);
});
it('rejects stop from a different user (operator mismatch)', () => {
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
cardSessions.set('inbound_1', {
messageId: 'card_1',
created: true,
creating: false,
stopped: false,
accumulatedText: 'test',
lastUpdateAt: Date.now(),
});
const msgToSenderId = getPrivateMethod<Map<string, string>>(
channel,
'msgToSenderId',
);
msgToSenderId.set('inbound_1', 'original_user');
const onCardAction = getPrivateMethod<
(data: Record<string, unknown>) => boolean
>(channel, 'onCardAction').bind(channel);
const result = onCardAction({
action: { value: { action: 'stop' } },
context: { open_message_id: 'card_1' },
operator: { open_id: 'different_user' },
});
expect(result).toBe(false);
const state = cardSessions.get('inbound_1') as
| Record<string, unknown>
| undefined;
expect(state?.['stopped']).toBe(false);
});
it('rejects stop when operator field is missing (fail-closed)', () => {
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
cardSessions.set('inbound_1', {
messageId: 'card_1',
created: true,
creating: false,
stopped: false,
accumulatedText: 'test',
lastUpdateAt: Date.now(),
});
const msgToSenderId = getPrivateMethod<Map<string, string>>(
channel,
'msgToSenderId',
);
msgToSenderId.set('inbound_1', 'original_user');
const onCardAction = getPrivateMethod<
(data: Record<string, unknown>) => boolean
>(channel, 'onCardAction').bind(channel);
// No operator field at all
const result = onCardAction({
action: { value: { action: 'stop' } },
context: { open_message_id: 'card_1' },
});
expect(result).toBe(false);
});
it('rejects stop when msgToSenderId has no entry (no originalSender)', () => {
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
cardSessions.set('inbound_1', {
messageId: 'card_1',
created: true,
creating: false,
stopped: false,
accumulatedText: 'test',
lastUpdateAt: Date.now(),
});
// msgToSenderId intentionally not populated for inbound_1
const onCardAction = getPrivateMethod<
(data: Record<string, unknown>) => boolean
>(channel, 'onCardAction').bind(channel);
const result = onCardAction({
action: { value: { action: 'stop' } },
context: { open_message_id: 'card_1' },
operator: { open_id: 'some_user' },
});
expect(result).toBe(false);
});
});
describe('disconnect', () => {
it('closes wsClient on disconnect', () => {
const channel = createChannel();
const mockClose = vi.fn();
(channel as unknown as Record<string, unknown>)['wsClient'] = {
close: mockClose,
};
channel.disconnect();
expect(mockClose).toHaveBeenCalled();
expect(
(channel as unknown as Record<string, unknown>)['wsClient'],
).toBeUndefined();
});
it('clears dedup timer on disconnect', () => {
const channel = createChannel();
const clearIntervalSpy = vi.spyOn(global, 'clearInterval');
const timer = setInterval(() => {}, 60000);
(channel as unknown as Record<string, unknown>)['dedupTimer'] = timer;
channel.disconnect();
expect(clearIntervalSpy).toHaveBeenCalledWith(timer);
clearIntervalSpy.mockRestore();
clearInterval(timer);
});
});
describe('extractContent: post at-node mentions', () => {
it('extracts @mention user_name from post at nodes', () => {
const channel = createChannel();
const extractContent = getPrivateMethod<
(messageType: string, contentJson: string) => { text: string }
>(channel, 'extractContent').bind(channel);
const post = {
zh_cn: {
title: '',
content: [
[
{ tag: 'text', text: 'hello ' },
{ tag: 'at', user_id: 'ou_123', user_name: 'John' },
{ tag: 'text', text: ' check this' },
],
],
},
};
const result = extractContent('post', JSON.stringify(post));
expect(result.text).toBe('hello @John check this');
});
it('handles at node without user_name gracefully', () => {
const channel = createChannel();
const extractContent = getPrivateMethod<
(messageType: string, contentJson: string) => { text: string }
>(channel, 'extractContent').bind(channel);
const post = {
zh_cn: {
title: '',
content: [
[
{ tag: 'text', text: 'hello ' },
{ tag: 'at', user_id: 'ou_123' },
],
],
},
};
const result = extractContent('post', JSON.stringify(post));
expect(result.text).toBe('hello');
});
});
describe('onCardAction: cancelSession failure', () => {
it('shows "停止失败" when cancelSession throws', async () => {
const bridge = createMockBridge();
(bridge.cancelSession as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
new Error('session not found'),
);
const config = createConfig();
const channel = new FeishuChannel('test', config, bridge);
// Set up botOpenId and card state
(channel as unknown as Record<string, unknown>)['botOpenId'] = 'bot_123';
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
cardSessions.set('inbound_1', {
messageId: 'card_1',
created: true,
creating: false,
stopped: false,
accumulatedText: 'some text',
lastUpdateAt: Date.now(),
});
const msgToSenderId = getPrivateMethod<Map<string, string>>(
channel,
'msgToSenderId',
);
msgToSenderId.set('inbound_1', 'original_user');
const msgToSenderName = getPrivateMethod<Map<string, string>>(
channel,
'msgToSenderName',
);
msgToSenderName.set('inbound_1', '@sender');
// Set up session mapping so cancelSession is actually called
const sessionToInboundMsg = getPrivateMethod<Map<string, string>>(
channel,
'sessionToInboundMsg',
);
sessionToInboundMsg.set('session_1', 'inbound_1');
// Mock updateCard to capture the text
const updateCardSpy = vi.fn().mockResolvedValue(true);
(channel as unknown as Record<string, unknown>)['updateCard'] =
updateCardSpy;
const onCardAction = getPrivateMethod<
(data: Record<string, unknown>) => boolean
>(channel, 'onCardAction').bind(channel);
onCardAction({
action: { value: { action: 'stop' } },
context: { open_message_id: 'card_1' },
operator: { open_id: 'original_user' },
});
// Wait for the fire-and-forget handleStop to complete
await new Promise((r) => setTimeout(r, 50));
expect(updateCardSpy).toHaveBeenCalled();
const cardText = updateCardSpy.mock.calls[0][1] as string;
expect(cardText).toContain('停止失败');
});
});
describe('deleteCard', () => {
it('returns true on successful deletion', async () => {
const channel = createChannel();
const fetchMock = vi
.fn()
.mockResolvedValue(new Response(null, { status: 200 }));
vi.spyOn(global, 'fetch').mockImplementation(fetchMock);
// Provide a valid token
(channel as unknown as Record<string, unknown>)['tokenCache'] = {
token: 'test_token',
expiresAt: Date.now() + 3600_000,
};
const deleteCard = getPrivateMethod<
(messageId: string) => Promise<boolean>
>(channel, 'deleteCard').bind(channel);
const result = await deleteCard('om_test_msg_id');
expect(result).toBe(true);
expect(fetchMock).toHaveBeenCalledWith(
expect.stringContaining('/im/v1/messages/om_test_msg_id'),
expect.objectContaining({ method: 'DELETE' }),
);
});
it('returns false when token is unavailable', async () => {
const channel = createChannel();
// No token cache and getTenantAccessToken will fail
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ code: -1 }), { status: 500 }),
);
vi.spyOn(global, 'fetch').mockImplementation(fetchMock);
const deleteCard = getPrivateMethod<
(messageId: string) => Promise<boolean>
>(channel, 'deleteCard').bind(channel);
const result = await deleteCard('om_test_msg_id');
expect(result).toBe(false);
});
it('returns false on HTTP error', async () => {
const channel = createChannel();
(channel as unknown as Record<string, unknown>)['tokenCache'] = {
token: 'test_token',
expiresAt: Date.now() + 3600_000,
};
const fetchMock = vi
.fn()
.mockResolvedValue(new Response('not found', { status: 404 }));
vi.spyOn(global, 'fetch').mockImplementation(fetchMock);
const deleteCard = getPrivateMethod<
(messageId: string) => Promise<boolean>
>(channel, 'deleteCard').bind(channel);
const result = await deleteCard('om_test_msg_id');
expect(result).toBe(false);
});
it('clears token cache on 401', async () => {
const channel = createChannel();
(channel as unknown as Record<string, unknown>)['tokenCache'] = {
token: 'stale_token',
expiresAt: Date.now() + 3600_000,
};
const fetchMock = vi
.fn()
.mockResolvedValue(new Response('unauthorized', { status: 401 }));
vi.spyOn(global, 'fetch').mockImplementation(fetchMock);
const deleteCard = getPrivateMethod<
(messageId: string) => Promise<boolean>
>(channel, 'deleteCard').bind(channel);
await deleteCard('om_test_msg_id');
expect(
(channel as unknown as Record<string, unknown>)['tokenCache'],
).toBeUndefined();
});
});
describe('sendMessage: token failure logging', () => {
it('logs and returns early when token is unavailable', async () => {
const channel = createChannel();
const stderrSpy = vi
.spyOn(process.stderr, 'write')
.mockImplementation(() => true);
// No token available
await channel.sendMessage('oc_chat_id', 'hello');
expect(stderrSpy).toHaveBeenCalledWith(
expect.stringContaining('Cannot send: no access token'),
);
stderrSpy.mockRestore();
});
});
describe('onPromptEnd: error recovery branches', () => {
it('sends error fallback when card creation failed and no accumulated text', async () => {
const channel = createChannel();
(channel as unknown as Record<string, unknown>)['botOpenId'] = 'bot_123';
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
cardSessions.set('inbound_1', {
messageId: '',
created: false,
creating: false,
stopped: false,
finalizing: false,
completed: false,
abandoned: false,
accumulatedText: '',
lastUpdateAt: Date.now(),
});
const sendMessageSpy = vi.fn().mockResolvedValue(undefined);
(channel as unknown as Record<string, unknown>)['sendMessage'] =
sendMessageSpy;
const onPromptEnd = getPrivateMethod<
(chatId: string, sessionId: string, messageId?: string) => Promise<void>
>(channel, 'onPromptEnd').bind(channel);
const sessionToInboundMsg = getPrivateMethod<Map<string, string>>(
channel,
'sessionToInboundMsg',
);
sessionToInboundMsg.set('session_1', 'inbound_1');
await onPromptEnd('oc_chat_id', 'session_1');
// Should send error fallback message
expect(sendMessageSpy).toHaveBeenCalledWith(
'oc_chat_id',
expect.stringContaining('出错了'),
);
});
it('sends accumulated text via sendMessage when card creation failed', async () => {
const channel = createChannel();
(channel as unknown as Record<string, unknown>)['botOpenId'] = 'bot_123';
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
cardSessions.set('inbound_1', {
messageId: '',
created: false,
creating: false,
stopped: false,
finalizing: false,
completed: false,
abandoned: false,
accumulatedText: 'partial response text',
lastUpdateAt: Date.now(),
});
const sendMessageSpy = vi.fn().mockResolvedValue(undefined);
(channel as unknown as Record<string, unknown>)['sendMessage'] =
sendMessageSpy;
const onPromptEnd = getPrivateMethod<
(chatId: string, sessionId: string, messageId?: string) => Promise<void>
>(channel, 'onPromptEnd').bind(channel);
const sessionToInboundMsg = getPrivateMethod<Map<string, string>>(
channel,
'sessionToInboundMsg',
);
sessionToInboundMsg.set('session_1', 'inbound_1');
await onPromptEnd('oc_chat_id', 'session_1');
expect(sendMessageSpy).toHaveBeenCalledWith(
'oc_chat_id',
expect.stringContaining('partial response text'),
);
});
});
describe('onResponseComplete: stopped card cleanup', () => {
it('cleans up and returns early when card was stopped', async () => {
const channel = createChannel();
(channel as unknown as Record<string, unknown>)['botOpenId'] = 'bot_123';
const cardSessions = getPrivateMethod<
Map<string, Record<string, unknown>>
>(channel, 'cardSessions');
cardSessions.set('inbound_1', {
messageId: 'card_1',
created: true,
creating: false,
stopped: true,
finalizing: false,
completed: true,
abandoned: false,
accumulatedText: 'text',
lastUpdateAt: Date.now(),
});
const sessionToInboundMsg = getPrivateMethod<Map<string, string>>(
channel,
'sessionToInboundMsg',
);
sessionToInboundMsg.set('session_1', 'inbound_1');
const sendMessageSpy = vi.fn().mockResolvedValue(undefined);
(channel as unknown as Record<string, unknown>)['sendMessage'] =
sendMessageSpy;
const onResponseComplete = getPrivateMethod<
(chatId: string, fullText: string, sessionId: string) => Promise<void>
>(channel, 'onResponseComplete').bind(channel);
await onResponseComplete('oc_chat_id', 'full response', 'session_1');
// Should NOT call sendMessage — the stop handler owns the card
expect(sendMessageSpy).not.toHaveBeenCalled();
// Card session should be cleaned up
expect(cardSessions.has('inbound_1')).toBe(false);
});
});
describe('webhook: JSON parse error logging', () => {
it('logs error message on malformed JSON body', async () => {
// This test verifies the fix is in place by checking the source code
// contains the error capture. A full integration test would require
// starting an HTTP server.
const channel = createChannel();
const connectWebhook = getPrivateMethod<
(
port: number,
verificationToken?: string,
encryptKey?: string,
) => Promise<void>
>(channel, 'connectWebhook').bind(channel);
// Just verify the method exists and is callable
expect(typeof connectWebhook).toBe('function');
});
});
describe('auxiliary map lifecycle', () => {
it('preserves auxiliary maps after handleInbound when no card session exists', () => {
const channel = createChannel();
// Simulate the state after processMessage populates maps but
// handleInbound (collect mode) didn't create a card session
const msgToQuestion = getPrivateMethod<Map<string, string>>(
channel,
'msgToQuestion',
);
const msgToSenderName = getPrivateMethod<Map<string, string>>(
channel,
'msgToSenderName',
);
const msgToSenderId = getPrivateMethod<Map<string, string>>(
channel,
'msgToSenderId',
);
const cardSessions = getPrivateMethod<Map<string, unknown>>(
channel,
'cardSessions',
);
// Populate auxiliary maps (as processMessage would)
msgToQuestion.set('msg_collect', 'question?');
msgToSenderName.set('msg_collect', '@sender');
msgToSenderId.set('msg_collect', 'user_123');
// No cardSession for msg_collect (collect mode)
// Verify maps are intact (the old code would have deleted them here)
expect(msgToQuestion.has('msg_collect')).toBe(true);
expect(msgToSenderName.has('msg_collect')).toBe(true);
expect(msgToSenderId.has('msg_collect')).toBe(true);
expect(cardSessions.has('msg_collect')).toBe(false);
});
});
});

View File

@ -0,0 +1,13 @@
export { FeishuChannel } from './FeishuAdapter.js';
export { downloadMedia } from './media.js';
import { FeishuChannel } from './FeishuAdapter.js';
import type { ChannelPlugin } from '@qwen-code/channel-base';
export const plugin: ChannelPlugin = {
channelType: 'feishu',
displayName: 'Feishu',
requiredConfigFields: ['clientId', 'clientSecret'],
createChannel: (name, config, bridge, options) =>
new FeishuChannel(name, config, bridge, options),
};

View File

@ -0,0 +1,179 @@
import { describe, it, expect } from 'vitest';
import { buildCardContent, extractTitle, splitChunks } from './markdown.js';
interface CardElement {
tag: string;
content?: string;
value?: Record<string, unknown>;
elements?: CardElement[];
}
interface CardStructure {
schema: string;
header?: { title: { content: string }; template: string };
body: { elements: CardElement[] };
}
describe('Feishu markdown utilities', () => {
describe('buildCardContent', () => {
it('returns a valid card structure', () => {
const card = buildCardContent('Hello world') as unknown as CardStructure;
expect(card.schema).toBe('2.0');
expect(card.body.elements).toBeDefined();
expect(card.body.elements[0]!.tag).toBe('markdown');
expect(card.body.elements[0]!.content).toBe('Hello world');
});
it('adds streaming indicator when isStreaming is true', () => {
const card = buildCardContent('text', {
isStreaming: true,
}) as unknown as CardStructure;
expect(card.body.elements[0]!.content).toContain('生成中...');
});
it('adds stop button when showStopButton is true', () => {
const card = buildCardContent('text', {
showStopButton: true,
}) as unknown as CardStructure;
const button = card.body.elements.find((e) => e.tag === 'button');
expect(button).toBeDefined();
expect(button!.value).toEqual({ action: 'stop' });
});
it('sets header with title', () => {
const card = buildCardContent('text', {
title: 'My Title',
}) as unknown as CardStructure;
expect(card.header!.title.content).toBe('My Title');
expect(card.header!.template).toBe('green');
});
it('sets blue header when streaming', () => {
const card = buildCardContent('text', {
title: 'Title',
isStreaming: true,
}) as unknown as CardStructure;
expect(card.header!.template).toBe('blue');
expect(card.header!.title.content).toBe('Title ...');
});
it('uses collapsible panel for long content when enabled', () => {
const longText = 'a'.repeat(600);
const card = buildCardContent(longText, {
collapsible: true,
collapsibleThreshold: 500,
}) as unknown as CardStructure;
const panel = card.body.elements.find(
(e) => e.tag === 'collapsible_panel',
);
expect(panel).toBeDefined();
});
it('does not use collapsible for short content', () => {
const card = buildCardContent('short', {
collapsible: true,
collapsibleThreshold: 500,
}) as unknown as CardStructure;
const panel = card.body.elements.find(
(e) => e.tag === 'collapsible_panel',
);
expect(panel).toBeUndefined();
});
});
describe('extractTitle', () => {
it('extracts title from first line', () => {
expect(extractTitle('Hello World\nmore text')).toBe('Hello World');
});
it('strips markdown heading markers', () => {
expect(extractTitle('## My Title\ncontent')).toBe('My Title');
});
it('strips bold/list markers', () => {
expect(extractTitle('* Item one')).toBe('Item one');
expect(extractTitle('> Quote text')).toBe('Quote text');
});
it('truncates to 20 chars', () => {
expect(
extractTitle('This is a very long title that should be truncated')
.length,
).toBeLessThanOrEqual(20);
});
it('returns default for empty text', () => {
expect(extractTitle('')).toBe('Qwen Code');
expect(extractTitle('###')).toBe('Qwen Code');
});
});
describe('splitChunks', () => {
it('returns single chunk for short text', () => {
expect(splitChunks('short text')).toEqual(['short text']);
});
it('returns single chunk for empty text', () => {
expect(splitChunks('')).toEqual(['']);
});
it('splits long text into chunks', () => {
const line = 'a'.repeat(100) + '\n';
const text = line.repeat(50); // 5050 chars > 4000
const chunks = splitChunks(text);
expect(chunks.length).toBeGreaterThan(1);
chunks.forEach((chunk) => {
expect(chunk.length).toBeLessThanOrEqual(4100);
});
});
it('closes and reopens code fences across boundaries', () => {
const longCode = '```\n' + 'x\n'.repeat(2500) + '```';
const chunks = splitChunks(longCode);
expect(chunks.length).toBeGreaterThan(1);
expect(chunks[0]).toContain('```');
if (chunks.length > 1) {
expect(chunks[1]!.trimStart().startsWith('```')).toBe(true);
}
});
it('hard-splits a single line exceeding CHUNK_LIMIT', () => {
const longLine = 'a'.repeat(5000);
const chunks = splitChunks(longLine);
expect(chunks.length).toBe(2);
expect(chunks[0]!.length).toBe(4000);
expect(chunks[1]!.length).toBe(1000);
});
});
describe('buildCardContent table splitting', () => {
it('splits table and following content into separate elements', () => {
const md = [
'Before table',
'| A | B |',
'| --- | --- |',
'| 1 | 2 |',
'After table',
].join('\n');
const card = buildCardContent(md) as unknown as CardStructure;
const mdElements = card.body.elements.filter((e) => e.tag === 'markdown');
expect(mdElements.length).toBeGreaterThanOrEqual(3);
});
it('keeps content without tables in one element', () => {
const md = 'Hello\nWorld\nNo tables here';
const card = buildCardContent(md) as unknown as CardStructure;
const mdElements = card.body.elements.filter((e) => e.tag === 'markdown');
expect(mdElements.length).toBe(1);
});
it('does not split tables inside code fences', () => {
const md = ['```', '| A | B |', '| --- | --- |', '| 1 | 2 |', '```'].join(
'\n',
);
const card = buildCardContent(md) as unknown as CardStructure;
const mdElements = card.body.elements.filter((e) => e.tag === 'markdown');
expect(mdElements.length).toBe(1);
});
});
});

View File

@ -0,0 +1,256 @@
/**
* Feishu markdown / rich text helpers.
*
* Feishu supports Markdown in interactive cards but has quirks:
* - Tables render only in card messages (not in plain text messages)
* - Max message content ~4000 chars — split into chunks
* - Code fences must be closed/reopened across chunk boundaries
*/
const CHUNK_LIMIT = 4000;
/**
* Split markdown into segments so that each segment contains at most one table.
* This avoids Feishu card rendering issues when a single markdown element
* contains a table followed by other content.
*/
function splitByTables(text: string): string[] {
const lines = text.split('\n');
const segments: string[] = [];
let current: string[] = [];
let inTable = false;
let inCode = false;
for (const line of lines) {
// Track code fences (parity-based to handle inline code on same line)
if ((line.match(/```/g) || []).length % 2 === 1) {
inCode = !inCode;
current.push(line);
continue;
}
if (inCode) {
current.push(line);
continue;
}
const isTableLine =
line.trim().startsWith('|') && line.trim().endsWith('|');
if (isTableLine && !inTable) {
// Entering a table — if there's content before, flush it
if (current.length > 0 && current.some((l) => l.trim())) {
segments.push(current.join('\n'));
current = [];
}
inTable = true;
current.push(line);
} else if (!isTableLine && inTable) {
// Leaving a table — flush the table segment
inTable = false;
segments.push(current.join('\n'));
current = [line];
} else {
current.push(line);
}
}
if (current.length > 0) {
segments.push(current.join('\n'));
}
return segments.filter((s) => s.trim());
}
/**
* Build a Feishu interactive card JSON structure with markdown content.
* Uses a clean design with header, streaming indicator, and optional stop button.
*/
export function buildCardContent(
markdown: string,
options?: {
title?: string;
showStopButton?: boolean;
isStreaming?: boolean;
collapsible?: boolean;
collapsibleThreshold?: number;
},
): Record<string, unknown> {
const elements: Array<Record<string, unknown>> = [];
// Main content + streaming indicator in one markdown block
const contentMd = options?.isStreaming
? markdown + '\n\n---\n*生成中...*'
: markdown;
const threshold = options?.collapsibleThreshold || 500;
// For long content, use collapsible panel if enabled
if (
options?.collapsible &&
!options?.isStreaming &&
markdown.length > threshold
) {
// Find a split point near position 200 that doesn't break code fences
const previewEnd = markdown.indexOf('\n', 200);
const rawSplit = previewEnd > 0 ? previewEnd : 200;
const safeSplit = markdown.lastIndexOf(' ', rawSplit);
let splitAt = safeSplit > 100 ? safeSplit : rawSplit;
// Verify fence parity at split point — if preview has odd fences,
// move split to the nearest newline before/after where fences balance
const previewCandidate = markdown.slice(0, splitAt);
let fenceCount = 0;
for (const line of previewCandidate.split('\n')) {
if ((line.match(/```/g) || []).length % 2 === 1) fenceCount++;
}
if (fenceCount % 2 === 1) {
// Inside a code block — find the closing fence and split after it
const fenceStart = markdown.indexOf('\n```', splitAt);
if (fenceStart > 0 && fenceStart < rawSplit + 500) {
const fenceLineEnd = markdown.indexOf('\n', fenceStart + 1);
splitAt = fenceLineEnd > 0 ? fenceLineEnd : fenceStart + 4;
}
// else: no nearby closing fence, accept the split as-is
}
const preview = markdown.slice(0, splitAt);
const rest = markdown.slice(splitAt);
elements.push({
tag: 'markdown',
content: preview,
});
elements.push({
tag: 'collapsible_panel',
expanded: false,
background_color: 'default',
header: {
title: {
tag: 'plain_text',
content: '查看更多',
},
},
elements: [
{
tag: 'markdown',
content: rest,
},
],
});
} else if (options?.isStreaming) {
// During streaming, keep a single markdown element to avoid structure flicker
elements.push({
tag: 'markdown',
content: contentMd,
});
} else {
// Final render: split by tables to avoid rendering issues
const segments = splitByTables(contentMd);
for (const segment of segments) {
elements.push({
tag: 'markdown',
content: segment,
});
}
}
// Stop button
if (options?.showStopButton) {
elements.push({
tag: 'button',
text: {
tag: 'plain_text',
content: '停止',
},
type: 'danger',
value: { action: 'stop' },
});
}
// Header
const header = options?.title
? {
title: {
tag: 'plain_text',
content: options.isStreaming ? `${options.title} ...` : options.title,
},
template: options.isStreaming ? 'blue' : 'green',
}
: undefined;
return {
schema: '2.0',
config: {
wide_screen_mode: true,
summary: { content: markdown.slice(0, 3500) },
},
header,
body: { elements },
};
}
/** Extract a short title from the first line of markdown. */
export function extractTitle(text: string): string {
const firstLine = text.split('\n')[0] || '';
const cleaned = firstLine.replace(/^[#*\s\->]+/, '').slice(0, 20);
return cleaned || 'Qwen Code';
}
/**
* Split long text into chunks that fit within Feishu's message size limit.
* Handles code fence boundaries across chunks.
*/
export function splitChunks(text: string): string[] {
if (!text || text.length <= CHUNK_LIMIT) {
return [text];
}
const chunks: string[] = [];
let buf = '';
const lines = text.split('\n');
let inCode = false;
let fenceLine = '```';
for (const line of lines) {
const fenceCount = (line.match(/```/g) || []).length;
// Reserve space for closing fence when inside a code block
const reserve = inCode ? fenceLine.length + 1 : 0;
if (
buf.length + line.length + 1 + reserve > CHUNK_LIMIT &&
buf.length > 0
) {
if (inCode) {
buf += '\n```';
}
chunks.push(buf);
buf = inCode ? fenceLine : '';
}
buf += (buf ? '\n' : '') + line;
// Hard-split oversized lines that exceed the limit on their own
while (buf.length > CHUNK_LIMIT) {
const maxSlice = inCode ? CHUNK_LIMIT - '\n```'.length - 1 : CHUNK_LIMIT;
let piece = buf.slice(0, maxSlice);
buf = buf.slice(maxSlice);
if (inCode) {
piece += '\n```';
buf = fenceLine + '\n' + buf;
}
chunks.push(piece);
}
if (fenceCount % 2 === 1) {
if (!inCode) {
fenceLine = line.trim();
}
inCode = !inCode;
}
}
if (buf) {
chunks.push(buf);
}
return chunks;
}

View File

@ -0,0 +1,203 @@
import {
describe,
it,
expect,
vi,
beforeEach,
afterEach,
type MockInstance,
} from 'vitest';
import { downloadMedia } from './media.js';
describe('downloadMedia', () => {
let fetchSpy: MockInstance<typeof fetch>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
});
afterEach(() => {
fetchSpy.mockRestore();
});
it('should download file successfully', async () => {
const mockData = new Uint8Array([1, 2, 3, 4]);
const mockResponse = {
ok: true,
headers: {
get: (key: string) => {
if (key === 'content-length') return '4';
if (key === 'content-type') return 'image/png';
return null;
},
},
body: {
getReader: () => ({
read: vi
.fn()
.mockResolvedValueOnce({ done: false, value: mockData })
.mockResolvedValueOnce({ done: true, value: undefined }),
cancel: vi.fn(),
}),
},
};
fetchSpy.mockResolvedValueOnce(mockResponse as unknown as Response);
const result = await downloadMedia(
'om_valid_msg',
'file_valid_key',
'image',
'valid_token',
);
expect(result).not.toBeNull();
expect(result?.buffer).toEqual(Buffer.from(mockData));
expect(result?.mimeType).toBe('image/png');
});
it('should reject invalid messageId (path traversal)', async () => {
const result = await downloadMedia(
'../../../etc/passwd',
'file_key',
'file',
'token',
);
expect(result).toBeNull();
expect(fetchSpy).not.toHaveBeenCalled();
});
it('should reject invalid fileKey (path traversal)', async () => {
const result = await downloadMedia(
'om_msg',
'../../../etc/passwd',
'file',
'token',
);
expect(result).toBeNull();
expect(fetchSpy).not.toHaveBeenCalled();
});
it('should reject empty parameters', async () => {
expect(await downloadMedia('', 'file_key', 'file', 'token')).toBeNull();
expect(await downloadMedia('om_msg', '', 'file', 'token')).toBeNull();
expect(await downloadMedia('om_msg', 'file_key', 'file', '')).toBeNull();
expect(fetchSpy).not.toHaveBeenCalled();
});
it('should return null on HTTP error', async () => {
const mockResponse = {
ok: false,
status: 404,
text: vi.fn().mockResolvedValue('Not found'),
};
fetchSpy.mockResolvedValueOnce(mockResponse as unknown as Response);
const result = await downloadMedia('om_msg', 'file_key', 'file', 'token');
expect(result).toBeNull();
});
it('should reject Content-Length exceeding 50MB', async () => {
const largeSize = 60 * 1024 * 1024; // 60 MB
const mockResponse = {
ok: true,
headers: {
get: (key: string) => {
if (key === 'content-length') return largeSize.toString();
return null;
},
},
body: {
getReader: () => ({
read: vi.fn().mockResolvedValue({ done: true, value: undefined }),
cancel: vi.fn(),
}),
},
};
fetchSpy.mockResolvedValueOnce(mockResponse as unknown as Response);
const result = await downloadMedia('om_msg', 'file_key', 'file', 'token');
expect(result).toBeNull();
});
it('should reject stream exceeding 50MB', async () => {
const chunkSize = 10 * 1024 * 1024; // 10 MB per chunk
const mockData = new Uint8Array(chunkSize);
const cancelMock = vi.fn();
const mockResponse = {
ok: true,
headers: {
get: () => null, // No content-length header
},
body: {
getReader: () => ({
read: vi.fn().mockResolvedValue({ done: false, value: mockData }), // Infinite stream
cancel: cancelMock,
}),
},
};
fetchSpy.mockResolvedValueOnce(mockResponse as unknown as Response);
const result = await downloadMedia('om_msg', 'file_key', 'file', 'token');
expect(result).toBeNull();
expect(cancelMock).toHaveBeenCalled();
});
it('should return null when response body is null', async () => {
const mockResponse = {
ok: true,
headers: {
get: () => null,
},
body: null,
};
fetchSpy.mockResolvedValueOnce(mockResponse as unknown as Response);
const result = await downloadMedia('om_msg', 'file_key', 'file', 'token');
expect(result).toBeNull();
});
it('should handle network errors', async () => {
fetchSpy.mockRejectedValueOnce(new Error('Network error'));
const result = await downloadMedia('om_msg', 'file_key', 'file', 'token');
expect(result).toBeNull();
});
it('should handle missing content-type header', async () => {
const mockData = new Uint8Array([1, 2, 3]);
const mockResponse = {
ok: true,
headers: {
get: () => null, // No content-type
},
body: {
getReader: () => ({
read: vi
.fn()
.mockResolvedValueOnce({ done: false, value: mockData })
.mockResolvedValueOnce({ done: true, value: undefined }),
cancel: vi.fn(),
}),
},
};
fetchSpy.mockResolvedValueOnce(mockResponse as unknown as Response);
const result = await downloadMedia('om_msg', 'file_key', 'file', 'token');
expect(result).not.toBeNull();
expect(result?.mimeType).toBe('application/octet-stream'); // Default
});
});

View File

@ -0,0 +1,102 @@
/**
* Feishu media download helpers.
*
* Downloads images, files, audio, and video from Feishu using the
* Open API: GET /im/v1/messages/:message_id/resources/:file_key
*/
const BASE_URL = 'https://open.feishu.cn/open-apis';
/** Validate Feishu ID format to prevent path traversal in URL interpolation. */
const FEISHU_ID_RE = /^[a-zA-Z0-9_.:-]+$/;
export interface MediaFile {
buffer: Buffer;
mimeType: string;
}
/**
* Download a media file from Feishu.
*
* @param messageId - The message ID containing the resource
* @param fileKey - The file_key or image_key from the message content
* @param resourceType - 'image' or 'file'
* @param accessToken - A valid tenant access token
* @returns MediaFile with buffer and mimeType, or null on failure
*/
export async function downloadMedia(
messageId: string,
fileKey: string,
resourceType: 'image' | 'file',
accessToken: string,
): Promise<MediaFile | null> {
if (
!messageId ||
!fileKey ||
!accessToken ||
!FEISHU_ID_RE.test(messageId) ||
!FEISHU_ID_RE.test(fileKey)
) {
return null;
}
try {
const url = `${BASE_URL}/im/v1/messages/${messageId}/resources/${fileKey}?type=${resourceType}`;
const resp = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
signal: AbortSignal.timeout(30_000),
});
if (!resp.ok) {
const detail = await resp.text().catch(() => '');
process.stderr.write(
`[Feishu] downloadMedia failed: HTTP ${resp.status} ${detail}\n`,
);
return null;
}
const MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024; // 50 MB
const contentLength = resp.headers.get('content-length');
if (contentLength && parseInt(contentLength, 10) > MAX_DOWNLOAD_BYTES) {
process.stderr.write(
`[Feishu] downloadMedia rejected: size ${contentLength} exceeds ${MAX_DOWNLOAD_BYTES} byte limit\n`,
);
return null;
}
const mimeType =
resp.headers.get('content-type') || 'application/octet-stream';
// Stream-read with size enforcement (handles chunked transfer without Content-Length)
const reader = resp.body?.getReader();
if (!reader) {
return null;
}
const chunks: Buffer[] = [];
let totalSize = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalSize += value.byteLength;
if (totalSize > MAX_DOWNLOAD_BYTES) {
reader.cancel();
process.stderr.write(
`[Feishu] downloadMedia rejected: actual size exceeds ${MAX_DOWNLOAD_BYTES} byte limit\n`,
);
return null;
}
chunks.push(Buffer.from(value));
}
const buffer = Buffer.concat(chunks);
return { buffer, mimeType };
} catch (err) {
process.stderr.write(
`[Feishu] downloadMedia error: ${err instanceof Error ? err.message : err}\n`,
);
return null;
}
}

View File

@ -0,0 +1,10 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist", "src/**/*.test.ts"],
"references": [{ "path": "../base" }]
}

View File

@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['src/**/*.test.ts'],
globals: true,
},
});

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-plugin-example",
"version": "0.16.1",
"version": "0.17.0",
"private": true,
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-telegram",
"version": "0.16.1",
"version": "0.17.0",
"description": "Telegram channel adapter for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-weixin",
"version": "0.16.1",
"version": "0.17.0",
"description": "WeChat (Weixin) channel adapter for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/qwen-code",
"version": "0.16.1",
"version": "0.17.0",
"description": "Qwen Code",
"repository": {
"type": "git",
@ -37,7 +37,7 @@
"dist"
],
"config": {
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.16.1"
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.17.0"
},
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1",
@ -47,6 +47,7 @@
"@qwen-code/acp-bridge": "file:../acp-bridge",
"@qwen-code/channel-base": "file:../channels/base",
"@qwen-code/channel-dingtalk": "file:../channels/dingtalk",
"@qwen-code/channel-feishu": "file:../channels/feishu",
"@qwen-code/channel-telegram": "file:../channels/telegram",
"@qwen-code/channel-weixin": "file:../channels/weixin",
"@qwen-code/qwen-code-core": "file:../core",

View File

@ -145,7 +145,20 @@ vi.mock('./runtimeOutputDirContext.js', () => ({
),
}));
vi.mock('./authMethods.js', () => ({ buildAuthMethods: vi.fn() }));
vi.mock('./authMethods.js', () => {
const buildAuthMethods = vi.fn();
return {
buildAuthMethods,
pickAuthMethodsForAuthRequired: vi.fn((selectedType?: string) => {
const authMethods = buildAuthMethods();
if (!selectedType) return authMethods;
const matched = authMethods.filter(
(method: { id: string }) => method.id === selectedType,
);
return matched.length ? matched : authMethods;
}),
};
});
vi.mock('./service/filesystem.js', () => ({
AcpFileSystemService: vi.fn(),
}));
@ -195,6 +208,7 @@ import { loadSettings } from '../config/settings.js';
import { loadCliConfig } from '../config/config.js';
import { Session, buildAvailableCommandsSnapshot } from './session/Session.js';
import { SERVE_STATUS_EXT_METHODS } from '../serve/status.js';
import { buildAuthMethods } from './authMethods.js';
describe('runAcpAgent shutdown cleanup', () => {
let processExitSpy: MockInstance<typeof process.exit>;
@ -792,6 +806,64 @@ describe('QwenAgent MCP SSE/HTTP support', () => {
await agentPromise;
});
it('does not return discontinued qwen-oauth as the only ACP auth option', async () => {
vi.mocked(buildAuthMethods).mockReturnValue([
{
id: 'openai',
name: 'Use OpenAI API key',
description: 'Requires setting OPENAI_API_KEY',
},
]);
const innerConfig = makeInnerConfig();
vi.mocked(innerConfig.getModelsConfig).mockReturnValue({
getCurrentAuthType: vi.fn().mockReturnValue('qwen-oauth'),
} as unknown as ReturnType<Config['getModelsConfig']>);
vi.mocked(innerConfig.refreshAuth).mockRejectedValue(
new Error('qwen-oauth token expired'),
);
vi.mocked(loadSettings).mockReturnValue(makeSessionSettings());
vi.mocked(loadCliConfig).mockResolvedValue(
innerConfig as unknown as Config,
);
vi.mocked(Session).mockImplementation(
() =>
({
getId: vi.fn().mockReturnValue('test-session-id'),
getConfig: vi.fn().mockReturnValue(innerConfig),
sendAvailableCommandsUpdate: vi.fn().mockResolvedValue(undefined),
replayHistory: vi.fn().mockResolvedValue(undefined),
installRewriter: vi.fn(),
}) as unknown as InstanceType<typeof Session>,
);
const agentPromise = runAcpAgent(
mockConfig,
makeSessionSettings(),
mockArgv,
);
await vi.waitFor(() => expect(capturedAgentFactory).toBeDefined());
const agent = capturedAgentFactory!({
get closed() {
return mockConnectionState.promise;
},
}) as AgentLike;
await expect(
agent.newSession({ cwd: '/tmp', mcpServers: [] }),
).rejects.toMatchObject({
authMethods: [
expect.objectContaining({
id: 'openai',
}),
],
});
mockConnectionState.resolve();
await agentPromise;
});
function makeInnerConfig() {
return {
initialize: vi.fn().mockResolvedValue(undefined),

View File

@ -40,7 +40,6 @@ import type { Content } from '@google/genai';
import type {
Agent,
AuthenticateRequest,
AuthMethod,
CancelNotification,
ClientCapabilities,
InitializeRequest,
@ -69,7 +68,10 @@ import type {
SetSessionModeRequest,
SetSessionModeResponse,
} from '@agentclientprotocol/sdk';
import { buildAuthMethods } from './authMethods.js';
import {
buildAuthMethods,
pickAuthMethodsForAuthRequired,
} from './authMethods.js';
import { AcpFileSystemService } from './service/filesystem.js';
import { Readable, Writable } from 'node:stream';
import type { LoadedSettings } from '../config/settings.js';
@ -1936,7 +1938,7 @@ class QwenAgent implements Agent {
const selectedType = config.getModelsConfig().getCurrentAuthType();
if (!selectedType) {
throw RequestError.authRequired(
{ authMethods: this.pickAuthMethodsForAuthRequired() },
{ authMethods: pickAuthMethodsForAuthRequired() },
'Use Qwen Code CLI to authenticate first.',
);
}
@ -1947,51 +1949,13 @@ class QwenAgent implements Agent {
debugLogger.error(`Authentication failed: ${e}`);
throw RequestError.authRequired(
{
authMethods: this.pickAuthMethodsForAuthRequired(selectedType, e),
authMethods: pickAuthMethodsForAuthRequired(selectedType),
},
'Authentication failed: ' + (e as Error).message,
);
}
}
private pickAuthMethodsForAuthRequired(
selectedType?: AuthType | string,
error?: unknown,
): AuthMethod[] {
const authMethods = buildAuthMethods();
const errorMessage = this.extractErrorMessage(error);
if (
errorMessage?.includes('qwen-oauth') ||
errorMessage?.includes('Qwen OAuth')
) {
const qwenOAuthMethods = authMethods.filter(
(m) => m.id === AuthType.QWEN_OAUTH,
);
return qwenOAuthMethods.length ? qwenOAuthMethods : authMethods;
}
if (selectedType) {
const matched = authMethods.filter((m) => m.id === selectedType);
return matched.length ? matched : authMethods;
}
return authMethods;
}
private extractErrorMessage(error?: unknown): string | undefined {
if (error instanceof Error) return error.message;
if (
typeof error === 'object' &&
error != null &&
'message' in error &&
typeof error.message === 'string'
) {
return error.message;
}
if (typeof error === 'string') return error;
return undefined;
}
private setupFileSystem(config: Config): void {
if (!this.clientCapabilities?.fs) return;

View File

@ -125,7 +125,20 @@ vi.mock('./runtimeOutputDirContext.js', () => ({
),
}));
vi.mock('./authMethods.js', () => ({ buildAuthMethods: vi.fn() }));
vi.mock('./authMethods.js', () => {
const buildAuthMethods = vi.fn();
return {
buildAuthMethods,
pickAuthMethodsForAuthRequired: vi.fn((selectedType?: string) => {
const authMethods = buildAuthMethods();
if (!selectedType) return authMethods;
const matched = authMethods.filter(
(method: { id: string }) => method.id === selectedType,
);
return matched.length ? matched : authMethods;
}),
};
});
vi.mock('./service/filesystem.js', () => ({
AcpFileSystemService: vi.fn(),
}));

View File

@ -0,0 +1,30 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect, it } from 'vitest';
import { AuthType } from '@qwen-code/qwen-code-core';
import {
buildAuthMethods,
pickAuthMethodsForAuthRequired,
} from './authMethods.js';
describe('ACP auth methods', () => {
it('does not advertise discontinued Qwen OAuth', () => {
const authMethods = buildAuthMethods();
expect(authMethods.map((method) => method.id)).toEqual([
AuthType.USE_OPENAI,
]);
});
it('falls back to working methods for a stored discontinued Qwen OAuth selection', () => {
const authMethods = pickAuthMethodsForAuthRequired('qwen-oauth');
expect(authMethods.map((method) => method.id)).toEqual([
AuthType.USE_OPENAI,
]);
});
});

View File

@ -18,33 +18,17 @@ export function buildAuthMethods(): AuthMethod[] {
args: ['--auth-type=openai'],
},
},
{
id: AuthType.QWEN_OAUTH,
name: 'Qwen OAuth',
description: 'Qwen OAuth (free tier discontinued 2026-04-15)',
_meta: {
type: 'terminal',
args: ['--auth-type=qwen-oauth'],
},
},
];
}
export function filterAuthMethodsById(
authMethods: AuthMethod[],
authMethodId: string,
export function pickAuthMethodsForAuthRequired(
selectedType?: AuthType | string,
): AuthMethod[] {
return authMethods.filter((method) => method.id === authMethodId);
}
export function pickAuthMethodsForDetails(details?: string): AuthMethod[] {
const authMethods = buildAuthMethods();
if (!details) {
return authMethods;
}
if (details.includes('qwen-oauth') || details.includes('Qwen OAuth')) {
const narrowed = filterAuthMethodsById(authMethods, AuthType.QWEN_OAUTH);
return narrowed.length ? narrowed : authMethods;
if (selectedType) {
const matched = authMethods.filter((method) => method.id === selectedType);
return matched.length ? matched : authMethods;
}
return authMethods;
}

View File

@ -8,7 +8,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import { computeInitialTurnFromHistory, Session } from './Session.js';
import {
computeInitialTurnFromHistory,
fireSessionPermissionDeniedForAutoMode,
Session,
} from './Session.js';
import type { Content } from '@google/genai';
import type { ChatRecord, Config, GeminiChat } from '@qwen-code/qwen-code-core';
import { ApprovalMode, AuthType } from '@qwen-code/qwen-code-core';
@ -192,6 +196,8 @@ describe('Session', () => {
sendMessageStream: vi.fn(),
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue([]),
getHistoryShallow: vi.fn().mockReturnValue([]),
getLastModelMessageText: vi.fn().mockReturnValue(''),
setHistory: vi.fn(),
truncateHistory: vi.fn(),
stripThoughtsFromHistory: vi.fn(),
@ -325,6 +331,7 @@ describe('Session', () => {
{ role: 'model', parts: [{ text: 'second reply' }] },
];
vi.mocked(mockChat.getHistory).mockReturnValue(history);
vi.mocked(mockChat.getHistoryShallow).mockReturnValue(history);
const result = session.rewindToTurn(1);
@ -344,6 +351,7 @@ describe('Session', () => {
{ role: 'model', parts: [{ text: 'first reply' }] },
];
vi.mocked(mockChat.getHistory).mockReturnValue(history);
vi.mocked(mockChat.getHistoryShallow).mockReturnValue(history);
const result = session.rewindToTurn(0);
@ -352,9 +360,9 @@ describe('Session', () => {
});
it('rejects unreachable user turns', () => {
vi.mocked(mockChat.getHistory).mockReturnValue([
{ role: 'user', parts: [{ text: 'first' }] },
]);
const history: Content[] = [{ role: 'user', parts: [{ text: 'first' }] }];
vi.mocked(mockChat.getHistory).mockReturnValue(history);
vi.mocked(mockChat.getHistoryShallow).mockReturnValue(history);
expect(() => session.rewindToTurn(2)).toThrow(
'Cannot rewind to the requested turn',
@ -849,6 +857,8 @@ describe('Session', () => {
sendMessageStream: vi.fn().mockResolvedValue(createEmptyStream()),
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue([]),
getHistoryShallow: vi.fn().mockReturnValue([]),
getLastModelMessageText: vi.fn().mockReturnValue(''),
} as unknown as GeminiChat;
mockChat.sendMessageStream = vi
@ -908,6 +918,36 @@ describe('Session', () => {
});
});
it('labels the notice as screenshot-triggered when triggerReason is image_overflow', async () => {
mockGeminiClient.tryCompressChat.mockResolvedValueOnce({
originalTokenCount: 1200,
newTokenCount: 450,
compressionStatus: core.CompressionStatus.COMPRESSED,
triggerReason: 'image_overflow',
});
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());
await session.prompt({
sessionId: 'test-session-id',
prompt: [{ type: 'text', text: 'hello' }],
});
expect(mockClient.sessionUpdate).toHaveBeenCalledWith({
sessionId: 'test-session-id',
update: {
sessionUpdate: 'agent_message_chunk',
content: {
type: 'text',
text:
'IMPORTANT: This conversation accumulated enough tool screenshots to trigger compaction for qwen3-code-plus. ' +
'A compressed context will be sent for future messages (compressed from: 1200 to 450 tokens).',
},
},
});
});
it('continues sending when automatic compression fails', async () => {
mockGeminiClient.tryCompressChat.mockRejectedValueOnce(
new Error('compression rate limited'),
@ -1173,6 +1213,8 @@ describe('Session', () => {
sendMessageStream: vi.fn().mockResolvedValue(createEmptyStream()),
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue([]),
getHistoryShallow: vi.fn().mockReturnValue([]),
getLastModelMessageText: vi.fn().mockReturnValue(''),
} as unknown as GeminiChat;
mockConfig.getSessionTokenLimit = vi.fn().mockReturnValue(100);
mockGeminiClient.tryCompressChat
@ -1489,6 +1531,9 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValueOnce(createEmptyStream())
@ -1550,6 +1595,9 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValueOnce(createEmptyStream())
@ -1621,6 +1669,9 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());
@ -2170,6 +2221,129 @@ describe('Session', () => {
});
describe('hooks', () => {
describe('PermissionDenied hook', () => {
it('fires PermissionDenied hooks for AUTO classifier blocks', async () => {
const hookSystem = {
firePermissionDeniedEvent: vi.fn().mockResolvedValue(undefined),
};
mockConfig.getHookSystem = vi.fn().mockReturnValue(hookSystem);
mockConfig.getDisableAllHooks = vi.fn().mockReturnValue(false);
const signal = new AbortController().signal;
await fireSessionPermissionDeniedForAutoMode(
mockConfig,
{
via: 'classifier',
shouldBlock: true,
reason: 'dangerous shell command',
unavailable: false,
stage: 'fast',
durationMs: 20,
},
{ kind: 'blocked', errorMessage: 'blocked' },
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
signal,
);
expect(hookSystem.firePermissionDeniedEvent).toHaveBeenCalledWith(
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
'classifier_blocked',
signal,
);
});
it('forwards classifier_unavailable reasons to PermissionDenied hooks', async () => {
const hookSystem = {
firePermissionDeniedEvent: vi.fn().mockResolvedValue(undefined),
};
mockConfig.getHookSystem = vi.fn().mockReturnValue(hookSystem);
mockConfig.getDisableAllHooks = vi.fn().mockReturnValue(false);
await fireSessionPermissionDeniedForAutoMode(
mockConfig,
{
via: 'classifier',
shouldBlock: true,
reason: 'classifier timeout',
unavailable: true,
stage: 'fast',
durationMs: 3000,
},
{ kind: 'blocked', errorMessage: 'blocked' },
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
new AbortController().signal,
);
expect(hookSystem.firePermissionDeniedEvent).toHaveBeenCalledWith(
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
'classifier_unavailable',
expect.any(AbortSignal),
);
});
it('skips PermissionDenied hooks when hooks are disabled', async () => {
const hookSystem = {
firePermissionDeniedEvent: vi.fn().mockResolvedValue(undefined),
};
mockConfig.getHookSystem = vi.fn().mockReturnValue(hookSystem);
mockConfig.getDisableAllHooks = vi.fn().mockReturnValue(true);
await fireSessionPermissionDeniedForAutoMode(
mockConfig,
{
via: 'classifier',
shouldBlock: true,
reason: 'dangerous shell command',
unavailable: false,
stage: 'fast',
durationMs: 20,
},
{ kind: 'blocked', errorMessage: 'blocked' },
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
new AbortController().signal,
);
expect(hookSystem.firePermissionDeniedEvent).not.toHaveBeenCalled();
});
it('skips PermissionDenied hooks when AUTO outcome is not blocked', async () => {
const hookSystem = {
firePermissionDeniedEvent: vi.fn().mockResolvedValue(undefined),
};
mockConfig.getHookSystem = vi.fn().mockReturnValue(hookSystem);
mockConfig.getDisableAllHooks = vi.fn().mockReturnValue(false);
await fireSessionPermissionDeniedForAutoMode(
mockConfig,
{
via: 'classifier',
shouldBlock: true,
reason: 'dangerous shell command',
unavailable: false,
stage: 'fast',
durationMs: 20,
},
{ kind: 'fallback' },
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
new AbortController().signal,
);
expect(hookSystem.firePermissionDeniedEvent).not.toHaveBeenCalled();
});
});
describe('UserPromptSubmit hook', () => {
it('fires UserPromptSubmit hook before sending prompt', async () => {
const messageBus = {
@ -2248,6 +2422,9 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi.fn().mockResolvedValue(
createStreamWithChunks([
@ -2301,6 +2478,9 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());
@ -2346,6 +2526,9 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());

View File

@ -23,6 +23,8 @@ import type {
MessageBus,
StreamEvent,
ChatCompressionInfo,
AutoModeDecision,
AutoModeOutcome,
} from '@qwen-code/qwen-code-core';
import {
AuthType,
@ -62,11 +64,13 @@ import {
formatStopHookBlockingCapWarning,
applyAutoModeDecision,
evaluateAutoMode,
getAutoModePermissionDeniedReason,
isApproveOutcome,
MAX_TRANSCRIPT_MESSAGES,
recordAllow,
recordFallbackApprove,
shouldFallback,
shouldFirePermissionDeniedForAutoMode,
shouldRunAutoModeForCall,
} from '@qwen-code/qwen-code-core';
import { getCommandSubcommandNames } from '../../services/commandMetadata.js';
@ -159,6 +163,31 @@ export function computeInitialTurnFromHistory(
return maxPromptTurn > 0 ? maxPromptTurn : userMessageCount;
}
export async function fireSessionPermissionDeniedForAutoMode(
config: Config,
decision: AutoModeDecision,
outcome: AutoModeOutcome,
toolName: string,
toolParams: Record<string, unknown>,
callId: string,
signal?: AbortSignal,
): Promise<void> {
if (
!config.getDisableAllHooks?.() &&
shouldFirePermissionDeniedForAutoMode(decision, outcome)
) {
await config
.getHookSystem?.()
?.firePermissionDeniedEvent(
toolName,
toolParams,
callId,
getAutoModePermissionDeniedReason(decision),
signal,
);
}
}
function getRecordPromptIds(record: ChatRecord): string[] {
const promptIds: string[] = [];
const recordPromptId = (record as { promptId?: unknown }).promptId;
@ -373,7 +402,7 @@ export class Session implements SessionContext {
}
const chat = this.config.getGeminiClient()!.getChat();
const apiHistory = chat.getHistory();
const apiHistory = chat.getHistoryShallow();
const apiTruncateIndex = this.#computeApiTruncationIndexForUserTurn(
apiHistory,
targetTurnIndex,
@ -866,16 +895,10 @@ export class Session implements SessionContext {
return { stopReason: 'end_turn' };
}
// Get response text from the chat history
const history = this.#getCurrentChat().getHistory();
const lastModelMessage = history
.filter((msg: Content) => msg.role === 'model')
.pop();
// Extract last model text without cloning the full history.
const responseText =
lastModelMessage?.parts
?.filter((p: Part): p is { text: string } & Part => 'text' in p)
.map((p: { text: string }) => p.text)
.join('') || '[no response text]';
this.#getCurrentChat().getLastModelMessageText?.() ||
'[no response text]';
const response = await messageBus.request<
HookExecutionRequest,
@ -1120,8 +1143,12 @@ export class Session implements SessionContext {
compressionInfo = compressed;
this.#recordCompressionTokenCount(compressed);
if (compressed.compressionStatus === CompressionStatus.COMPRESSED) {
const reasonClause =
compressed.triggerReason === 'image_overflow'
? `accumulated enough tool screenshots to trigger compaction for ${this.config.getModel()}`
: `approached the input token limit for ${this.config.getModel()}`;
compressionDiagnostic =
`IMPORTANT: This conversation approached the input token limit for ${this.config.getModel()}. ` +
`IMPORTANT: This conversation ${reasonClause}. ` +
`A compressed context will be sent for future messages (compressed from: ` +
`${compressed.originalTokenCount ?? 'unknown'} to ` +
`${compressed.newTokenCount ?? 'unknown'} tokens).`;
@ -1980,6 +2007,15 @@ export class Session implements SessionContext {
this.config,
denialState,
);
await fireSessionPermissionDeniedForAutoMode(
this.config,
decision,
outcome,
fc.name,
toolParams,
callId,
abortSignal,
);
switch (outcome.kind) {
case 'approved':
autoModeAllowed = true;

View File

@ -6,13 +6,14 @@ let builtinsPromise: Promise<void> | null = null;
function ensureBuiltins(): Promise<void> {
if (!builtinsPromise) {
builtinsPromise = (async () => {
const [telegram, weixin, dingtalk] = await Promise.all([
const [telegram, weixin, dingtalk, feishu] = await Promise.all([
import('@qwen-code/channel-telegram'),
import('@qwen-code/channel-weixin'),
import('@qwen-code/channel-dingtalk'),
import('@qwen-code/channel-feishu'),
]);
for (const mod of [telegram, weixin, dingtalk]) {
for (const mod of [telegram, weixin, dingtalk, feishu]) {
registry.set(mod.plugin.channelType, mod.plugin);
}
})();

View File

@ -12,7 +12,12 @@ import type { Argv, CommandModule } from 'yargs';
// handler below so it only loads when the user actually runs `qwen serve`.
import { writeStderrLine } from '../utils/stdioHelpers.js';
import { DEFAULT_RING_SIZE } from '../serve/eventBus.js';
import { MCP_BUDGET_WARN_FRACTION } from '@qwen-code/qwen-code-core';
import {
ApprovalMode,
MCP_BUDGET_WARN_FRACTION,
} from '@qwen-code/qwen-code-core';
import { loadSettings } from '../config/settings.js';
import { HEADLESS_YOLO_NO_SANDBOX_WARNING } from '../utils/headlessSafetyWarnings.js';
/**
* Pause the current async function indefinitely. Used after the daemon
@ -203,6 +208,37 @@ export const serveCommand: CommandModule<unknown, ServeArgs> = {
);
}
// Emit the headless-YOLO safety warning at daemon startup if
// settings.json statically configures yolo + no sandbox. We can't
// use `getHeadlessYoloSafetyWarning(config)` here because the daemon
// hasn't constructed a `Config` yet — sessions get their own — so
// we re-derive the predicate from the same settings.json the
// sessions will load. Per-session override (the ACP client flipping
// approval mode mid-session) is out of scope here; this warns about
// a deployment that's wide-open at boot. Suppress with
// QWEN_CODE_SUPPRESS_YOLO_WARNING=1.
try {
const loaded = loadSettings(argv.workspace ?? process.cwd());
const merged = loaded.merged;
const approvalMode = merged.tools?.approvalMode;
const sandbox = merged.tools?.sandbox;
const sandboxEnv = process.env['SANDBOX'];
const suppress = process.env['QWEN_CODE_SUPPRESS_YOLO_WARNING'];
const suppressed = suppress === '1' || suppress === 'true';
if (
approvalMode === ApprovalMode.YOLO &&
!sandbox &&
!sandboxEnv &&
!suppressed
) {
writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING);
}
} catch {
// Settings load can fail (corrupt JSON, etc.); don't block
// daemon startup just to emit a warning — the existing settings
// path will report the same error to the user via Session.
}
// Lazy-load the serve module so non-serve invocations don't pay for
// express + body-parser + qs in their startup path.
const { runQwenServe } = await import('../serve/index.js');

View File

@ -165,7 +165,7 @@ export function validateAuthMethod(
authMethod: string,
config?: Config,
): string | null {
const settings = loadSettings();
const settings = loadSettings(process.cwd(), false);
loadEnvironment(settings.merged);
if (authMethod === AuthType.USE_OPENAI) {

View File

@ -2354,6 +2354,16 @@ describe('loadCliConfig with includeDirectories', () => {
]);
});
it('should default managed-memory toggles to enabled when not in bare mode', async () => {
process.argv = ['node', 'script.js'];
const argv = await parseArguments();
const config = await loadCliConfig({}, argv, undefined, []);
expect(config.getManagedAutoMemoryEnabled()).toBe(true);
expect(config.getManagedAutoDreamEnabled()).toBe(true);
expect(config.getAutoSkillEnabled()).toBe(true);
});
it('should force minimal startup behavior in bare mode', async () => {
process.argv = ['node', 'script.js', '--bare'];
const argv = await parseArguments();
@ -2393,6 +2403,8 @@ describe('loadCliConfig with includeDirectories', () => {
]);
expect(config.getDisableAllHooks()).toBe(true);
expect(config.getManagedAutoMemoryEnabled()).toBe(false);
expect(config.getManagedAutoDreamEnabled()).toBe(false);
expect(config.getAutoSkillEnabled()).toBe(false);
expect(config.getToolDiscoveryCommand()).toBeUndefined();
expect(config.getToolCallCommand()).toBeUndefined();
expect(config.getMcpServers()).toEqual({});

View File

@ -75,6 +75,11 @@ export function isValidSessionId(value: string): boolean {
import { isWorkspaceTrusted } from './trustedFolders.js';
import { writeStderrLine } from '../utils/stdioHelpers.js';
import {
parseDurationSeconds,
validateMaxToolCalls,
validateMaxWallTimeSetting,
} from '../utils/runBudget.js';
const debugLogger = createDebugLogger('CONFIG');
@ -170,7 +175,20 @@ export interface CliArgs {
forkSession?: boolean | undefined;
/** Internal: preserve the outer session ID when relaunching in a sandbox */
sandboxSessionId?: string | undefined;
/**
* Start the session inside a git worktree. Accepted forms:
* - bare `--worktree` (empty string from yargs) → auto-generated slug
* - `--worktree foo` / `--worktree=foo` → explicit slug
* - `--worktree=#123` / `--worktree https://github.com/o/r/pull/123` → PR ref
*
* Consumed by `setupStartupWorktree()` before `loadCliConfig()`. When set,
* the CLI chdirs into `<repoRoot>/.qwen/worktrees/<slug>/` and the entire
* session runs inside that worktree.
*/
worktree?: string | undefined;
maxSessionTurns: number | undefined;
maxWallTime: string | undefined;
maxToolCalls: number | undefined;
coreTools: string[] | undefined;
excludeTools: string[] | undefined;
disabledSlashCommands: string[] | undefined;
@ -824,10 +842,28 @@ export async function parseArguments(): Promise<CliArgs> {
type: 'string',
hidden: true,
})
.option('worktree', {
type: 'string',
description:
'Start the session inside a git worktree at <repoRoot>/.qwen/worktrees/<slug>/. ' +
'Pass a slug (`--worktree my-feature`), a PR reference (`--worktree=#123` or a full ' +
'GitHub pull-request URL), or use bare `--worktree` to auto-generate a slug. ' +
'On exit, the WorktreeExitDialog prompts to keep or remove the worktree.',
})
.option('max-session-turns', {
type: 'number',
description: 'Maximum number of session turns',
})
.option('max-wall-time', {
type: 'string',
description:
'Run-level wall-clock budget for headless / unattended runs. Accepts seconds (e.g. `90`), or a duration string with unit (e.g. `30s`, `5m`, `1h`, `1.5h`). Minimum 1s — sub-second values (`500ms`, `0.5`) are rejected as typos; max ~24 days. Aborts the run with exit code 55 when exceeded.',
})
.option('max-tool-calls', {
type: 'number',
description:
'Maximum cumulative tool calls executed during the run (success or failure; `structured_output` under --json-schema is exempt). Aborts with exit code 55 when exceeded. -1 / unset means no limit; 0 means "no tool calls allowed" (first call aborts). Capped at 1,000,000 to catch typos.',
})
.option('core-tools', {
type: 'array',
string: true,
@ -1116,6 +1152,65 @@ export async function loadHierarchicalGeminiMemory(
);
}
/**
* Resolves the wall-clock budget for a run. Returns seconds (`-1` =
* unlimited). Order of precedence: `--max-wall-time` flag, then
* `model.maxWallTimeSeconds` from settings, else unlimited.
*
* The CLI flag is a duration string (`30s` / `5m` / `1h` / `90`); the
* settings entry is a plain number of seconds (parity with
* `model.maxSessionTurns`). Both layers reject `0` and out-of-range
* values up front — a typo in a CI guardrail should fail loud at startup,
* not silently disable the budget.
*/
function resolveMaxWallTimeSeconds(argv: CliArgs, settings: Settings): number {
if (argv.maxWallTime !== undefined && argv.maxWallTime !== null) {
try {
return parseDurationSeconds(String(argv.maxWallTime));
} catch (err) {
throw new Error(`--max-wall-time: ${(err as Error).message}`);
}
}
const fromSettings = settings.model?.maxWallTimeSeconds;
if (typeof fromSettings === 'number') {
try {
return validateMaxWallTimeSetting(fromSettings);
} catch (err) {
throw new Error(`settings.json: ${(err as Error).message}`);
}
}
return -1;
}
/**
* Resolves the tool-call budget for a run. Returns the validated count
* (`-1` = unlimited). Order of precedence: `--max-tool-calls` flag, then
* `model.maxToolCalls` from settings, else unlimited.
*
* Symmetric with `resolveMaxWallTimeSeconds`: yargs accepts `NaN` from
* non-numeric flag values, and the enforcer's `>= 0` gate would silently
* disable the budget for `NaN` / negatives. Validate up front so a typo
* in a CI guardrail fails loudly.
*/
function resolveMaxToolCalls(argv: CliArgs, settings: Settings): number {
if (argv.maxToolCalls !== undefined && argv.maxToolCalls !== null) {
try {
return validateMaxToolCalls(argv.maxToolCalls);
} catch (err) {
throw new Error(`--max-tool-calls: ${(err as Error).message}`);
}
}
const fromSettings = settings.model?.maxToolCalls;
if (typeof fromSettings === 'number') {
try {
return validateMaxToolCalls(fromSettings);
} catch (err) {
throw new Error(`settings.json: ${(err as Error).message}`);
}
}
return -1;
}
export function isDebugMode(argv: CliArgs): boolean {
return (
argv.debug ||
@ -1710,6 +1805,7 @@ export async function loadCliConfig(
screenReader,
},
telemetry: telemetrySettings,
outboundCorrelation: settings.outboundCorrelation,
usageStatisticsEnabled: settings.privacy?.usageStatisticsEnabled ?? true,
clearContextOnIdle: settings.context?.clearContextOnIdle,
fileFiltering: settings.context?.fileFiltering,
@ -1731,8 +1827,11 @@ export async function loadCliConfig(
sessionTokenLimit: settings.model?.sessionTokenLimit ?? -1,
maxSessionTurns:
argv.maxSessionTurns ?? settings.model?.maxSessionTurns ?? -1,
maxWallTimeSeconds: resolveMaxWallTimeSeconds(argv, settings),
maxToolCalls: resolveMaxToolCalls(argv, settings),
experimentalZedIntegration: argv.acp || argv.experimentalAcp || false,
cronEnabled: settings.experimental?.cron ?? false,
computerUseEnabled: settings.tools?.computerUse?.enabled ?? true,
emitToolUseSummaries: settings.experimental?.emitToolUseSummaries ?? true,
listExtensions: argv.listExtensions || false,
overrideExtensions: overrideExtensions || argv.extensions,
@ -1771,10 +1870,12 @@ export async function loadCliConfig(
enableManagedAutoMemory: bareMode
? false
: (settings.memory?.enableManagedAutoMemory ?? true),
enableManagedAutoDream: settings.memory?.enableManagedAutoDream ?? false,
enableManagedAutoDream: bareMode
? false
: (settings.memory?.enableManagedAutoDream ?? true),
enableAutoSkill: bareMode
? false
: (settings.memory?.enableAutoSkill ?? false),
: (settings.memory?.enableAutoSkill ?? true),
fastModel: settings.fastModel || undefined,
// Use separated hooks if provided, otherwise fall back to merged hooks
userHooks: bareMode
@ -1814,6 +1915,11 @@ export async function loadCliConfig(
: undefined,
}
: undefined,
worktree: settings.worktree
? {
symlinkDirectories: settings.worktree.symlinkDirectories,
}
: undefined,
};
const config = new Config(configParams);

View File

@ -56,6 +56,8 @@ import {
SETTINGS_VERSION,
SETTINGS_VERSION_KEY,
resetHomeEnvBootstrapForTesting,
ENV_CORRUPTED_PATH,
ENV_WAS_RECOVERED,
} from './settings.js';
import { needsMigration } from './migration/index.js';
import { QWEN_DIR } from '@qwen-code/qwen-code-core';
@ -108,6 +110,7 @@ vi.mock('node:fs', async (importOriginal) => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
renameSync: vi.fn(),
copyFileSync: vi.fn(),
mkdirSync: vi.fn(),
statSync: vi.fn(() => ({ isDirectory: () => false, isFile: () => true })),
realpathSync: (p: string) => p,
@ -126,6 +129,7 @@ vi.mock('fs', async (importOriginal) => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
renameSync: vi.fn(),
copyFileSync: vi.fn(),
mkdirSync: vi.fn(),
statSync: vi.fn(() => ({ isDirectory: () => false, isFile: () => true })),
realpathSync: (p: string) => p,
@ -1874,19 +1878,18 @@ describe('Settings Loading and Merging', () => {
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result).toBeDefined();
// Verify the corrupted file was renamed with timestamp suffix
const renameCalls = (fs.renameSync as Mock).mock.calls;
const corruptedRename = renameCalls.find(
// Verify the corrupted file was copied to .corrupted
const copyCalls = (fs.copyFileSync as Mock).mock.calls;
const corruptedCopy = copyCalls.find(
(call: unknown[]) =>
call[0] === USER_SETTINGS_PATH &&
String(call[1]).includes('.corrupted.'),
String(call[1]).includes('.corrupted'),
);
expect(corruptedRename).toBeDefined();
expect(corruptedCopy).toBeDefined();
// Verify migrationWarnings contains recovery message
const warnings = getSettingsWarnings(result);
expect(warnings.some((w) => w.includes('invalid JSON'))).toBe(true);
expect(warnings.some((w) => w.includes('renamed'))).toBe(true);
// Corrupted dialog is driven by corruptedPath, not by migrationWarnings
expect(result.corruptedPath).toBe(`${USER_SETTINGS_PATH}.corrupted`);
expect(result.wasRecovered).toBe(false);
vi.restoreAllMocks();
});
@ -1919,11 +1922,8 @@ describe('Settings Loading and Merging', () => {
);
expect(restoreWrite).toBeDefined();
// Verify migrationWarnings informs user about recovery
const warnings = getSettingsWarnings(result);
expect(warnings.some((w) => w.includes('recovered from backup'))).toBe(
true,
);
// Recovery is communicated via wasRecovered flag, not migrationWarnings
expect(result.wasRecovered).toBe(true);
vi.restoreAllMocks();
});
@ -1954,20 +1954,27 @@ describe('Settings Loading and Merging', () => {
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result).toBeDefined();
// Verify the corrupted file was renamed
const renameCalls = (fs.renameSync as Mock).mock.calls;
expect(result.corruptedPath).toBe(`${USER_SETTINGS_PATH}.corrupted`);
expect(result.wasRecovered).toBe(false);
const resetWrites = (fs.writeFileSync as Mock).mock.calls.filter(
(call: unknown[]) => call[0] === USER_SETTINGS_PATH && call[1] === '{}',
);
expect(resetWrites.length).toBeGreaterThan(0);
// Verify the corrupted file was copied to .corrupted
const copyCalls = (fs.copyFileSync as Mock).mock.calls;
expect(
renameCalls.some(
copyCalls.some(
(call: unknown[]) =>
call[0] === USER_SETTINGS_PATH &&
String(call[1]).includes('.corrupted.'),
String(call[1]).includes('.corrupted'),
),
).toBe(true);
vi.restoreAllMocks();
});
it('should start with empty settings when rename of corrupted file fails', () => {
it('should start with empty settings when copy of corrupted file fails', () => {
const invalidJsonContent = 'invalid json';
(mockFsExistsSync as Mock).mockImplementation((p: fs.PathLike) => {
@ -1983,8 +1990,8 @@ describe('Settings Loading and Merging', () => {
},
);
// Simulate rename failure (e.g., permission denied)
(fs.renameSync as Mock).mockImplementation(() => {
// Simulate copy failure (e.g., permission denied)
(fs.copyFileSync as Mock).mockImplementation(() => {
throw new Error('EACCES: permission denied');
});
@ -1992,15 +1999,136 @@ describe('Settings Loading and Merging', () => {
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result).toBeDefined();
// Verify the warning message does NOT say "renamed" since rename failed,
// but instead tells user to fix the file manually.
// Corruption warning no longer goes through migrationWarnings —
// copy failed so corruptedPath is undefined too
const warnings = getSettingsWarnings(result);
expect(warnings.some((w) => w.includes('fix the JSON'))).toBe(true);
expect(warnings.some((w) => w.includes('renamed to'))).toBe(false);
expect(warnings.some((w) => w.includes('invalid JSON'))).toBe(false);
expect(result.corruptedPath).toBeUndefined();
vi.restoreAllMocks();
});
it('should return warnings suitable for early stderr emission when settings.json has invalid JSON', () => {
const invalidJsonContent = '{ broken json!!!';
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH) return invalidJsonContent;
return '{}';
},
);
(fs.renameSync as Mock).mockImplementation(() => {});
const result = loadSettings(MOCK_WORKSPACE_DIR);
const warnings = getSettingsWarnings(result);
// Corruption warning no longer goes through migrationWarnings —
// it is emitted via settings.corruptedPath check in gemini.tsx
// early stderr path instead. Verify corruptedPath is set.
expect(result.corruptedPath).toBeDefined();
expect(warnings.some((w) => w.includes('invalid JSON'))).toBe(false);
vi.restoreAllMocks();
});
describe('corruption env var propagation', () => {
afterEach(() => {
delete process.env[ENV_CORRUPTED_PATH];
delete process.env[ENV_WAS_RECOVERED];
});
it('should propagate corruptedPath/wasRecovered from env vars', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '1';
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result.corruptedPath).toBe(`${USER_SETTINGS_PATH}.corrupted`);
expect(result.wasRecovered).toBe(true);
});
it('should delete env vars after reading so subsequent calls do not re-trigger', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '0';
loadSettings(MOCK_WORKSPACE_DIR);
expect(process.env[ENV_CORRUPTED_PATH]).toBeUndefined();
expect(process.env[ENV_WAS_RECOVERED]).toBeUndefined();
});
it('should only consume env vars for SettingScope.User', () => {
(mockFsExistsSync as Mock).mockImplementation((p: fs.PathLike) => {
const s = p.toString();
return s === USER_SETTINGS_PATH || s === MOCK_WORKSPACE_SETTINGS_PATH;
});
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '1';
const result = loadSettings(MOCK_WORKSPACE_DIR);
// env vars consumed in User scope — scope guard exercised
expect(process.env[ENV_CORRUPTED_PATH]).toBeUndefined();
expect(process.env[ENV_WAS_RECOVERED]).toBeUndefined();
expect(result.corruptedPath).toBeDefined();
});
it('should map wasRecovered="0" to false', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '0';
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result.wasRecovered).toBe(false);
});
it('should not consume env vars when consumeCorruptionEnvVars=false', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '1';
loadSettings(MOCK_WORKSPACE_DIR, false);
// env vars should remain untouched so child processes can still read them
expect(process.env[ENV_CORRUPTED_PATH]).toBe(
`${USER_SETTINGS_PATH}.corrupted`,
);
expect(process.env[ENV_WAS_RECOVERED]).toBe('1');
});
it('should reject mismatched ENV_CORRUPTED_PATH', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = '/some/other/path.corrupted';
process.env[ENV_WAS_RECOVERED] = '1';
const result = loadSettings(MOCK_WORKSPACE_DIR);
// Guard rejected — corruptedPath not propagated
expect(result.corruptedPath).toBeUndefined();
// Env vars not consumed because guard failed
expect(process.env[ENV_CORRUPTED_PATH]).toBe(
'/some/other/path.corrupted',
);
});
});
it('should resolve environment variables in user settings', () => {
process.env['TEST_API_KEY'] = 'user_api_key_from_env';
const userSettingsContent: TestSettings = {
@ -2147,6 +2275,256 @@ describe('Settings Loading and Merging', () => {
delete process.env['SHARED_VAR'];
});
it('should resolve ${VAR} in settings from home-level .env file (#4466)', () => {
const homeQwenEnvPath = path.join(
path.dirname(USER_SETTINGS_PATH),
'.env',
);
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${MY_SECRET_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH || p === homeQwenEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === homeQwenEnvPath)
return 'MY_SECRET_TOKEN=secret_from_dotenv';
return '{}';
},
);
delete process.env['MY_SECRET_TOKEN'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer secret_from_dotenv',
);
delete process.env['MY_SECRET_TOKEN'];
});
it('should not override process.env values with home .env file (#4466)', () => {
const homeQwenEnvPath = path.join(
path.dirname(USER_SETTINGS_PATH),
'.env',
);
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${MY_SECRET_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH || p === homeQwenEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === homeQwenEnvPath) return 'MY_SECRET_TOKEN=from_dotenv';
return '{}';
},
);
process.env['MY_SECRET_TOKEN'] = 'from_process_env';
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer from_process_env',
);
delete process.env['MY_SECRET_TOKEN'];
});
it('should not search dirname(qwenDir)/.env when QWEN_HOME is set (#4466)', () => {
const customHome = '/custom/qwen/home';
process.env['QWEN_HOME'] = customHome;
const customSettingsPath = path.join(customHome, 'settings.json');
const dirnameEnvPath = path.join(path.dirname(customHome), '.env');
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${MY_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === customSettingsPath || p === dirnameEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === customSettingsPath)
return JSON.stringify(userSettingsContent);
if (p === dirnameEnvPath) return 'MY_TOKEN=should_not_be_found';
return '{}';
},
);
delete process.env['MY_TOKEN'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer ${MY_TOKEN}',
);
delete process.env['MY_TOKEN'];
delete process.env['QWEN_HOME'];
});
it('should resolve ${VAR} from ~/.env when QWEN_HOME is not set (#4466)', () => {
const homeEnvPath = path.join(
path.dirname(path.dirname(USER_SETTINGS_PATH)),
'.env',
);
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${HOME_ENV_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH || p === homeEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === homeEnvPath) return 'HOME_ENV_TOKEN=from_home_env';
return '{}';
},
);
delete process.env['HOME_ENV_TOKEN'];
delete process.env['QWEN_HOME'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer from_home_env',
);
delete process.env['HOME_ENV_TOKEN'];
});
it('should prefer ~/.qwen/.env over ~/.env for the same key (first-write-wins) (#4466)', () => {
const qwenEnvPath = path.join(path.dirname(USER_SETTINGS_PATH), '.env');
const homeEnvPath = path.join(
path.dirname(path.dirname(USER_SETTINGS_PATH)),
'.env',
);
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${PRECEDENCE_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) =>
p === USER_SETTINGS_PATH || p === qwenEnvPath || p === homeEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === qwenEnvPath) return 'PRECEDENCE_TOKEN=from_qwen_dir';
if (p === homeEnvPath) return 'PRECEDENCE_TOKEN=from_home_dir';
return '{}';
},
);
delete process.env['PRECEDENCE_TOKEN'];
delete process.env['QWEN_HOME'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer from_qwen_dir',
);
delete process.env['PRECEDENCE_TOKEN'];
});
it('should succeed with unresolved placeholder when .env read throws (#4466)', () => {
const qwenEnvPath = path.join(path.dirname(USER_SETTINGS_PATH), '.env');
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${ERROR_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH || p === qwenEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === qwenEnvPath) throw new Error('EACCES: permission denied');
return '{}';
},
);
delete process.env['ERROR_TOKEN'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer ${ERROR_TOKEN}',
);
delete process.env['ERROR_TOKEN'];
});
it('should correctly merge dnsResolutionOrder with workspace taking precedence', () => {
(mockFsExistsSync as Mock).mockReturnValue(true);
const userSettingsContent = {
@ -2731,6 +3109,122 @@ describe('Settings Loading and Merging', () => {
externallyModifiedUserSettingsContent.modelProviders.openai,
);
});
it('persists removed MCP servers when replacing the top-level mcpServers object', () => {
(mockFsExistsSync as Mock).mockReturnValue(true);
const userSettingsContent = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
ui: {
theme: 'dark',
},
mcpServers: {
keep: {
command: 'node',
},
remove: {
command: 'python',
},
},
};
let currentUserSettingsContent = JSON.stringify(userSettingsContent);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH) {
return currentUserSettingsContent;
}
return '{}';
},
);
const settings = loadSettings(MOCK_WORKSPACE_DIR);
currentUserSettingsContent = JSON.stringify(userSettingsContent);
settings.setValue(SettingScope.User, 'mcpServers', {
keep: {
command: 'node',
},
});
const writeCall = (fs.writeFileSync as Mock).mock.calls.at(-1);
expect(writeCall).toBeDefined();
const writtenContent = JSON.parse(String(writeCall?.[1]));
expect(writtenContent.ui).toEqual({ theme: 'dark' });
expect(writtenContent.mcpServers).toEqual({
keep: {
command: 'node',
},
});
});
it('preserves sibling keys for non-MCP top-level object updates', () => {
(mockFsExistsSync as Mock).mockReturnValue(true);
const userSettingsContent = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
tools: {
approvalMode: 'default',
disabled: ['shell'],
},
};
let currentUserSettingsContent = JSON.stringify(userSettingsContent);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH) {
return currentUserSettingsContent;
}
return '{}';
},
);
const settings = loadSettings(MOCK_WORKSPACE_DIR);
currentUserSettingsContent = JSON.stringify(userSettingsContent);
settings.setValue(SettingScope.User, 'tools', {
disabled: ['read-file'],
});
const writeCall = (fs.writeFileSync as Mock).mock.calls.at(-1);
expect(writeCall).toBeDefined();
const writtenContent = JSON.parse(String(writeCall?.[1]));
expect(writtenContent.tools).toEqual({
approvalMode: 'default',
disabled: ['read-file'],
});
});
it('logs when setValue persistence is refused', () => {
(mockFsExistsSync as Mock).mockReturnValue(true);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH) {
return JSON.stringify({
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
}
return '{}';
},
);
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mockFn =
commentJsonUtils.updateSettingsFilePreservingFormat as Mock;
mockFn.mockReturnValueOnce(false);
settings.setValue(SettingScope.User, 'mcpServers', {});
expect(mockDebugLogger.error).toHaveBeenCalledWith(
expect.stringContaining(
'saveSettings: updateSettingsFilePreservingFormat returned false',
),
);
});
});
describe('loadEnvironment', () => {

View File

@ -73,12 +73,22 @@ export function getUserSettingsDir(): string {
}
export const DEFAULT_EXCLUDED_ENV_VARS = ['DEBUG', 'DEBUG_MODE'];
// Env var names used for inter-process communication of corruption state.
// Defined as constants to avoid duplicated string literals.
export const ENV_CORRUPTED_PATH = 'QWEN_CODE_SETTINGS_CORRUPTED_PATH';
export const ENV_WAS_RECOVERED = 'QWEN_CODE_SETTINGS_WAS_RECOVERED';
// QWEN_HOME and QWEN_RUNTIME_DIR control where global state (settings, OAuth
// credentials, installation IDs, etc.) is written. A project `.env` must never
// redirect these — that would split global state between the real home and a
// project-controlled directory. Always excluded from project .env files,
// regardless of user-configurable `advanced.excludedEnvVars`.
const PROJECT_ENV_HARDCODED_EXCLUSIONS = ['QWEN_HOME', 'QWEN_RUNTIME_DIR'];
const PROJECT_ENV_HARDCODED_EXCLUSIONS = [
'QWEN_HOME',
'QWEN_RUNTIME_DIR',
ENV_CORRUPTED_PATH,
ENV_WAS_RECOVERED,
];
// Settings version to track migration state
export const SETTINGS_VERSION = 4;
@ -396,6 +406,8 @@ export class LoadedSettings {
isTrusted: boolean,
migratedInMemorScopes: Set<SettingScope>,
migrationWarnings: string[] = [],
corruptedPath: string | undefined = undefined,
wasRecovered: boolean = false,
) {
this.system = system;
this.systemDefaults = systemDefaults;
@ -404,6 +416,8 @@ export class LoadedSettings {
this.isTrusted = isTrusted;
this.migratedInMemorScopes = migratedInMemorScopes;
this.migrationWarnings = migrationWarnings;
this.corruptedPath = corruptedPath;
this.wasRecovered = wasRecovered;
this._merged = this.computeMergedSettings();
}
@ -414,6 +428,9 @@ export class LoadedSettings {
readonly isTrusted: boolean;
readonly migratedInMemorScopes: Set<SettingScope>;
readonly migrationWarnings: string[];
readonly corruptedPath: string | undefined;
readonly wasRecovered: boolean;
corruptionDialogDismissed: boolean = false;
private _merged: Settings;
@ -451,7 +468,8 @@ export class LoadedSettings {
setNestedPropertySafe(settingsFile.settings, key, value);
setNestedPropertySafe(settingsFile.originalSettings, key, value);
this._merged = this.computeMergedSettings();
saveSettings(settingsFile, createSettingsUpdate(key, value));
const replacePath = key === 'mcpServers' ? key.split('.') : [];
saveSettings(settingsFile, createSettingsUpdate(key, value), replacePath);
}
recomputeMerged(): void {
@ -498,6 +516,8 @@ export function createMinimalSettings(): LoadedSettings {
false,
new Set(),
[],
undefined,
false,
);
}
@ -596,6 +616,50 @@ export function resetHomeEnvBootstrapForTesting(): void {
homeEnvBootstrapped = false;
}
/**
* Collects environment variables from user-level `.env` files and returns
* them as a plain dictionary **without** mutating `process.env`.
*
* Candidates are iterated most-specific-first (`~/.qwen/.env` before
* `~/.env`). `??=` ensures the first file to define a key wins, matching
* dotenv's first-occurrence-wins semantics used elsewhere.
*
* Note: this dict intentionally does NOT filter PROJECT_ENV_HARDCODED_EXCLUSIONS
* or advanced.excludedEnvVars — substitution scope is narrower than process.env
* population handled by preResolveHomeEnvOverrides / readHomeEnvInto.
*/
function getHomeEnvFallbackVars(): Record<string, string> {
const globalQwenDir = Storage.getGlobalQwenDir();
const candidates = [path.join(globalQwenDir, '.env')];
// When QWEN_HOME is set, skip ~/.env to avoid surprise cross-contamination
// from a shared home .env. getUserLevelEnvPaths() always includes ~/.env
// because loadEnvironment() populates process.env independently — the two
// scopes are intentionally different.
if (!process.env['QWEN_HOME']) {
candidates.push(path.join(path.dirname(globalQwenDir), '.env'));
}
const result: Record<string, string> = {};
for (const candidate of candidates) {
if (!fs.existsSync(candidate)) {
continue;
}
try {
const parsed = dotenv.parse(fs.readFileSync(candidate, 'utf-8'));
for (const key in parsed) {
if (Object.hasOwn(parsed, key) && !Object.hasOwn(process.env, key)) {
result[key] ??= parsed[key]!;
}
}
} catch (e) {
debugLogger.warn(
`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`,
);
}
}
return result;
}
/**
* Surfaces a one-shot warning when QWEN_HOME has been redirected but the
* user hasn't migrated their existing global state. Auto-copying OAuth
@ -803,12 +867,15 @@ export function loadEnvironment(settings: Settings): void {
}
}
export const CORRUPTED_SUFFIX = '.corrupted';
/**
* Loads settings from user and workspace directories.
* Project settings override user settings.
* Load and merge settings from all scopes:
* System Defaults → User (~/.qwen/settings.json) → Workspace → System.
*/
export function loadSettings(
workspaceDir: string = process.cwd(),
consumeCorruptionEnvVars: boolean = true,
): LoadedSettings {
// Apply any QWEN_HOME / QWEN_RUNTIME_DIR set in user-level `.env` files
// BEFORE any code reads a path derived from them. After this call, the
@ -850,17 +917,48 @@ export function loadSettings(
const loadAndMigrate = (
filePath: string,
scope: SettingScope,
): { settings: Settings; rawJson?: string; migrationWarnings?: string[] } => {
): {
settings: Settings;
rawJson?: string;
migrationWarnings?: string[];
corruptedPath?: string;
wasRecovered?: boolean;
} => {
try {
if (fs.existsSync(filePath)) {
let content = fs.readFileSync(filePath, 'utf-8');
let rawSettings: unknown;
let recoveryWarning: string | undefined;
// Carry corruption state through to the final return so it
// can be attached after the migration pipeline runs.
const corruptedPath = `${filePath}${CORRUPTED_SUFFIX}`;
let corruptedSaved = false;
let recoveredFromBackup = false;
let recoveredFromEnvVar: boolean | null = null;
try {
rawSettings = JSON.parse(stripJsonComments(content));
} catch (parseError: unknown) {
// JSON parse failed — try to recover from .orig backup
// ===== JSON parse failed — enter corruption recovery =====
// Strategy: save corrupted file as .corrupted → recover from .orig →
// show dialog in UI. Never crash due to a corrupted settings file.
// Step 1: copy corrupted file to .corrupted for reference
// MUST guarantee .corrupted exists so onExit can restore it.
// Use copy (not rename) — the file must stay on disk so that
// child processes spawned by relaunchAppInChildProcess() can
// enter the existsSync block where env-var propagation is
// checked. Step 2 will overwrite it with .orig if available.
try {
fs.copyFileSync(filePath, corruptedPath);
corruptedSaved = true;
} catch (copyError) {
debugLogger.warn(
`Failed to copy corrupted file: ${getErrorMessage(copyError)}`,
);
}
// Step 2: try recovering from .orig backup (created on each write)
const backupPath = `${filePath}.orig`;
if (fs.existsSync(backupPath)) {
debugLogger.warn(
@ -871,43 +969,63 @@ export function loadSettings(
const backupSettings = JSON.parse(
stripJsonComments(backupContent),
);
// Backup is valid — restore it
// Backup valid — overwrite with backup to restore last good state
fs.writeFileSync(filePath, backupContent, 'utf-8');
content = backupContent;
rawSettings = backupSettings;
const recoveryMsg = `Settings file ${filePath} had invalid JSON and was recovered from backup ${backupPath}. Some recent settings changes may have been lost.`;
debugLogger.warn(recoveryMsg);
// Surface warning to user so they know settings were rolled back
recoveryWarning = recoveryMsg;
recoveredFromBackup = true;
} catch (backupError) {
// Could be invalid JSON, read error, or write-back failure
// Backup also corrupted — give up recovery
debugLogger.warn(
`Failed to recover from backup ${backupPath}: ${getErrorMessage(backupError)}. Falling back to empty settings.`,
);
}
}
// No valid backup available — rename the corrupted file so the app
// can start with empty settings rather than crashing.
// Step 3: no backup available — start with empty settings
if (!rawSettings) {
const corruptedPath = `${filePath}.corrupted.${Date.now()}`;
let warningMsg: string;
try {
fs.renameSync(filePath, corruptedPath);
warningMsg = `Settings file ${filePath} has invalid JSON and was renamed to ${corruptedPath}. Your settings have been reset. To recover, fix the JSON in ${corruptedPath} and rename it back.`;
} catch (renameError) {
// If rename fails, still proceed with empty settings
debugLogger.error(
`Failed to rename corrupted settings file: ${getErrorMessage(renameError)}`,
);
warningMsg = `Settings file ${filePath} has invalid JSON. Your settings have been reset. Please fix the JSON in ${filePath} manually.`;
}
const warningMsg = `Settings file ${filePath} has invalid JSON. Your settings have been reset.`;
debugLogger.warn(warningMsg);
if (corruptedSaved) {
// Clear the original file so the settings UI shows empty settings
// instead of the corrupted content.
try {
fs.writeFileSync(filePath, '{}', 'utf-8');
} catch {
/* ignore — settings are already empty in memory */
}
}
return {
settings: {},
migrationWarnings: [warningMsg],
migrationWarnings: [],
corruptedPath: corruptedSaved ? corruptedPath : undefined,
wasRecovered: false,
};
}
// Fall through to migration pipeline — .orig backup may be in
// an older schema and needs to go through runMigrations.
}
// Propagate corruption state from parent process via env vars.
// relaunchAppInChildProcess() spawns a child that re-reads
// settings.json (already valid after parent recovered it). The
// env vars preserve the corruption marker across the boundary.
// Only apply to user scope since that's where corruption is detected.
// Clear env vars after reading so subsequent loadSettings calls
// don't re-trigger this path.
const envCorruptedPath = process.env[ENV_CORRUPTED_PATH];
if (
consumeCorruptionEnvVars &&
envCorruptedPath &&
envCorruptedPath === corruptedPath &&
scope === SettingScope.User
) {
corruptedSaved = true;
recoveredFromEnvVar = process.env[ENV_WAS_RECOVERED] === '1';
delete process.env[ENV_CORRUPTED_PATH];
delete process.env[ENV_WAS_RECOVERED];
}
if (
@ -952,6 +1070,10 @@ export function loadSettings(
}
};
// Execute migrations even on recovered settings — the migrated data
// must persist. The disk-write branches below (version normalization)
// are guarded by !corruptedSaved to avoid creating .orig backups
// of freshly-reset settings.
if (needsMigration(settingsObject)) {
const migrationResult = runMigrations(settingsObject, scope);
if (migrationResult.executedMigrations.length > 0) {
@ -961,7 +1083,10 @@ export function loadSettings(
>;
migrationWarnings = migrationResult.warnings;
persistSettingsObject('Error migrating settings file on disk');
} else if (hasLegacyNumericVersion || hasInvalidVersion) {
} else if (
(hasLegacyNumericVersion || hasInvalidVersion) &&
!corruptedSaved
) {
// Migration was deemed needed but nothing executed. Normalize version metadata
// to avoid repeated no-op checks on startup.
settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
@ -971,28 +1096,30 @@ export function loadSettings(
persistSettingsObject('Error normalizing settings version on disk');
}
} else if (
!hasVersionKey ||
hasInvalidVersion ||
hasLegacyNumericVersion
(!hasVersionKey || hasInvalidVersion || hasLegacyNumericVersion) &&
!corruptedSaved
) {
// No migration needed/executable, but version metadata is missing or invalid.
// Normalize it to current version to avoid repeated startup work.
// Skip if we just recovered from corruption — the next startup will
// handle normalization, avoiding an unnecessary writeWithBackupSync
// that would create a .orig file from the freshly reset settings.
settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
persistSettingsObject('Error normalizing settings version on disk');
}
// Prepend recovery warning if settings were restored from backup
const allWarnings = [
...(recoveryWarning ? [recoveryWarning] : []),
...(migrationWarnings ?? []),
];
return {
// Attach corruption state if settings were recovered from backup
const result: ReturnType<typeof loadAndMigrate> = {
settings: settingsObject as Settings,
rawJson: content,
migrationWarnings:
allWarnings.length > 0 ? allWarnings : migrationWarnings,
migrationWarnings: migrationWarnings ?? [],
};
if (corruptedSaved) {
result.corruptedPath = corruptedPath;
result.wasRecovered =
recoveredFromBackup || (recoveredFromEnvVar ?? false);
}
return result;
}
} catch (error: unknown) {
settingsErrors.push({
@ -1032,11 +1159,25 @@ export function loadSettings(
const userOriginalSettings = structuredClone(userResult.settings);
const workspaceOriginalSettings = structuredClone(workspaceResult.settings);
// Environment variables for runtime use
systemSettings = resolveEnvVarsInObject(systemResult.settings);
systemDefaultSettings = resolveEnvVarsInObject(systemDefaultsResult.settings);
userSettings = resolveEnvVarsInObject(userResult.settings);
workspaceSettings = resolveEnvVarsInObject(workspaceResult.settings);
// Resolve ${VAR} placeholders in settings using home .env as fallback.
// getHomeEnvFallbackVars() excludes keys already in process.env, so
// effective precedence is: process.env > home .env > unresolved placeholder.
// The resolver checks customEnv before process.env, but since customEnv
// never contains a process.env key, process.env always wins.
const homeEnvFallback = getHomeEnvFallbackVars();
systemSettings = resolveEnvVarsInObject(
systemResult.settings,
homeEnvFallback,
);
systemDefaultSettings = resolveEnvVarsInObject(
systemDefaultsResult.settings,
homeEnvFallback,
);
userSettings = resolveEnvVarsInObject(userResult.settings, homeEnvFallback);
workspaceSettings = resolveEnvVarsInObject(
workspaceResult.settings,
homeEnvFallback,
);
// Support legacy theme names
if (userSettings.ui?.theme === 'VS') {
@ -1121,6 +1262,8 @@ export function loadSettings(
isTrusted,
migratedInMemorScopes,
allMigrationWarnings,
userResult.corruptedPath,
userResult.wasRecovered ?? false,
);
}
@ -1139,6 +1282,7 @@ export function saveSettings(
string,
unknown
>,
replacePath: readonly string[] = [],
): void {
try {
// Ensure the directory exists
@ -1148,7 +1292,17 @@ export function saveSettings(
}
// Use the format-preserving update function
updateSettingsFilePreservingFormat(settingsFile.path, updates);
const written = updateSettingsFilePreservingFormat(
settingsFile.path,
updates,
false,
replacePath,
);
if (!written) {
debugLogger.error(
`saveSettings: updateSettingsFilePreservingFormat returned false for ${settingsFile.path}`,
);
}
} catch (error) {
debugLogger.error('Error saving user settings file.');
debugLogger.error(error instanceof Error ? error.message : String(error));

View File

@ -8,6 +8,7 @@ import type {
MCPServerConfig,
BugCommandSettings,
TelemetrySettings,
OutboundCorrelationSettings,
AuthType,
ChatCompressionSettings,
ModelProvidersConfig,
@ -1037,6 +1038,29 @@ const SETTINGS_SCHEMA = {
},
},
outboundCorrelation: {
type: 'object',
label: 'Outbound Correlation',
category: 'Advanced',
requiresRestart: true,
default: undefined as OutboundCorrelationSettings | undefined,
description:
"SECURITY-RELEVANT. Controls what client-side correlation data qwen-code writes into outbound LLM API requests (DashScope, OpenAI, Anthropic, etc.) — separate from `telemetry.*` which governs data flow into the operator's OWN OTLP collector. All values default to off. Opt in only when the LLM provider also reports into your OTel collector for cross-process trace stitching (e.g. ARMS Tracing + DashScope).",
showInDialog: false,
jsonSchemaOverride: {
type: 'object',
properties: {
propagateTraceContext: {
description:
"Requires `telemetry.enabled: true`. Inject W3C `traceparent` header on outbound `fetch` requests (LLM SDK calls, MCP StreamableHTTP, WebFetch, ...). Default: false — trace context stays internal to the operator's OTLP collector and is NOT written onto third-party request streams. Set true only when you want cross-process trace stitching with an OTel-aware LLM provider (e.g. ARMS+DashScope). Client HTTP spans are still emitted in either case; this flag only governs the wire `traceparent` header.",
type: 'boolean',
default: false,
},
},
additionalProperties: false,
},
},
fastModel: {
type: 'string',
label: 'Fast Model',
@ -1076,6 +1100,26 @@ const SETTINGS_SCHEMA = {
'Maximum number of user/model/tool turns to keep in a session. -1 means unlimited.',
showInDialog: false,
},
maxWallTimeSeconds: {
type: 'number',
label: 'Max Wall-Clock Time (seconds)',
category: 'Model',
requiresRestart: false,
default: -1,
description:
'Run-level wall-clock budget for headless / unattended runs, in seconds. -1 means unlimited; otherwise must be in [1, ~2,147,483] (sub-second values and values above ~24 days are rejected as typos). Overridable per-invocation via --max-wall-time (which also accepts duration suffixes like 5m, 1.5h).',
showInDialog: false,
},
maxToolCalls: {
type: 'number',
label: 'Max Tool Calls',
category: 'Model',
requiresRestart: false,
default: -1,
description:
'Cumulative tool-call budget for a run (counts every executed tool, success or failure; structured_output under --json-schema is exempt). -1 means unlimited; 0 means "no tool calls allowed" (first call aborts). Capped at 1,000,000 to catch typos. Overridable via --max-tool-calls.',
showInDialog: false,
},
chatCompression: {
type: 'object',
label: 'Chat Compression',
@ -1109,7 +1153,8 @@ const SETTINGS_SCHEMA = {
category: 'Model',
requiresRestart: false,
default: true,
description: 'Disable all loop detection checks (streaming and LLM).',
description:
'Skip streaming loop detection. Defaults to true to avoid false-positive interruptions; set to false to re-enable as an unattended-run guardrail.',
showInDialog: false,
},
skipStartupContext: {
@ -1394,7 +1439,7 @@ const SETTINGS_SCHEMA = {
label: 'Enable Managed Auto-Dream',
category: 'Memory',
requiresRestart: false,
default: false,
default: true,
description:
'Enable automatic consolidation (dream) of collected memories.',
showInDialog: false,
@ -1404,7 +1449,7 @@ const SETTINGS_SCHEMA = {
label: 'Enable Auto Skill',
category: 'Memory',
requiresRestart: false,
default: false,
default: true,
description:
'Enable background review for reusable project skills after tool-heavy sessions.',
showInDialog: false,
@ -1762,6 +1807,28 @@ const SETTINGS_SCHEMA = {
description: 'The number of lines to keep when truncating tool output.',
showInDialog: false,
},
computerUse: {
type: 'object',
label: 'Computer Use',
category: 'Tools',
requiresRestart: true,
default: {},
description:
'Cross-platform desktop automation via the upstream open-computer-use MCP server. Tools: list_apps, get_app_state, click, type_text, scroll, drag, press_key, perform_secondary_action, set_value. On first invocation, the upstream binary is fetched via npx and the user is walked through macOS Accessibility / Screen Recording permissions if needed.',
showInDialog: false,
properties: {
enabled: {
type: 'boolean',
label: 'Enable Computer Use',
category: 'Tools',
requiresRestart: true,
default: true,
description:
'When enabled (default), the 9 computer_use__* tools are registered as deferred built-ins.',
showInDialog: true,
},
},
},
},
},
@ -2272,6 +2339,41 @@ const SETTINGS_SCHEMA = {
},
},
},
worktree: {
type: 'object',
label: 'Worktree',
category: 'Advanced',
requiresRestart: false,
default: {},
description:
'Configuration for general-purpose git worktrees created by the ' +
'CLI (the `enter_worktree` tool, the `agent isolation: "worktree"` ' +
'parameter, and the startup `--worktree` flag). Does NOT affect ' +
'Agent Arena worktrees — see `agents.arena.worktreeBaseDir` for those.',
showInDialog: false,
properties: {
symlinkDirectories: {
type: 'array',
label: 'Symlink Directories Into Worktrees',
category: 'Advanced',
requiresRestart: false,
default: undefined as string[] | undefined,
description:
'Directories under the main repository to symlink into every ' +
'general-purpose worktree on creation. Useful for sharing ' +
'large opt-in dirs like `node_modules` so the model can run ' +
'tests / builds inside the worktree without a fresh install. ' +
'Paths must be relative to the repo root; absolute paths, ' +
'anything containing `..`, and any path inside `.git` or ' +
'`.qwen` (the CLI-managed metadata tree, which contains ' +
'the worktrees directory itself) are rejected. Missing ' +
'source dirs and existing destination paths are silently ' +
'skipped (no overwrite, no failure).',
showInDialog: false,
},
},
},
} as const satisfies SettingsSchema;
export type SettingsSchemaType = typeof SETTINGS_SCHEMA;

View File

@ -24,7 +24,7 @@ import type { CliArgs } from './config/config.js';
import { type LoadedSettings } from './config/settings.js';
import { appEvents, AppEvent } from './utils/events.js';
import type { Config } from '@qwen-code/qwen-code-core';
import { OutputFormat } from '@qwen-code/qwen-code-core';
import { ApprovalMode, OutputFormat } from '@qwen-code/qwen-code-core';
const mockWriteStderrLine = vi.hoisted(() => vi.fn());
@ -181,6 +181,7 @@ describe('gemini.tsx main function', () => {
isInteractive: () => false,
getQuestion: () => '',
getSandbox: () => false,
getApprovalMode: () => ApprovalMode.DEFAULT,
getDebugMode: () => false,
getListExtensions: () => false,
getMcpServers: () => ({}),
@ -260,6 +261,7 @@ describe('gemini.tsx main function', () => {
isInteractive: () => false,
getQuestion: () => 'bare prompt',
getSandbox: () => false,
getApprovalMode: () => ApprovalMode.DEFAULT,
getDebugMode: () => false,
getListExtensions: () => false,
getMcpServers: () => ({}),
@ -569,6 +571,7 @@ describe('gemini.tsx main function', () => {
isInteractive: () => false,
getQuestion: () => ' hello stream ',
getSandbox: () => false,
getApprovalMode: () => ApprovalMode.DEFAULT,
getDebugMode: () => false,
getListExtensions: () => false,
getMcpServers: () => ({}),
@ -773,6 +776,8 @@ describe('gemini.tsx main function kitty protocol', () => {
disabledSlashCommands: undefined,
authType: undefined,
maxSessionTurns: undefined,
maxWallTime: undefined,
maxToolCalls: undefined,
experimentalLsp: undefined,
channel: undefined,
chatRecording: undefined,

View File

@ -21,7 +21,7 @@ import {
import { render } from 'ink';
import dns from 'node:dns';
import os from 'node:os';
import { basename } from 'node:path';
import path, { basename } from 'node:path';
import v8 from 'node:v8';
import React from 'react';
import { validateAuthMethod } from './config/auth.js';
@ -29,6 +29,8 @@ import * as cliConfig from './config/config.js';
import { loadCliConfig, parseArguments } from './config/config.js';
import type { DnsResolutionOrder, LoadedSettings } from './config/settings.js';
import {
ENV_CORRUPTED_PATH,
ENV_WAS_RECOVERED,
createMinimalSettings,
getSettingsWarnings,
loadSettings,
@ -39,6 +41,12 @@ import {
type InitializationResult,
} from './core/initializer.js';
import { runNonInteractive } from './nonInteractiveCli.js';
import {
setupStartupWorktree,
persistStartupWorktreeSidecar,
buildStartupWorktreeNotice,
type StartupWorktreeContext,
} from './startup/worktreeStartup.js';
import { runNonInteractiveStreamJson } from './nonInteractive/session.js';
import { AppContainer } from './ui/AppContainer.js';
import { setMaxSizedBoxDebugging } from './ui/components/shared/MaxSizedBox.js';
@ -78,7 +86,9 @@ import { start_sandbox } from './utils/sandbox.js';
import { getStartupWarnings } from './utils/startupWarnings.js';
import { getUserStartupWarnings } from './utils/userStartupWarnings.js';
import { getCliVersion } from './utils/version.js';
import { initializeWarningHandler } from './utils/warningHandler.js';
import { writeStderrLine } from './utils/stdioHelpers.js';
import { getHeadlessYoloSafetyWarning } from './utils/headlessSafetyWarnings.js';
import { computeWindowTitle } from './utils/windowTitle.js';
import {
startEarlyInputCapture,
@ -97,6 +107,11 @@ import { installSynchronizedOutput } from './ui/utils/synchronizedOutput.js';
const debugLogger = createDebugLogger('STARTUP');
function clearCorruptionEnvVars(): void {
delete process.env[ENV_CORRUPTED_PATH];
delete process.env[ENV_WAS_RECOVERED];
}
export function validateDnsResolutionOrder(
order: string | undefined,
): DnsResolutionOrder {
@ -402,6 +417,7 @@ export async function main() {
setStartupEventSink((name, attrs) => recordStartupEvent(name, attrs));
}
setupUnhandledRejectionHandler();
initializeWarningHandler();
if (process.argv.includes('--bare')) {
process.env[QWEN_CODE_SIMPLE_ENV_VAR] = '1';
@ -418,12 +434,38 @@ export async function main() {
process.env[QWEN_CODE_SIMPLE_ENV_VAR] = '1';
}
// Load user settings — bare mode uses minimal config, normal mode loads full.
const settings = isBareMode(argv.bare)
? createMinimalSettings()
: loadSettings();
// Propagate corruption state to child process via env vars so
// relaunchAppInChildProcess() doesn't lose the marker.
if (settings.corruptedPath) {
process.env[ENV_CORRUPTED_PATH] = settings.corruptedPath;
process.env[ENV_WAS_RECOVERED] = settings.wasRecovered ? '1' : '0';
}
await cleanupCheckpoints();
// Performance checkpoint
profileCheckpoint('after_load_settings');
// Emit settings warnings early so the parent process surfaces them
// before relaunchAppInChildProcess() exits (the child has empty
// migrationWarnings because the parent already renamed the file).
const settingsWarnings = getSettingsWarnings(settings);
for (const warning of settingsWarnings) {
writeStderrLine(warning);
}
// Corruption notification no longer goes through migrationWarnings —
// check corruptedPath directly to keep stderr visible in relaunch.
if (settings.corruptedPath) {
writeStderrLine(
'Warning: Settings file had invalid JSON and was reset. ' +
'A copy of the corrupted file has been saved at: ' +
settings.corruptedPath,
);
}
// Check for invalid input combinations early to prevent crashes
if (argv.promptInteractive && !process.stdin.isTTY) {
writeStderrLine(
@ -577,7 +619,89 @@ export async function main() {
} else {
// Relaunch app so we always have a child process that can be internally
// restarted if needed.
await relaunchAppInChildProcess(memoryArgs, []);
await relaunchAppInChildProcess(memoryArgs, [], {
afterSpawn: clearCorruptionEnvVars,
});
}
}
// When --worktree is going to chdir us into a worktree below, resolve
// any relative-path argv fields to absolute paths now — BEFORE the
// chdir. Otherwise downstream `fs.existsSync('./mcp.json')` calls in
// `loadCliConfig` re-resolve against the worktree dir, where the file
// doesn't exist. Only touches values that look like paths (mcpConfig
// also accepts inline JSON — skip those).
//
// The list of fields below is hand-maintained. If you add a new
// CLI flag that takes a relative path, register it here too,
// otherwise --worktree silently breaks for that flag.
if (argv.worktree !== undefined) {
const launchCwdForPaths = process.cwd();
const looksLikeInlineJson = (v: string): boolean => {
const t = v.trim();
return t.startsWith('{') || t.startsWith('[');
};
const resolveIfPath = (v: string | undefined): string | undefined => {
if (typeof v !== 'string' || v.length === 0) return v;
if (looksLikeInlineJson(v)) return v;
return path.resolve(launchCwdForPaths, v);
};
argv.mcpConfig = resolveIfPath(argv.mcpConfig);
argv.openaiLoggingDir = resolveIfPath(argv.openaiLoggingDir);
argv.jsonFile = resolveIfPath(argv.jsonFile);
argv.inputFile = resolveIfPath(argv.inputFile);
argv.telemetryOutfile = resolveIfPath(argv.telemetryOutfile);
if (Array.isArray(argv.includeDirectories)) {
argv.includeDirectories = argv.includeDirectories.map((d) =>
typeof d === 'string' && d.length > 0
? path.resolve(launchCwdForPaths, d)
: d,
);
}
// `--json-schema` accepts either an inline schema or `@<path>`. The
// `@`-prefixed form is read from disk inside `resolveJsonSchemaArg`
// (`packages/cli/src/config/config.ts`), AFTER chdir, so a relative
// value would resolve against the worktree — fix the prefix path
// here.
if (typeof argv.jsonSchema === 'string') {
const trimmedSchema = argv.jsonSchema.trim();
if (trimmedSchema.startsWith('@')) {
const rel = trimmedSchema.slice(1);
if (rel.length > 0 && !path.isAbsolute(rel)) {
argv.jsonSchema = '@' + path.resolve(launchCwdForPaths, rel);
}
}
}
}
// Phase D-1: process --worktree before the resume picker so the picker
// (which uses process.cwd() to scope its session search) finds sessions
// saved inside the target worktree. Creates the worktree directory on
// disk and chdirs into it; on failure we emit to stderr and exit before
// any expensive initialization runs.
//
// ACP mode is exempt: the ACP host (Zed, etc.) supplies its own per-session
// cwd, and the startup-level chdir would not propagate. Reject the
// combination with a clear error rather than silently dropping --worktree.
let startupWorktreeContext: StartupWorktreeContext | null = null;
if (argv.worktree !== undefined && (argv.acp || argv.experimentalAcp)) {
writeStderrLine(
'--worktree cannot be combined with --acp / --experimental-acp. ' +
'Pass the worktree path as the cwd of the ACP loadSession / newSession ' +
'request instead.',
);
process.exit(1);
}
{
const startupRes = await setupStartupWorktree(argv.worktree, {
symlinkDirectories: settings.merged.worktree?.symlinkDirectories,
});
if (startupRes !== null) {
if (!startupRes.ok) {
writeStderrLine(startupRes.error);
process.exit(1);
}
startupWorktreeContext = startupRes.context;
}
}
@ -653,6 +777,51 @@ export async function main() {
);
profileCheckpoint('after_load_cli_config');
// Phase D-1: persist the WorktreeSession sidecar so Phase C's restore
// machinery on a subsequent `--resume` picks the worktree back up, and
// capture any override of a previously-resumed session's worktree so
// we can emit a one-shot notice on the model's first prompt.
//
// The notice is set BEFORE the persist attempt and AGAIN inside the
// try block (so the override addendum can be appended on success).
// A persist failure must NOT silently drop the notice — the cwd is
// already switched, and the model needs to know which worktree it's
// operating in regardless of whether the sidecar landed.
if (startupWorktreeContext) {
config.setPendingStartupWorktreeNotice(
buildStartupWorktreeNotice(startupWorktreeContext),
);
try {
const startupWorktreePersist = await persistStartupWorktreeSidecar(
config,
startupWorktreeContext,
);
if (startupWorktreePersist.overrodeResumedWorktree) {
writeStderrLine(
`--worktree overrode the resumed session's previous worktree ` +
`"${startupWorktreePersist.overriddenSlug ?? '(unknown)'}". ` +
`That worktree directory was left intact on disk.`,
);
}
// Refresh the notice with the override addendum (if any). When
// there is no override this is a no-op text-wise; on override it
// gives the model the "you overrode <previous-slug>" hint. TUI
// and headless consume this via Config.consumePendingStartupWorktreeNotice();
// ACP is excluded above (`--worktree` × `--acp` is mutually
// exclusive — see the mutex check earlier in this function).
config.setPendingStartupWorktreeNotice(
buildStartupWorktreeNotice(
startupWorktreeContext,
startupWorktreePersist,
),
);
} catch (error) {
debugLogger.warn(
`--worktree sidecar persist failed (non-fatal, notice preserved): ${error instanceof Error ? error.message : String(error)}`,
);
}
}
// Register cleanup for MCP clients as early as possible
// This ensures MCP server subprocesses are properly terminated on exit
registerCleanup(() => config.shutdown());
@ -761,6 +930,17 @@ export async function main() {
]),
];
// Surface critical startup warnings (corrupted settings, recovery, etc.)
// to stderr so they are visible regardless of UI mode. In interactive
// mode the TUI's Notifications component also renders them, but the
// onboarding flow can obscure the notification area, leaving users
// unaware that their settings were reset. Writing to stderr before
// the TUI takes over ensures the message is visible in the terminal
// scrollback. In non-interactive mode this is the *only* channel.
for (const warning of startupWarnings) {
writeStderrLine(warning);
}
// Render UI, passing necessary config values. Check that there is no command line question.
profileCheckpoint('before_render');
@ -802,9 +982,16 @@ export async function main() {
process.cwd(),
initializationResult!,
);
// Clean up corruption env vars so subsequent relaunch children
// and subprocesses don't inherit stale state.
clearCorruptionEnvVars();
return;
}
// Also clean up env vars for non-interactive paths so that
// subprocesses don't inherit stale state.
clearCorruptionEnvVars();
// Non-interactive: defer finalize until after `config.initialize()` runs
// so MCP discovery events (mcp_first_tool_registered, mcp_all_servers_settled,
// gemini_tools_updated) are captured in the profile.
@ -822,6 +1009,17 @@ export async function main() {
}
}
// Headless + YOLO without a sandbox lets the model auto-approve and
// execute shell / write / edit tools at the current process's
// privilege level. Emit a one-line stderr warning so unattended runs
// have at least an observable signal. Interactive runs are excluded
// because the user is at the keyboard and the TUI shows approval
// state directly. See issue #4103.
if (!config.isInteractive()) {
const yoloWarning = getHeadlessYoloSafetyWarning(config);
if (yoloWarning) writeStderrLine(yoloWarning);
}
// For non-stream-json mode, initialize config here. Stream-json defers
// `config.initialize()` to inside `Session.ensureConfigInitialized`
// because the initial control_request may register SDK MCP servers

View File

@ -861,6 +861,7 @@ export default {
'Auto-memory: {{status}}': 'Memòria automàtica: {{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'Auto-dream: {{status}} · {{lastDream}} · /dream per executar',
'Auto-skill: {{status}}': 'Habilitat automàtica: {{status}}',
never: 'mai',
on: 'activada',
off: 'desactivada',

View File

@ -818,6 +818,7 @@ export default {
'Auto-memory: {{status}}': 'Auto-Speicher: {{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'Auto-Konsolidierung: {{status}} · {{lastDream}} · /dream zum Ausführen',
'Auto-skill: {{status}}': 'Auto-Skill: {{status}}',
never: 'nie',
on: 'ein',
off: 'aus',

View File

@ -901,6 +901,7 @@ export default {
'Auto-memory: {{status}}': 'Auto-memory: {{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'Auto-dream: {{status}} · {{lastDream}} · /dream to run',
'Auto-skill: {{status}}': 'Auto-skill: {{status}}',
never: 'never',
on: 'on',
off: 'off',

View File

@ -1859,6 +1859,7 @@ export default {
'Auto-memory: {{status}}': 'Mémoire automatique : {{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'Rêve automatique : {{status}} · {{lastDream}} · /dream pour lancer',
'Auto-skill: {{status}}': 'Compétence automatique : {{status}}',
never: 'jamais',
on: 'activé',
off: 'désactivé',

View File

@ -594,6 +594,7 @@ export default {
'Auto-memory: {{status}}': '自動メモリ: {{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'自動統合: {{status}} · {{lastDream}} · /dream で実行',
'Auto-skill: {{status}}': '自動スキル: {{status}}',
never: '未実行',
on: 'オン',
off: 'オフ',

View File

@ -823,6 +823,7 @@ export default {
'Auto-memory: {{status}}': 'Memória automática: {{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'Consolidação automática: {{status}} · {{lastDream}} · /dream para executar',
'Auto-skill: {{status}}': 'Habilidade automática: {{status}}',
never: 'nunca',
on: 'ativado',
off: 'desativado',

View File

@ -832,6 +832,7 @@ export default {
'Auto-memory: {{status}}': 'Автопамять: {{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'Автоконсолидация: {{status}} · {{lastDream}} · /dream для запуска',
'Auto-skill: {{status}}': 'Автонавык: {{status}}',
never: 'никогда',
on: 'вкл',
off: 'выкл',

View File

@ -768,6 +768,7 @@ export default {
'Auto-memory: {{status}}': '自動記憶:{{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'自動整理:{{status}} · {{lastDream}} · /dream 立即運行',
'Auto-skill: {{status}}': '自動技能:{{status}}',
never: '從未',
on: '開',
off: '關',

View File

@ -852,6 +852,7 @@ export default {
'Auto-memory: {{status}}': '自动记忆:{{status}}',
'Auto-dream: {{status}} · {{lastDream}} · /dream to run':
'自动整理:{{status}} · {{lastDream}} · /dream 立即运行',
'Auto-skill: {{status}}': '自动技能:{{status}}',
never: '从未',
on: '开',
off: '关',

View File

@ -35,6 +35,7 @@ export interface IControlContext {
readonly settings: LoadedSettings;
permissionMode: PermissionMode;
sdkCanUseToolTimeoutMs?: number;
sdkMcpServers: Set<string>;
mcpClients: Map<string, { client: Client; config: MCPServerConfig }>;
inputClosed: boolean;
@ -54,6 +55,7 @@ export class ControlContext implements IControlContext {
readonly settings: LoadedSettings;
permissionMode: PermissionMode;
sdkCanUseToolTimeoutMs?: number;
sdkMcpServers: Set<string>;
mcpClients: Map<string, { client: Client; config: MCPServerConfig }>;
inputClosed: boolean;

View File

@ -0,0 +1,186 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect, it, vi } from 'vitest';
import {
InputFormat,
ToolConfirmationOutcome,
} from '@qwen-code/qwen-code-core';
import { createMinimalSettings } from '../../../config/settings.js';
import type { StreamJsonOutputAdapter } from '../../io/StreamJsonOutputAdapter.js';
import type { IControlContext } from '../ControlContext.js';
import type { IPendingRequestRegistry } from './baseController.js';
import { PermissionController } from './permissionController.js';
function createContext(canUseToolTimeoutMs?: number): IControlContext {
const abortController = new AbortController();
return {
config: {
getDebugMode: vi.fn().mockReturnValue(false),
getInputFormat: vi.fn().mockReturnValue(InputFormat.STREAM_JSON),
} as unknown as IControlContext['config'],
streamJson: {
send: vi.fn(),
} as unknown as StreamJsonOutputAdapter,
sessionId: 'test-session-id',
abortSignal: abortController.signal,
debugMode: false,
settings: createMinimalSettings(),
permissionMode: 'default',
sdkCanUseToolTimeoutMs: canUseToolTimeoutMs,
sdkMcpServers: new Set<string>(),
mcpClients: new Map(),
inputClosed: false,
};
}
function createRegistry(): IPendingRequestRegistry {
return {
registerIncomingRequest: vi.fn(),
deregisterIncomingRequest: vi.fn(),
registerOutgoingRequest: vi.fn(),
deregisterOutgoingRequest: vi.fn(),
};
}
describe('PermissionController', () => {
it('uses SDK canUseTool timeout for outgoing permission requests', async () => {
const context = createContext(120_000);
const controller = new PermissionController(
context,
createRegistry(),
'PermissionController',
);
const sendControlRequest = vi
.spyOn(controller, 'sendControlRequest')
.mockResolvedValue({
subtype: 'success',
request_id: 'request-1',
response: { behavior: 'allow' },
});
const onConfirm = vi.fn();
controller.getToolCallUpdateCallback()([
{
status: 'awaiting_approval',
request: {
callId: 'tool-call-1',
name: 'ask_user_question',
args: { questions: [] },
},
confirmationDetails: {
type: 'ask_user_question',
title: 'Please answer',
onConfirm,
},
},
]);
await vi.waitFor(() => {
expect(sendControlRequest).toHaveBeenCalledWith(
expect.objectContaining({
subtype: 'can_use_tool',
tool_name: 'ask_user_question',
}),
120_000,
context.abortSignal,
);
});
await vi.waitFor(() => {
expect(onConfirm).toHaveBeenCalledWith(
ToolConfirmationOutcome.ProceedOnce,
);
});
});
it('uses default timeout when SDK canUseTool timeout is undefined', async () => {
const context = createContext(); // undefined timeout
const controller = new PermissionController(
context,
createRegistry(),
'PermissionController',
);
const sendControlRequest = vi
.spyOn(controller, 'sendControlRequest')
.mockResolvedValue({
subtype: 'success',
request_id: 'request-2',
response: { behavior: 'allow' },
});
const onConfirm = vi.fn();
controller.getToolCallUpdateCallback()([
{
status: 'awaiting_approval',
request: {
callId: 'tool-call-2',
name: 'ask_user_question',
args: { questions: [] },
},
confirmationDetails: {
type: 'ask_user_question',
title: 'Please answer',
onConfirm,
},
},
]);
await vi.waitFor(() => {
expect(sendControlRequest).toHaveBeenCalledWith(
expect.objectContaining({
subtype: 'can_use_tool',
tool_name: 'ask_user_question',
}),
60_000, // DEFAULT_CAN_USE_TOOL_TIMEOUT_MS
context.abortSignal,
);
});
await vi.waitFor(() => {
expect(onConfirm).toHaveBeenCalledWith(
ToolConfirmationOutcome.ProceedOnce,
);
});
});
it('calls onConfirm with Cancel when sendControlRequest rejects', async () => {
const context = createContext(120_000);
const controller = new PermissionController(
context,
createRegistry(),
'PermissionController',
);
vi.spyOn(controller, 'sendControlRequest').mockRejectedValue(
new Error('Request timeout'),
);
const onConfirm = vi.fn();
controller.getToolCallUpdateCallback()([
{
status: 'awaiting_approval',
request: {
callId: 'tool-call-3',
name: 'ask_user_question',
args: { questions: [] },
},
confirmationDetails: {
type: 'ask_user_question',
title: 'Please answer',
onConfirm,
},
},
]);
await vi.waitFor(() => {
expect(onConfirm).toHaveBeenCalledWith(
ToolConfirmationOutcome.Cancel,
expect.objectContaining({
cancelMessage: expect.stringContaining('Request timeout'),
}),
);
});
});
});

View File

@ -36,6 +36,8 @@ import { BaseController } from './baseController.js';
// Import ToolCallConfirmationDetails types for type alignment
type ToolConfirmationType = 'edit' | 'exec' | 'mcp' | 'info' | 'plan';
const DEFAULT_CAN_USE_TOOL_TIMEOUT_MS = 60_000;
export class PermissionController extends BaseController {
private pendingOutgoingRequests = new Set<string>();
@ -427,7 +429,7 @@ export class PermissionController extends BaseController {
permission_suggestions: permissionSuggestions,
blocked_path: null,
} as CLIControlPermissionRequest,
undefined, // use default timeout
this.context.sdkCanUseToolTimeoutMs ?? DEFAULT_CAN_USE_TOOL_TIMEOUT_MS,
this.context.abortSignal,
);

View File

@ -0,0 +1,207 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect, it, vi } from 'vitest';
import { InputFormat } from '@qwen-code/qwen-code-core';
import { createMinimalSettings } from '../../../config/settings.js';
import type { StreamJsonOutputAdapter } from '../../io/StreamJsonOutputAdapter.js';
import type { IControlContext } from '../ControlContext.js';
import type { IPendingRequestRegistry } from './baseController.js';
import { SystemController } from './systemController.js';
function createContext(): IControlContext {
const abortController = new AbortController();
return {
config: {
getDebugMode: vi.fn().mockReturnValue(false),
getInputFormat: vi.fn().mockReturnValue(InputFormat.STREAM_JSON),
setSdkMode: vi.fn(),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
addMcpServers: vi.fn(),
setSessionSubagents: vi.fn(),
setApprovalMode: vi.fn(),
setModel: vi.fn(),
} as unknown as IControlContext['config'],
streamJson: {
send: vi.fn(),
} as unknown as StreamJsonOutputAdapter,
sessionId: 'test-session-id',
abortSignal: abortController.signal,
debugMode: false,
settings: createMinimalSettings(),
permissionMode: 'default',
sdkCanUseToolTimeoutMs: undefined,
sdkMcpServers: new Set<string>(),
mcpClients: new Map(),
inputClosed: false,
};
}
function createRegistry(): IPendingRequestRegistry {
return {
registerIncomingRequest: vi.fn(),
deregisterIncomingRequest: vi.fn(),
registerOutgoingRequest: vi.fn(),
deregisterOutgoingRequest: vi.fn(),
};
}
describe('SystemController', () => {
describe('initialize timeout validation', () => {
it('accepts valid timeout within bounds', async () => {
const context = createContext();
const controller = new SystemController(
context,
createRegistry(),
'SystemController',
);
await controller.handleRequest(
{
subtype: 'initialize',
timeout: { canUseTool: 120_000 },
},
'test-1',
);
expect(context.sdkCanUseToolTimeoutMs).toBe(120_000);
});
it('accepts timeout at maximum boundary (600_000ms)', async () => {
const context = createContext();
const controller = new SystemController(
context,
createRegistry(),
'SystemController',
);
await controller.handleRequest(
{
subtype: 'initialize',
timeout: { canUseTool: 600_000 },
},
'test-2',
);
expect(context.sdkCanUseToolTimeoutMs).toBe(600_000);
});
it('ignores timeout exceeding maximum boundary', async () => {
const context = createContext();
const controller = new SystemController(
context,
createRegistry(),
'SystemController',
);
await controller.handleRequest(
{
subtype: 'initialize',
timeout: { canUseTool: 600_001 },
},
'test-3',
);
expect(context.sdkCanUseToolTimeoutMs).toBeUndefined();
});
it('ignores Number.MAX_VALUE timeout', async () => {
const context = createContext();
const controller = new SystemController(
context,
createRegistry(),
'SystemController',
);
await controller.handleRequest(
{
subtype: 'initialize',
timeout: { canUseTool: Number.MAX_VALUE },
},
'test-4',
);
expect(context.sdkCanUseToolTimeoutMs).toBeUndefined();
});
it('ignores negative timeout', async () => {
const context = createContext();
const controller = new SystemController(
context,
createRegistry(),
'SystemController',
);
await controller.handleRequest(
{
subtype: 'initialize',
timeout: { canUseTool: -1000 },
},
'test-5',
);
expect(context.sdkCanUseToolTimeoutMs).toBeUndefined();
});
it('ignores zero timeout', async () => {
const context = createContext();
const controller = new SystemController(
context,
createRegistry(),
'SystemController',
);
await controller.handleRequest(
{
subtype: 'initialize',
timeout: { canUseTool: 0 },
},
'test-6',
);
expect(context.sdkCanUseToolTimeoutMs).toBeUndefined();
});
it('ignores Infinity timeout', async () => {
const context = createContext();
const controller = new SystemController(
context,
createRegistry(),
'SystemController',
);
await controller.handleRequest(
{
subtype: 'initialize',
timeout: { canUseTool: Infinity },
},
'test-7',
);
expect(context.sdkCanUseToolTimeoutMs).toBeUndefined();
});
it('ignores NaN timeout', async () => {
const context = createContext();
const controller = new SystemController(
context,
createRegistry(),
'SystemController',
);
await controller.handleRequest(
{
subtype: 'initialize',
timeout: { canUseTool: NaN },
},
'test-8',
);
expect(context.sdkCanUseToolTimeoutMs).toBeUndefined();
});
});
});

View File

@ -31,6 +31,14 @@ import {
const debugLogger = createDebugLogger('SYSTEM_CONTROLLER');
/**
* Maximum allowed timeout for canUseTool requests (10 minutes).
* Node.js setTimeout coerces delays > 2^31-1 to 32-bit signed integers,
* which can cause timeouts to fire immediately or never. This cap prevents
* such edge cases while still allowing reasonable timeout values.
*/
const MAX_CAN_USE_TOOL_TIMEOUT_MS = 600_000;
export class SystemController extends BaseController {
/**
* Handle system control requests
@ -132,6 +140,16 @@ export class SystemController extends BaseController {
this.context.config.setSdkMode(true);
const canUseToolTimeout = payload.timeout?.canUseTool;
if (
typeof canUseToolTimeout === 'number' &&
Number.isFinite(canUseToolTimeout) &&
canUseToolTimeout > 0 &&
canUseToolTimeout <= MAX_CAN_USE_TOOL_TIMEOUT_MS
) {
this.context.sdkCanUseToolTimeoutMs = canUseToolTimeout;
}
// Process SDK MCP servers
if (
payload.sdkMcpServers &&

View File

@ -364,6 +364,9 @@ export interface CLIMcpServerConfig {
export interface CLIControlInitializeRequest {
subtype: 'initialize';
hooks?: HookRegistration[] | null;
timeout?: {
canUseTool?: number;
};
/**
* SDK MCP servers config
* These are MCP servers running in the SDK process, connected via control plane.

View File

@ -174,6 +174,8 @@ describe('runNonInteractive', () => {
getGeminiClient: vi.fn().mockReturnValue(mockGeminiClient),
getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
getMaxSessionTurns: vi.fn().mockReturnValue(10),
getMaxWallTimeSeconds: vi.fn().mockReturnValue(-1),
getMaxToolCalls: vi.fn().mockReturnValue(-1),
getProjectRoot: vi.fn().mockReturnValue('/test/project'),
getTargetDir: vi.fn().mockReturnValue('/test/project'),
getMcpServers: vi.fn().mockReturnValue(undefined),
@ -211,6 +213,12 @@ describe('runNonInteractive', () => {
// restore worktree context. These tests don't exercise resume, so
// return undefined to short-circuit the helper.
getResumedSessionData: vi.fn().mockReturnValue(undefined),
// Phase D-1: nonInteractiveCli calls this on every prompt to pick
// up the one-shot startup-worktree notice (set by gemini.tsx
// when --worktree was passed). These tests don't exercise the
// --worktree flag, so return null to short-circuit injection
// and let the resume-restore branch run.
consumePendingStartupWorktreeNotice: vi.fn().mockReturnValue(null),
} as unknown as Config;
mockSettings = {

View File

@ -43,7 +43,9 @@ import {
handleToolError,
handleCancellationError,
handleMaxTurnsExceededError,
handleBudgetExceededError,
} from './utils/errors.js';
import { RunBudgetEnforcer } from './utils/runBudget.js';
const debugLogger = createDebugLogger('NON_INTERACTIVE_CLI');
@ -220,6 +222,44 @@ export async function runNonInteractive(
const geminiClient = config.getGeminiClient();
const abortController = options.abortController ?? new AbortController();
// Run-level budget enforcement for headless / unattended runs
// (issue #4103). Tied to the same abortController as user-initiated
// SIGINT so the existing cancellation plumbing carries the abort;
// `routeAbort` below interprets the reason so the user sees
// "budget exceeded" instead of a generic "cancelled" envelope.
const budgetEnforcer = new RunBudgetEnforcer(
{
maxWallTimeSeconds: config.getMaxWallTimeSeconds(),
maxToolCalls: config.getMaxToolCalls(),
},
abortController,
);
budgetEnforcer.start();
/**
* Called at every abort-detection site in place of
* `handleCancellationError` directly. If a budget tripped, surface the
* structured budget error (exit 55); otherwise fall through to the
* SIGINT / user-cancel path (exit 130) so existing behavior is
* preserved. Both branches call into `process.exit(...)` so the
* `unreachable` throw is only present to keep the type-checker honest.
*/
const routeAbort = async (): Promise<never> => {
const exceeded = budgetEnforcer.getExceeded();
if (exceeded) {
await handleBudgetExceededError(config, exceeded);
// Explicit unreachable — `handleBudgetExceededError` is `never`
// in production (it calls `process.exit`). If a test stubs
// `process.exit` or a future refactor makes the handler
// resumable, this throw carries the original budget message
// so the outer catch's `errorMessage` field stays actionable
// (vs. a useless literal "unreachable").
throw new Error(exceeded.message);
}
await handleCancellationError(config);
throw new Error('Operation cancelled.');
};
interface LocalQueueItem {
displayText: string;
modelText: string;
@ -375,27 +415,42 @@ export async function runNonInteractive(
initialPartList = [{ text: input }];
}
// Phase C: when --resume restored a session with an active worktree,
// prepend a system-reminder block to the user prompt so the model
// knows to keep using the worktree path. Stale sidecars (worktree
// dir deleted between sessions) are cleaned up inside the helper.
// TUI does this via historyManager.addItem(INFO); headless does it
// here because there is no UI history to write into.
if (config.getResumedSessionData()) {
// Inject a worktree context notice into the model's first prompt.
// Two sources: the `--worktree` startup flag (set by gemini.tsx
// before loadCliConfig) takes precedence over the Phase C resume
// restore. TUI does this via historyManager.addItem(INFO); here in
// headless we prepend a `<system-reminder>` block since there is
// no UI history to write into.
const withReminder = (
existing: PartListUnion,
text: string,
): PartListUnion => {
const reminderPart: Part = {
text: `<system-reminder>\n${text}\n</system-reminder>\n\n`,
};
return Array.isArray(existing)
? [reminderPart, ...existing]
: [reminderPart, existing];
};
const startupNotice = config.consumePendingStartupWorktreeNotice();
if (startupNotice) {
initialPartList = withReminder(initialPartList, startupNotice);
adapter.emitSystemMessage('worktree_started', {
notice: startupNotice,
});
} else if (config.getResumedSessionData()) {
try {
const sessionPath = config
.getSessionService()
.getWorktreeSessionPath(sessionId);
const restored = await restoreWorktreeContext(sessionPath);
if (restored.contextMessage) {
const reminderPart: Part = {
text: `<system-reminder>\n${restored.contextMessage}\n</system-reminder>\n\n`,
};
const partsArr = Array.isArray(initialPartList)
? initialPartList
: [initialPartList];
initialPartList = [reminderPart, ...partsArr];
// Also surface the notice in the JSON stream so SDK consumers
initialPartList = withReminder(
initialPartList,
restored.contextMessage,
);
// Surface the notice in the JSON stream so SDK consumers
// can react to it (logging, UI hints, etc.).
adapter.emitSystemMessage('worktree_restored', {
slug: restored.session?.slug,
@ -613,6 +668,34 @@ export async function runNonInteractive(
)
: createToolProgressHandler(requestInfo, adapter);
// Tick BEFORE the call so that --max-tool-calls=N caps the run
// at exactly N executions: the (N+1)th tick aborts before the
// tool runs. Ticking after would let the (N+1)th tool execute
// and only then abort. See issue #4103.
//
// Exempt `structured_output` ONLY when `--json-schema` is
// active: under --json-schema this is the terminal "I'm done"
// contract tool, not real work, and counting it would abort
// an otherwise-valid completion at the budget edge (budget=3,
// model used 3 tools then emits structured_output as call #4
// → exit 55 instead of success). Guarding on
// `getJsonSchema()` keeps the exemption tied to the feature
// that owns the tool name — an MCP server that registers an
// unrelated tool literally named `structured_output` would
// otherwise inherit a free pass.
//
// Caveat: failed structured_output calls (Ajv validation
// failure) also skip the tick, so a model stuck in a
// validation-retry loop is not bounded by --max-tool-calls.
// Documented in docs/users/features/headless.md → "Scope".
// Combine with --max-session-turns or --max-wall-time.
const isStructuredOutputExempt =
requestInfo.name === ToolNames.STRUCTURED_OUTPUT &&
config.getJsonSchema?.() !== undefined;
if (!isStructuredOutputExempt) {
budgetEnforcer.tickToolCall();
}
if (abortController.signal.aborted) await routeAbort();
const toolResponse = await executeToolCall(
config,
requestInfo,
@ -749,7 +832,12 @@ export async function runNonInteractive(
for await (const event of responseStream) {
if (abortController.signal.aborted) {
await handleCancellationError(config);
// Pair the startAssistantMessage() above so stream-json mode
// doesn't leave an unterminated message_start when a budget /
// SIGINT abort lands mid-stream. Symmetric with the drain-item
// loop fix below.
adapter.finalizeAssistantMessage();
await routeAbort();
}
// Use adapter for all event processing
adapter.processEvent(event);
@ -863,10 +951,24 @@ export async function runNonInteractive(
for await (const event of itemStream) {
if (abortController.signal.aborted) {
// Pair the startAssistantMessage() above so stream-json mode doesn't
// leave an unterminated message_start.
// Pair the startAssistantMessage() above so stream-json
// mode doesn't leave an unterminated message_start, then
// route through `routeAbort` so a budget overrun in the
// final drain item surfaces as exit code 55 instead of
// being silently swallowed by the outer success path
// (drain-loop fall-through; see issue #4103 review).
//
// Also flush queued task notifications and finalize
// one-shot monitors here. Previously this site used a
// bare `return` and let control fall through to the
// outer holdback loop, which did the flushing before
// exiting; routing through `routeAbort` skips that
// path, so we re-do it inline to preserve the
// task_started↔task_notification pairing invariant.
adapter.finalizeAssistantMessage();
return;
flushQueuedNotificationsToSdk(localQueue);
finalizeOneShotMonitors();
await routeAbort();
}
adapter.processEvent(event);
if (event.type === GeminiEventType.ToolCallRequest) {
@ -1018,12 +1120,12 @@ export async function runNonInteractive(
while (true) {
if (abortController.signal.aborted) {
registry.abortAll();
// Flush queued terminal notifications before handleCancellationError
// exits so stream-json consumers always see a task_notification paired
// with every task_started.
// Flush queued terminal notifications before routeAbort
// exits so stream-json consumers always see a task_notification
// paired with every task_started.
flushQueuedNotificationsToSdk(localQueue);
finalizeOneShotMonitors();
await handleCancellationError(config);
await routeAbort();
}
// Once we enter the final holdback loop, monitor events should no
// longer extend one-shot runtime. Already-queued events still drain
@ -1130,8 +1232,22 @@ export async function runNonInteractive(
flushQueuedNotificationsToSdk(localQueue);
finalizeOneShotMonitors();
// If a run-level budget tripped during an awaited stream / tool
// call, the underlying fetch's AbortError lands here before our
// explicit `routeAbort` sites can fire. Capture the reason so we
// can (a) include the friendly "Run aborted: …" message in the
// adapter's terminal result envelope (STREAM_JSON consumers
// depend on that envelope to close the stream cleanly) and (b)
// exit with the budget handler's exit code 55 instead of the
// generic `handleError` exit code 1 from a raw "AbortError".
const budgetExceeded = budgetEnforcer.getExceeded();
// For JSON and STREAM_JSON modes, compute usage from metrics
const message = error instanceof Error ? error.message : String(error);
const message = budgetExceeded
? budgetExceeded.message
: error instanceof Error
? error.message
: String(error);
const metrics = uiTelemetryService.getMetrics();
const usage = computeUsageFromMetrics(metrics);
// Get stats for JSON format output
@ -1152,18 +1268,43 @@ export async function runNonInteractive(
outputFormat === OutputFormat.TEXT && isAlreadyReportedError;
if (!skipAdapterEmit) {
adapter.emitResult({
isError: true,
durationMs: Date.now() - startTime,
apiDurationMs: totalApiDurationMs,
numTurns: turnCount,
errorMessage: message,
usage,
stats,
});
// Wrap in try/catch: emitResult eventually hits stdout.write, which
// can throw on EPIPE / ERR_STREAM_WRITE_AFTER_END when a piped
// consumer closes early (`qwen -p ... | head -n 1` is the common
// case). Letting that throw bubble out skips `handleBudgetExceededError`
// / `handleError` below, dropping the documented exit code 55
// contract — precisely when stdout is in trouble. Best-effort emit
// and continue to the exit handler.
try {
adapter.emitResult({
isError: true,
durationMs: Date.now() - startTime,
apiDurationMs: totalApiDurationMs,
numTurns: turnCount,
errorMessage: message,
usage,
stats,
});
} catch (emitErr) {
debugLogger.error(
`Failed to emit terminal result envelope: ${
emitErr instanceof Error ? emitErr.message : String(emitErr)
}`,
);
}
}
if (budgetExceeded) {
// Always exit AFTER emitResult so STREAM_JSON / JSON consumers
// see a terminal result envelope before the process dies.
await handleBudgetExceededError(config, budgetExceeded);
}
await handleError(error, config);
} finally {
// Cancel the wall-clock timer so it doesn't fire after a successful
// run completes — important for callers (e.g. the `qwen serve`
// daemon, SDK) that reuse a single process across many runs.
budgetEnforcer.stop();
const reg = config.getBackgroundTaskRegistry();
reg.setNotificationCallback(undefined);
reg.setRegisterCallback(undefined);

View File

@ -38,6 +38,8 @@ import type {
import { createDaemonStatusProvider } from './daemonStatusProvider.js';
import {
createHttpAcpBridge,
detachSessionIdFromEntryChannel,
findChannelInfoForEntry,
InvalidClientIdError,
InvalidPermissionOptionError,
InvalidSessionMetadataError,
@ -299,6 +301,56 @@ function makeChannel(opts: FakeAgentOpts = {}): ChannelHandle {
}
describe('createHttpAcpBridge', () => {
it('selects a session entry channel when the current attach channel has changed', () => {
// Model the channel-overlap window directly: old channel A still has
// an entry, while new channel B is the current attach target.
const channelA = { name: 'A' };
const channelB = { name: 'B' };
const infoA = { channel: channelA, label: 'old-dying-channel' };
const infoB = { channel: channelB, label: 'fresh-attach-channel' };
expect(
findChannelInfoForEntry(infoB, [infoA, infoB], {
channel: channelA,
}),
).toBe(infoA);
expect(
findChannelInfoForEntry(infoB, [infoB], {
channel: channelA,
}),
).toBeUndefined();
});
it('detaches a session from its entry channel during channel overlap', () => {
// Model the close/kill overlap window directly: old channel A still owns
// the session entry while fresh channel B is the current attach target.
// The detach helper used by closeSession/killSession must decrement A,
// not the current B channel.
const channelA = { name: 'A' };
const channelB = { name: 'B' };
const infoA = {
channel: channelA,
sessionIds: new Set(['session-a']),
label: 'old-dying-channel',
};
const infoB = {
channel: channelB,
sessionIds: new Set(['session-b']),
label: 'fresh-attach-channel',
};
const selected = detachSessionIdFromEntryChannel(
infoB,
[infoA, infoB],
{ channel: channelA },
'session-a',
);
expect(selected).toBe(infoA);
expect(infoA.sessionIds.has('session-a')).toBe(false);
expect(Array.from(infoB.sessionIds)).toEqual(['session-b']);
});
it('accepts a valid BridgeOptions.eventRingSize at construction time', () => {
// Smoke: positive finite integers are accepted; the underlying
// EventBus ring-size threading is exercised end-to-end in
@ -5840,6 +5892,37 @@ describe('createHttpAcpBridge', () => {
await bridge.shutdown();
});
it('keeps a shared ACP channel alive while closing one of several sessions', async () => {
const handles: ChannelHandle[] = [];
const factory: ChannelFactory = async () => {
const h = makeChannel({ sessionIdPrefix: `s${handles.length}` });
handles.push(h);
return h.channel;
};
const bridge = makeBridge({
channelFactory: factory,
sessionScope: 'thread',
});
const a = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const b = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const c = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
expect(handles).toHaveLength(1);
await bridge.closeSession(b.sessionId);
expect(bridge.sessionCount).toBe(2);
expect(handles[0]?.killed).toBe(false);
await bridge.closeSession(a.sessionId);
expect(bridge.sessionCount).toBe(1);
expect(handles[0]?.killed).toBe(false);
await bridge.closeSession(c.sessionId);
expect(bridge.sessionCount).toBe(0);
expect(handles[0]?.killed).toBe(true);
await bridge.shutdown();
});
it('throws SessionNotFoundError for unknown session', async () => {
const bridge = makeBridge();
await expect(bridge.closeSession('nonexistent')).rejects.toThrow(

View File

@ -278,6 +278,33 @@ interface ChannelInfo {
isDying: boolean;
}
/** @internal Visible for bridge lifecycle regression tests. */
export function findChannelInfoForEntry<T extends { channel: unknown }>(
current: T | undefined,
alive: Iterable<T>,
entry: { channel: unknown },
): T | undefined {
if (current?.channel === entry.channel) return current;
for (const info of alive) {
if (info.channel === entry.channel) return info;
}
return undefined;
}
/** @internal Visible for bridge lifecycle regression tests. */
export function detachSessionIdFromEntryChannel<
T extends { channel: unknown; sessionIds: Set<string> },
>(
current: T | undefined,
alive: Iterable<T>,
entry: { channel: unknown },
sessionId: string,
): T | undefined {
const info = findChannelInfoForEntry(current, alive, entry);
info?.sessionIds.delete(sessionId);
return info;
}
interface SessionEntry {
sessionId: string;
workspaceCwd: string;
@ -2031,15 +2058,8 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
return channelInfo;
};
const channelInfoForEntry = (
entry: SessionEntry,
): ChannelInfo | undefined => {
if (channelInfo?.channel === entry.channel) return channelInfo;
for (const info of aliveChannels) {
if (info.channel === entry.channel) return info;
}
return undefined;
};
const channelInfoForEntry = (entry: SessionEntry): ChannelInfo | undefined =>
findChannelInfoForEntry(channelInfo, aliveChannels, entry);
const getChannelClosedReject = (info: ChannelInfo): Promise<never> => {
if (!info.statusClosedReject) {
@ -2887,10 +2907,12 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
: ''),
);
if (defaultEntry === entry) defaultEntry = undefined;
const ci = channelInfo;
if (ci && ci.channel === entry.channel) {
ci.sessionIds.delete(sessionId);
}
const ci = detachSessionIdFromEntryChannel(
channelInfo,
aliveChannels,
entry,
sessionId,
);
for (const id of Array.from(entry.pendingPermissionIds)) {
resolvePending(id, { outcome: { outcome: 'cancelled' } });
}
@ -3717,10 +3739,12 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
// Detach from the channel. The channel dies only when its LAST
// session leaves — other sessions on the same channel keep
// running.
const ci = channelInfo;
if (ci && ci.channel === entry.channel) {
ci.sessionIds.delete(sessionId);
}
const ci = detachSessionIdFromEntryChannel(
channelInfo,
aliveChannels,
entry,
sessionId,
);
// PR 14b fix (codex round 5): tombstone the killed sessionId
// so any in-flight `extNotification` from the (about-to-be-
// killed) child can't seed the early-event buffer for a

View File

@ -0,0 +1,409 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import {
setupStartupWorktree,
buildStartupWorktreeNotice,
} from './worktreeStartup.js';
const exec = promisify(execFile);
async function makeTempRepo(): Promise<string> {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-wt-startup-test-'));
// macOS resolves /var → /private/var; pwd -P is the cheapest way to
// normalise. Use realpath so subsequent string comparisons against
// process.cwd() match exactly.
const resolved = await fs.realpath(dir);
await exec('git', ['init', '-q', '-b', 'main'], { cwd: resolved });
await exec('git', ['config', 'user.email', 't@e.com'], { cwd: resolved });
await exec('git', ['config', 'user.name', 't'], { cwd: resolved });
await exec('git', ['config', 'commit.gpgsign', 'false'], { cwd: resolved });
// Disable autocrlf so file contents committed and read back via the
// test compare byte-for-byte on Windows runners (where the default
// `core.autocrlf=true` checks files out with `\r\n`, breaking
// assertions like `expect(content).toBe('foo\n')`).
await exec('git', ['config', 'core.autocrlf', 'false'], { cwd: resolved });
await exec('git', ['config', 'core.eol', 'lf'], { cwd: resolved });
await fs.writeFile(path.join(resolved, 'README.md'), 'hello\n');
await exec('git', ['add', 'README.md'], { cwd: resolved });
await exec('git', ['commit', '-q', '-m', 'initial', '--no-verify'], {
cwd: resolved,
});
return resolved;
}
describe('setupStartupWorktree', () => {
// Real git operations + fetch through a local bare remote can take
// 10–15s on slower runners; bump the per-test ceiling so the PR-ref
// happy-path test doesn't flake.
vi.setConfig({ testTimeout: 30000, hookTimeout: 30000 });
let prevCwd: string;
let tempRepo: string | null = null;
beforeEach(() => {
prevCwd = process.cwd();
});
afterEach(async () => {
// Restore cwd before cleanup so the test process can rm -rf the temp dir.
process.chdir(prevCwd);
if (tempRepo) {
await fs.rm(tempRepo, { recursive: true, force: true });
tempRepo = null;
}
});
it('returns null when --worktree was not passed', async () => {
const res = await setupStartupWorktree(undefined);
expect(res).toBeNull();
});
it('rejects when the launch cwd is not a git repo', async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-wt-nongit-'));
tempRepo = dir;
process.chdir(await fs.realpath(dir));
const res = await setupStartupWorktree('foo');
expect(res).not.toBeNull();
expect(res!.ok).toBe(false);
if (!res!.ok) {
expect(res!.error).toMatch(/not a git repository/i);
}
});
it('creates a worktree with an auto-generated slug for bare --worktree', async () => {
tempRepo = await makeTempRepo();
process.chdir(tempRepo);
const res = await setupStartupWorktree('');
expect(res).not.toBeNull();
expect(res!.ok).toBe(true);
if (res!.ok) {
// adj-noun-XXXXXX pattern from GitWorktreeService.generateAutoSlug
// (3 random bytes → 6 hex chars).
expect(res!.context.slug).toMatch(/^[a-z]+-[a-z]+-[0-9a-f]{6}$/);
expect(res!.context.branch).toBe(`worktree-${res!.context.slug}`);
expect(res!.context.worktreePath).toContain(
path.join('.qwen', 'worktrees', res!.context.slug),
);
expect(res!.context.repoRoot).toBe(tempRepo);
expect(res!.context.originalBranch).toBe('main');
// 40-char SHA
expect(res!.context.originalHeadCommit).toMatch(/^[0-9a-f]{40}$/);
expect(res!.context.isPullRequest).toBe(false);
// process.cwd() was switched into the worktree.
expect(process.cwd()).toBe(res!.context.worktreePath);
// The worktree directory exists on disk and is a real dir.
const stat = await fs.stat(res!.context.worktreePath);
expect(stat.isDirectory()).toBe(true);
}
});
it('creates a worktree with an explicit slug', async () => {
tempRepo = await makeTempRepo();
process.chdir(tempRepo);
const res = await setupStartupWorktree('my-feature');
expect(res).not.toBeNull();
expect(res!.ok).toBe(true);
if (res!.ok) {
expect(res!.context.slug).toBe('my-feature');
expect(res!.context.branch).toBe('worktree-my-feature');
expect(res!.context.worktreePath).toBe(
path.join(tempRepo, '.qwen', 'worktrees', 'my-feature'),
);
}
});
it('rejects invalid slug characters before any git operation', async () => {
tempRepo = await makeTempRepo();
process.chdir(tempRepo);
const res = await setupStartupWorktree('../escape');
expect(res).not.toBeNull();
expect(res!.ok).toBe(false);
if (!res!.ok) {
expect(res!.error.toLowerCase()).toMatch(
/letters|hyphens|invalid|may only/,
);
}
// No worktree directory was created.
const exists = await fs
.stat(path.join(tempRepo, '.qwen', 'worktrees'))
.then(() => true)
.catch(() => false);
expect(exists).toBe(false);
// cwd was not changed.
expect(process.cwd()).toBe(tempRepo);
});
it('rejects #N PR references when origin remote is missing', async () => {
tempRepo = await makeTempRepo();
process.chdir(tempRepo);
// Temp repo has no `origin` remote — fetch should fail-close with a
// clear hint about adding origin.
const res = await setupStartupWorktree('#123');
expect(res).not.toBeNull();
expect(res!.ok).toBe(false);
if (!res!.ok) {
expect(res!.error).toContain('#123');
expect(res!.error.toLowerCase()).toContain('origin');
}
// No worktree directory was created — fail-close means no side effect.
const exists = await fs
.stat(path.join(tempRepo, '.qwen', 'worktrees'))
.then(() => true)
.catch(() => false);
expect(exists).toBe(false);
});
it('rejects full GitHub PR URLs when origin remote is missing', async () => {
tempRepo = await makeTempRepo();
process.chdir(tempRepo);
const res = await setupStartupWorktree(
'https://github.com/QwenLM/qwen-code/pull/4174',
);
expect(res).not.toBeNull();
expect(res!.ok).toBe(false);
if (!res!.ok) {
expect(res!.error).toContain('#4174');
expect(res!.error.toLowerCase()).toContain('origin');
}
});
it('creates a pr-<N> worktree from FETCH_HEAD when fetch succeeds (local fake remote)', async () => {
// Set up a fake "origin" repo that exposes refs/pull/<N>/head — git
// fetch only cares that the refspec exists on the remote, not that
// the remote is github.com. update-ref lets us materialise the ref
// locally without an actual GitHub round-trip.
const upstream = await fs.mkdtemp(
path.join(os.tmpdir(), 'qwen-wt-pr-upstream-'),
);
const upstreamResolved = await fs.realpath(upstream);
await exec('git', ['init', '-q', '--bare', '-b', 'main'], {
cwd: upstreamResolved,
});
tempRepo = await makeTempRepo();
process.chdir(tempRepo);
await exec('git', ['remote', 'add', 'origin', upstreamResolved], {
cwd: tempRepo,
});
await exec('git', ['push', '-q', 'origin', 'main'], { cwd: tempRepo });
// Author a "PR commit" on a feature branch in the local repo, push
// it to the upstream as refs/pull/42/head.
await exec('git', ['checkout', '-q', '-b', 'pr-source'], { cwd: tempRepo });
await fs.writeFile(path.join(tempRepo, 'pr-file.txt'), 'from PR 42\n');
await exec('git', ['add', 'pr-file.txt'], { cwd: tempRepo });
await exec('git', ['commit', '-q', '-m', 'PR 42 commit', '--no-verify'], {
cwd: tempRepo,
});
await exec('git', ['push', '-q', 'origin', 'HEAD:refs/pull/42/head'], {
cwd: tempRepo,
});
await exec('git', ['checkout', '-q', 'main'], { cwd: tempRepo });
// Drop the local pr-source branch so the worktree branch isn't
// confused with it.
await exec('git', ['branch', '-q', '-D', 'pr-source'], { cwd: tempRepo });
try {
const res = await setupStartupWorktree('#42');
expect(res).not.toBeNull();
expect(res!.ok).toBe(true);
if (res!.ok) {
expect(res!.context.slug).toBe('pr-42');
expect(res!.context.branch).toBe('worktree-pr-42');
expect(res!.context.isPullRequest).toBe(true);
expect(res!.context.worktreePath).toBe(
path.join(tempRepo, '.qwen', 'worktrees', 'pr-42'),
);
// The PR file lives inside the worktree (proving FETCH_HEAD was
// the base, not main).
const prFile = await fs.readFile(
path.join(res!.context.worktreePath, 'pr-file.txt'),
'utf8',
);
expect(prFile).toBe('from PR 42\n');
// Phase D-3 round 4: `originalHeadCommit` for PR worktrees must
// be the resolved FETCH_HEAD SHA (the PR tip), NOT the parent
// repo's HEAD. `WorktreeExitDialog`'s `rev-list <head>..HEAD`
// later relies on this to count only the user's own commits in
// the worktree, not the entire PR's history.
expect(res!.context.originalHeadCommit).toMatch(/^[0-9a-f]{40}$/);
// Resolve the PR ref directly and compare: must match.
const expectedSha = (
await exec('git', ['rev-parse', 'refs/pull/42/head'], {
cwd: upstreamResolved,
})
).stdout.trim();
expect(res!.context.originalHeadCommit).toBe(expectedSha);
// Sanity: must NOT equal the parent repo's main HEAD.
const parentHead = (
await exec('git', ['rev-parse', 'HEAD'], { cwd: tempRepo })
).stdout.trim();
expect(res!.context.originalHeadCommit).not.toBe(parentHead);
}
} finally {
// Restore cwd before rm so the upstream cleanup doesn't hit EBUSY.
process.chdir(prevCwd);
await fs.rm(upstreamResolved, { recursive: true, force: true });
}
});
it('re-attaches to an existing worktree instead of erroring (Phase 6 G1 fix)', async () => {
tempRepo = await makeTempRepo();
process.chdir(tempRepo);
// First call creates the worktree.
const first = await setupStartupWorktree('reattach-test');
expect(first).not.toBeNull();
expect(first!.ok).toBe(true);
if (!first!.ok) return;
expect(first!.context.wasReattached).toBe(false);
// Restore cwd so the second call starts from launch cwd, mirroring
// the real `qwen --resume <sid> --worktree foo` invocation flow.
process.chdir(tempRepo);
// Second call with the same slug now re-attaches, doesn't create.
const second = await setupStartupWorktree('reattach-test');
expect(second).not.toBeNull();
expect(second!.ok).toBe(true);
if (!second!.ok) return;
expect(second!.context.wasReattached).toBe(true);
expect(second!.context.slug).toBe('reattach-test');
expect(second!.context.branch).toBe('worktree-reattach-test');
expect(second!.context.worktreePath).toBe(first!.context.worktreePath);
expect(process.cwd()).toBe(first!.context.worktreePath);
});
it('refuses to re-attach when an existing dir occupies the slot on a different branch', async () => {
tempRepo = await makeTempRepo();
process.chdir(tempRepo);
// Manually create a directory at the would-be worktree path that
// is NOT a git worktree (just a plain dir with a file in it).
const slotPath = path.join(
tempRepo,
'.qwen',
'worktrees',
'plain-dir-conflict',
);
await fs.mkdir(slotPath, { recursive: true });
await fs.writeFile(path.join(slotPath, 'unexpected-content.txt'), 'oops');
// setupStartupWorktree should NOT silently re-attach (the dir is
// not a registered worktree). It also should NOT error — instead,
// it falls through to createUserWorktree which fails with the
// "already exists" branch.
const res = await setupStartupWorktree('plain-dir-conflict');
expect(res).not.toBeNull();
expect(res!.ok).toBe(false);
if (!res!.ok) {
// Either the re-attach branch error or createUserWorktree's
// "already exists" message is acceptable — both prevent clobbering.
expect(res!.error.toLowerCase()).toMatch(
/already exists|registered git worktree|expected/,
);
}
// Unexpected file survived.
const survived = await fs.readFile(
path.join(slotPath, 'unexpected-content.txt'),
'utf8',
);
expect(survived).toBe('oops');
});
it('refuses nested worktree creation from inside .qwen/worktrees/', async () => {
tempRepo = await makeTempRepo();
// Pre-create a fake worktree path and chdir into it. We don't need a
// real git worktree — the guard fires on path shape, not git state.
const nestedPath = path.join(tempRepo, '.qwen', 'worktrees', 'outer');
await fs.mkdir(nestedPath, { recursive: true });
process.chdir(nestedPath);
const res = await setupStartupWorktree('inner');
expect(res).not.toBeNull();
expect(res!.ok).toBe(false);
if (!res!.ok) {
expect(res!.error.toLowerCase()).toMatch(
/nested|inside another worktree/,
);
}
});
});
describe('buildStartupWorktreeNotice', () => {
// Only the four fields the function actually consumes — the `Pick<>`
// signature lets us keep the fixture minimal so adding new
// StartupWorktreeContext fields doesn't churn this file.
const baseContext = {
worktreePath: '/repo/.qwen/worktrees/foo',
slug: 'foo',
branch: 'worktree-foo',
wasReattached: false,
};
it('produces a single line for the no-override created case', () => {
const notice = buildStartupWorktreeNotice(baseContext);
expect(notice).toContain('[Startup]');
expect(notice).toContain('Active worktree');
expect(notice).toContain('"foo"');
expect(notice).toContain('/repo/.qwen/worktrees/foo');
expect(notice).toContain('worktree-foo');
expect(notice).not.toContain('Re-attached');
expect(notice).not.toContain('overrode');
});
it('uses "Re-attached" verb when wasReattached is true', () => {
const notice = buildStartupWorktreeNotice({
...baseContext,
wasReattached: true,
});
expect(notice).toContain('[Startup]');
expect(notice).toContain('Re-attached to worktree');
expect(notice).not.toContain('Active worktree');
});
it('appends an override hint when a previous worktree was overridden', () => {
const notice = buildStartupWorktreeNotice(baseContext, {
overrodeResumedWorktree: true,
overriddenSlug: 'old-slug',
sidecarPath: '/anywhere/sidecar.json',
});
expect(notice).toContain('[Startup]');
expect(notice).toContain('overrode');
expect(notice).toContain('"old-slug"');
expect(notice).toContain('qwen --worktree old-slug');
});
it('does NOT append the override hint when overrodeResumedWorktree is false', () => {
const notice = buildStartupWorktreeNotice(baseContext, {
overrodeResumedWorktree: false,
sidecarPath: '/anywhere/sidecar.json',
});
expect(notice).not.toContain('overrode');
});
});

View File

@ -0,0 +1,470 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Startup-time worktree setup for the `--worktree` CLI flag (Phase D-1).
*
* Runs after argv parsing and before `loadCliConfig()` / `Config` construction
* so the resulting `process.cwd()` change feeds directly into the Config's
* `targetDir`. Three entry forms are supported (see {@link setupStartupWorktree}):
*
* - Empty string (bare `--worktree`) → auto-generated `{adj}-{noun}-{6hex}` slug
* - Plain slug (`--worktree my-feature`) → that exact slug
* - PR reference (`--worktree=#123`, `--worktree https://github.com/o/r/pull/123`)
* → slug `pr-<N>`, fetched via `git fetch origin pull/<N>/head` and based
* off `FETCH_HEAD` (Phase D-3).
*
* Sidecar writing and `--resume` override accounting are NOT handled here —
* those need a constructed `Config` and live in {@link persistStartupWorktreeSidecar}.
*/
import * as path from 'node:path';
import {
createDebugLogger,
GitWorktreeService,
readWorktreeSession,
worktreeBranchForSlug,
writeWorktreeSession,
writeWorktreeSessionMarker,
} from '@qwen-code/qwen-code-core';
import type { Config, WorktreeSession } from '@qwen-code/qwen-code-core';
const debugLogger = createDebugLogger('WORKTREE_STARTUP');
/**
* `git rev-parse --abbrev-ref HEAD` returns this literal when the
* launch cwd has a detached HEAD checked out. Two related uses:
*
* 1. As an INPUT filter when normalizing `getCurrentBranch` output:
* we treat `'HEAD'` as "no real branch" and collapse to `undefined`
* so detached-state propagates uniformly through the slug/baseRef
* pipeline.
* 2. As the FALLBACK metadata string written to the sidecar's
* `originalBranch` field when the launch state was detached
* (no branch name to record).
*/
const DETACHED_HEAD = 'HEAD';
/**
* Resolved metadata for a startup worktree. Returned to the caller so the
* sidecar write (which needs `Config`) can happen after `loadCliConfig`.
*/
export interface StartupWorktreeContext {
/** Resolved absolute worktree path (where `process.cwd()` now points). */
worktreePath: string;
/** Slug, e.g. `my-feature` or `pr-123`. */
slug: string;
/** Branch name, e.g. `worktree-my-feature` or `worktree-pr-123`. */
branch: string;
/** Repo top level captured before chdir. */
repoRoot: string;
/** Branch that was checked out at worktree-creation time. */
originalBranch: string;
/** HEAD SHA captured at worktree-creation time (for WorktreeExitDialog). */
originalHeadCommit: string;
/** True iff the input was a PR reference. */
isPullRequest: boolean;
/**
* True when the worktree directory already existed at startup and we
* re-attached to it. PR fetch is skipped
* on re-attach since the ref was materialized previously, and
* commit-count semantics in `WorktreeExitDialog` will track only this
* session's new commits.
*/
wasReattached: boolean;
}
export type SetupStartupWorktreeResult =
| { ok: true; context: StartupWorktreeContext }
| { ok: false; error: string };
/**
* Resolves slug, creates the worktree, switches `process.cwd()`, and returns
* the metadata needed for the post-`loadCliConfig` sidecar write.
*
* Returns `null` when `rawInput === undefined` (no `--worktree` flag passed
* at all). Returns `{ ok: false, error }` for validation / git failures so
* the caller can print to stderr and exit with a controlled non-zero status.
*
* The caller is responsible for chdir-ing back if a later step fails — this
* helper does not roll back the worktree directory on a downstream error,
* matching `EnterWorktreeTool`'s "the worktree is yours now" semantics.
*/
export interface SetupStartupWorktreeOptions {
/**
* Mirrors `worktree.symlinkDirectories` (Phase D-2). Forwarded to
* `createUserWorktree` so the new worktree gets the same opt-in
* symlinks as `enter_worktree` and agent isolation worktrees do.
*/
symlinkDirectories?: readonly string[];
}
export async function setupStartupWorktree(
rawInput: string | undefined,
options?: SetupStartupWorktreeOptions,
): Promise<SetupStartupWorktreeResult | null> {
if (rawInput === undefined) return null;
// yargs delivers bare `--worktree` as an empty string (mirrors --resume).
// We accept it and fall through to auto-slug below.
const trimmed = rawInput.trim();
// Probe service rooted at the launch cwd so we can locate the repo top
// level before the chdir; the chdir target lives under that top level.
const launchCwd = process.cwd();
const probe = new GitWorktreeService(launchCwd);
const gitCheck = await probe.checkGitAvailable();
if (!gitCheck.available) {
return {
ok: false,
error: `--worktree: ${gitCheck.error ?? 'git is not available on PATH.'}`,
};
}
// Refuse nested creation: launching with --worktree from inside an existing
// worktree creates `<otherRepo>/.qwen/worktrees/<slug>/`, which is rarely
// what the user wants and corrupts ownership tracking.
if (/[\\/]\.qwen[\\/]worktrees[\\/]/.test(launchCwd)) {
return {
ok: false,
error: `--worktree: cannot start a new worktree from inside another worktree (cwd: ${launchCwd}). Run from the main checkout.`,
};
}
// `getRepoTopLevel()` returns null when cwd is not inside a git repo,
// so a single subprocess covers both the is-a-repo gate and the
// top-level resolution we need for the worktree path.
const rawRepoRoot = await probe.getRepoTopLevel();
if (rawRepoRoot === null) {
return {
ok: false,
error: `--worktree: ${launchCwd} is not a git repository. Run \`git init\` first or relaunch from inside one.`,
};
}
// git always emits POSIX-style paths (forward slashes) via
// `--show-toplevel`. Normalize to the platform-native separator
// before storing or comparing so the sidecar's `originalCwd` and
// downstream `startsWith` checks don't mix `/` and `\` on Windows.
const repoRoot = path.resolve(rawRepoRoot);
const service =
repoRoot === launchCwd ? probe : new GitWorktreeService(repoRoot);
// Resolve slug. Branch on PR reference first so `#123` / URLs don't fall
// through to slug validation (which would reject `#`). For PR refs we
// DEFER the fetch until we've checked whether the worktree already
// exists on disk — re-attach skips the fetch since the ref was
// materialized on the first run.
const prNumber = GitWorktreeService.parsePRReference(trimmed);
const isPullRequest = prNumber !== null;
let slug: string;
if (prNumber !== null) {
slug = `pr-${prNumber}`;
} else if (trimmed.length === 0) {
slug = GitWorktreeService.generateAutoSlug();
} else {
const validation = GitWorktreeService.validateUserWorktreeSlug(trimmed);
if (validation) {
return { ok: false, error: `--worktree: ${validation}` };
}
slug = trimmed;
}
// Capture the launch-time branch and HEAD. These feed the WorktreeSession
// sidecar's `originalBranch` / `originalHeadCommit` fields when we go
// through the CREATE path; on re-attach the HEAD baseline is re-captured
// from inside the worktree itself (see the re-attach branch below) so
// `WorktreeExitDialog`'s `rev-list <originalHeadCommit>..HEAD` counts
// only this session's new commits — not every commit the kept worktree
// accumulated across prior sessions.
//
// The two probes are independent — run in parallel to shave one
// subprocess off the critical path. Each is individually try-wrapped
// so a failure in one (unborn HEAD, partial init) doesn't poison
// the other. Detached-HEAD normalization via DETACHED_HEAD const.
const [originalBranchRaw, originalHeadCommit] = await Promise.all([
service.getCurrentBranch().catch(() => undefined),
service.getCurrentCommitHash().catch(() => ''),
]);
const originalBranch =
originalBranchRaw && originalBranchRaw !== DETACHED_HEAD
? originalBranchRaw
: undefined;
// Re-attach to an existing worktree instead of erroring out. Common
// case: user did `qwen --worktree foo` previously, exited with Keep,
// and now runs `qwen --resume <sid> --worktree foo` to continue. The
// directory + branch are already on disk; we just chdir into them.
//
// `getRegisteredWorktreeBranch` returns the worktree's HEAD commit
// alongside the branch (single rev-parse). Using THAT as
// `originalHeadCommit` instead of the launch-cwd capture is critical:
// `WorktreeExitDialog` later runs `rev-list <head>..HEAD` inside the
// worktree, so the launch-cwd HEAD would make it count every commit
// accumulated in the worktree across all prior sessions as "new work
// this session".
const expectedWorktreePath = service.getUserWorktreePath(slug);
const expectedBranch = worktreeBranchForSlug(slug);
let registered: { branch: string; headCommit: string } | null = null;
try {
registered =
await service.getRegisteredWorktreeBranch(expectedWorktreePath);
} catch {
registered = null;
}
if (registered !== null) {
if (registered.branch !== expectedBranch) {
// SOMETHING ELSE is occupying the path on a different branch —
// refuse to clobber it.
return {
ok: false,
error:
`--worktree: ${expectedWorktreePath} is already a git worktree, but its branch ` +
`is ${registered.branch} (expected ${expectedBranch}). Refusing to re-attach. ` +
`Resolve the conflict manually (e.g. \`git worktree remove ${expectedWorktreePath}\`).`,
};
}
const worktreePath = path.resolve(expectedWorktreePath);
try {
process.chdir(worktreePath);
} catch (error) {
return {
ok: false,
error: `--worktree: failed to chdir into ${worktreePath} (${error instanceof Error ? error.message : String(error)}).`,
};
}
debugLogger.debug(
`setupStartupWorktree: re-attached to existing worktree at ${worktreePath} (branch=${registered.branch})`,
);
return {
ok: true,
context: {
worktreePath,
slug,
branch: registered.branch,
repoRoot,
originalBranch: originalBranch ?? DETACHED_HEAD,
originalHeadCommit: registered.headCommit,
isPullRequest,
wasReattached: true,
},
};
}
// Phase D-3: fetch the PR ref BEFORE creating the worktree, so the
// base ref (FETCH_HEAD) is available to `git worktree add`. Skipped
// on re-attach above. Fail-close: any fetch error stops startup before
// we create disk state.
//
// Lock FETCH_HEAD to an immutable SHA *immediately* after the fetch:
// - closes a TOCTOU window in which a concurrent `git fetch` from
// any other process sharing this repo would overwrite FETCH_HEAD
// before `git worktree add` reads it, branching the new worktree
// off an unrelated commit;
// - lets us pass that same SHA back as `originalHeadCommit`, so
// `WorktreeExitDialog`'s `rev-list <head>..HEAD` later inside the
// worktree counts only the user's own new commits — not the
// entire fetched PR's history.
let pullRequestHeadSha: string | null = null;
if (prNumber !== null) {
const fetchRes = await service.fetchPullRequestRef(prNumber);
if (!fetchRes.success) {
return { ok: false, error: `--worktree: ${fetchRes.error}` };
}
pullRequestHeadSha = await service.resolveRef('FETCH_HEAD');
if (pullRequestHeadSha === null) {
return {
ok: false,
error: `--worktree: fetched PR #${prNumber} but FETCH_HEAD did not resolve to a commit SHA. Refusing to proceed (the worktree would otherwise branch off an unknown commit).`,
};
}
}
// For PR worktrees the base ref is the SHA we just locked in (NOT the
// literal `FETCH_HEAD`, which is mutable); for regular slugs we anchor
// at the parent session's currently checked-out branch.
const baseRef = isPullRequest ? pullRequestHeadSha! : originalBranch;
const result = await service.createUserWorktree(slug, baseRef, {
symlinkDirectories: options?.symlinkDirectories,
});
if (!result.success || !result.worktree) {
return {
ok: false,
error: `--worktree: ${result.error ?? 'failed to create worktree.'}`,
};
}
// Switch the process working directory so loadCliConfig() picks up the
// worktree as targetDir, and subsequent shell / file operations land
// inside it. Mirror the convention used elsewhere in the codebase by
// working with the resolved absolute path.
const worktreePath = path.resolve(result.worktree.path);
try {
process.chdir(worktreePath);
} catch (error) {
return {
ok: false,
error: `--worktree: created worktree at ${worktreePath} but failed to chdir into it (${error instanceof Error ? error.message : String(error)}). Run \`cd ${worktreePath}\` manually.`,
};
}
return {
ok: true,
context: {
worktreePath,
slug,
branch: result.worktree.branch,
repoRoot,
originalBranch: originalBranch ?? DETACHED_HEAD,
// For PR worktrees, the worktree's HEAD starts at the fetched PR
// tip — not at the parent repo's HEAD. Use the SHA we locked in
// post-fetch so the exit-dialog rev-list counts only the user's
// new commits, not the entire PR history.
originalHeadCommit: isPullRequest
? pullRequestHeadSha!
: originalHeadCommit,
isPullRequest,
wasReattached: false,
},
};
}
/**
* Result of the post-`loadCliConfig` sidecar persist step. Callers use the
* boolean fields to decide whether to surface an INFO line in TUI / a
* `<system-reminder>` in headless / a `pendingWorktreeNotice` in ACP.
*/
export interface PersistStartupWorktreeResult {
/** True when a pre-existing sidecar was found and overridden. */
overrodeResumedWorktree: boolean;
/**
* Slug of the worktree that was overridden, when {@link overrodeResumedWorktree}
* is true. Used in the INFO message so users can re-attach to it if they
* launched with `--worktree` by mistake.
*/
overriddenSlug?: string;
/** Path to the sidecar file just written. */
sidecarPath: string;
}
/**
* Writes the `WorktreeSession` sidecar that Phase C's `--resume` restore
* machinery consumes, and tags the worktree directory with the current
* session ID so cross-session `exit_worktree action="remove"` is refused.
*
* Handles the `--worktree` × `--resume` precedence: when a sidecar already
* exists (the user resumed a session that previously had a different
* worktree), the new context wins and the previous slug is reported back
* so callers can show an INFO line.
*/
export async function persistStartupWorktreeSidecar(
config: Config,
context: StartupWorktreeContext,
): Promise<PersistStartupWorktreeResult> {
const sessionId = config.getSessionId();
const sidecarPath = config
.getSessionService()
.getWorktreeSessionPath(sessionId);
// Read whatever sidecar exists before we clobber it, so we can detect
// and report an override. A read failure (corrupt JSON, permission)
// collapses to "no previous worktree" — the new sidecar still wins.
// Log the failure with the sidecar path so an operator can recover the
// previous slug from a backup if they care; silent loss would make
// "where did my previous worktree binding go?" undebuggable.
let overrodeResumedWorktree = false;
let overriddenSlug: string | undefined;
let previous: WorktreeSession | null = null;
try {
previous = await readWorktreeSession(sidecarPath);
} catch (error) {
debugLogger.warn(
`persistStartupWorktreeSidecar: failed to read existing sidecar at ${sidecarPath} — treating as "no previous worktree" and proceeding: ${error}`,
);
previous = null;
}
if (previous && previous.slug !== context.slug) {
overrodeResumedWorktree = true;
overriddenSlug = previous.slug;
}
// Best-effort marker write — same policy as EnterWorktreeTool: a failure
// here does not abort the session, the worktree is usable, ownership
// checks just treat the worktree as "owner unknown" for future
// exit_worktree calls.
//
// SKIP on re-attach: the marker was written by whichever session
// ORIGINALLY created this worktree. Overwriting with the current
// session id would let `exit_worktree action="remove"` succeed across
// sessions, bypassing Phase A's cross-session ownership guard. The
// existing marker stays so the original owner remains canonical; the
// current session can still operate INSIDE the worktree (file ops,
// commits) — ownership only governs the destructive remove.
if (!context.wasReattached) {
await writeWorktreeSessionMarker(context.worktreePath, sessionId).catch(
() => {},
);
}
await writeWorktreeSession(sidecarPath, {
slug: context.slug,
worktreePath: context.worktreePath,
worktreeBranch: context.branch,
originalCwd: context.repoRoot,
originalBranch: context.originalBranch,
originalHeadCommit: context.originalHeadCommit,
});
// The previous worktree directory (if any) is intentionally left on
// disk — the user retains the ability to re-attach by launching again
// with `--worktree <previous-slug>`. We only swap the sidecar's slug.
return { overrodeResumedWorktree, overriddenSlug, sidecarPath };
}
/**
* Builds the one-shot context message that gets injected into the model on
* the first user prompt (TUI: INFO history item + reminder prefix; headless:
* `<system-reminder>` prefix + JSON event; ACP currently exits before
* reaching this code path — see the `--worktree` × `--acp` mutex check
* in `gemini.tsx`).
*
* Mirrors `restoreWorktreeContext`'s contextMessage shape so resumed-with-
* worktree and started-with-worktree sessions read identically to the model.
*
* Differentiates the verb based on whether the worktree was just created
* or the CLI re-attached to a pre-existing one — same slug + branch but
* meaningfully different user intent. The override addendum (when
* `--worktree` clobbered a resumed session's prior worktree) is shown
* regardless of created/reattached state.
*
* Parameter type is `Pick<StartupWorktreeContext, …>` rather than the full
* context so test fixtures can construct minimal literals without
* tracking every internal field. Adding fields to {@link
* StartupWorktreeContext} should NOT force test-fixture churn here.
*/
export function buildStartupWorktreeNotice(
context: Pick<
StartupWorktreeContext,
'slug' | 'worktreePath' | 'branch' | 'wasReattached'
>,
override?: PersistStartupWorktreeResult,
): string {
const verb = context.wasReattached
? 'Re-attached to worktree'
: 'Active worktree';
const base =
`[Startup] ${verb}: "${context.slug}" at ${context.worktreePath} ` +
`(branch: ${context.branch}). Continue using this path for all file operations.`;
if (override?.overrodeResumedWorktree && override.overriddenSlug) {
return (
`${base}\n` +
`Note: --worktree overrode the resumed session's previous worktree "${override.overriddenSlug}". ` +
`That worktree directory was left intact; re-attach with \`qwen --worktree ${override.overriddenSlug}\` if needed.`
);
}
return base;
}

View File

@ -14,6 +14,8 @@ import {
type UIActions,
} from './contexts/UIActionsContext.js';
import { AgentViewProvider } from './contexts/AgentViewContext.js';
import { SettingsContext } from './contexts/SettingsContext.js';
import type { LoadedSettings } from '../config/settings.js';
import { StreamingState } from './types.js';
vi.mock('ink', async (importOriginal) => {
@ -65,9 +67,16 @@ describe('App', () => {
updateItem: vi.fn(),
clearItems: vi.fn(),
loadHistory: vi.fn(),
truncateToItem: vi.fn(),
},
};
const mockSettings = {
merged: {},
corruptedPath: undefined,
wasRecovered: false,
} as LoadedSettings;
const mockUIActions = {
refreshStatic: vi.fn(),
} as unknown as UIActions;
@ -77,7 +86,9 @@ describe('App', () => {
<UIActionsContext.Provider value={mockUIActions}>
<AgentViewProvider>
<UIStateContext.Provider value={uiState}>
<App />
<SettingsContext.Provider value={mockSettings}>
<App />
</SettingsContext.Provider>
</UIStateContext.Provider>
</AgentViewProvider>
</UIActionsContext.Provider>,

View File

@ -4,21 +4,87 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { useIsScreenReaderEnabled } from 'ink';
import { useState } from 'react';
import { Box, useIsScreenReaderEnabled } from 'ink';
import { useUIState } from './contexts/UIStateContext.js';
import { useSettings } from './contexts/SettingsContext.js';
import { CORRUPTED_SUFFIX } from '../config/settings.js';
import { writeStderrLine } from '../utils/stdioHelpers.js';
import { StreamingContext } from './contexts/StreamingContext.js';
import { QuittingDisplay } from './components/QuittingDisplay.js';
import { SettingsCorruptedDialog } from './components/SettingsCorruptedDialog.js';
import { ScreenReaderAppLayout } from './layouts/ScreenReaderAppLayout.js';
import { DefaultAppLayout } from './layouts/DefaultAppLayout.js';
import fs from 'node:fs';
export const App = () => {
const uiState = useUIState();
const settings = useSettings();
const isScreenReaderEnabled = useIsScreenReaderEnabled();
const [dismissed, setDismissed] = useState(false);
if (uiState.quittingMessages) {
return <QuittingDisplay />;
}
// Render corrupted dialog at the top level, before any other UI
if (settings.corruptedPath && !dismissed) {
return (
<StreamingContext.Provider value={uiState.streamingState}>
<Box marginX={2}>
<SettingsCorruptedDialog
corruptedPath={settings.corruptedPath}
wasRecovered={settings.wasRecovered}
onExit={() => {
if (
settings.corruptedPath &&
fs.existsSync(settings.corruptedPath)
) {
try {
const settingsPath = settings.corruptedPath.slice(
0,
-CORRUPTED_SUFFIX.length,
);
fs.copyFileSync(settings.corruptedPath, settingsPath);
} catch (e) {
writeStderrLine(
`Failed to restore corrupted file: ${e instanceof Error ? e.message : String(e)}`,
);
process.exit(1);
return;
}
try {
fs.unlinkSync(settings.corruptedPath);
} catch (e) {
writeStderrLine(
`Settings restored, but could not remove ${settings.corruptedPath}: ${e instanceof Error ? e.message : String(e)}`,
);
}
}
process.exit(1);
}}
onContinue={() => {
if (
settings.corruptedPath &&
fs.existsSync(settings.corruptedPath)
) {
try {
fs.unlinkSync(settings.corruptedPath);
} catch (e) {
writeStderrLine(
`Could not remove ${settings.corruptedPath}: ${e instanceof Error ? e.message : String(e)}`,
);
}
}
settings.corruptionDialogDismissed = true;
setDismissed(true);
}}
/>
</Box>
</StreamingContext.Provider>
);
}
return (
<StreamingContext.Provider value={uiState.streamingState}>
{isScreenReaderEnabled ? <ScreenReaderAppLayout /> : <DefaultAppLayout />}

View File

@ -519,6 +519,21 @@ export const AppContainer = (props: AppContainerProps) => {
// the profile captures the full MCP timeline without holding back
// the user-facing TTI.
// Phase D-1: when launched with --worktree, gemini.tsx stashes a
// one-shot notice on Config. Consume it here so it surfaces in the
// transcript AND gets injected into the next user prompt. This
// wins over the Phase C resume-restore path below — startup beats
// resume on the same prompt.
const startupWorktreeNotice =
config.consumePendingStartupWorktreeNotice();
if (startupWorktreeNotice) {
historyManager.addItem(
{ type: MessageType.INFO, text: startupWorktreeNotice },
Date.now(),
);
pendingWorktreeNoticeRef.current = startupWorktreeNotice;
}
const resumedSessionData = config.getResumedSessionData();
if (resumedSessionData) {
const historyItems = buildResumedHistoryItems(
@ -560,32 +575,39 @@ export const AppContainer = (props: AppContainerProps) => {
// Restore worktree context (shared logic — headless and ACP use
// the same helper). Stale sidecars get cleaned up; live ones
// produce an INFO message the model sees on the next turn.
try {
const sessionPath = config
.getSessionService()
.getWorktreeSessionPath(config.getSessionId());
const restored = await restoreWorktreeContext(sessionPath, (err) => {
// eslint-disable-next-line no-console
console.debug('worktree session restore warning:', err);
});
if (restored.contextMessage) {
// UI: show the notice in the transcript so the user knows.
historyManager.addItem(
{ type: MessageType.INFO, text: restored.contextMessage },
Date.now(),
// Skipped when Phase D-1 already injected a --worktree startup
// notice above (startup wins over resume on the same prompt).
if (!startupWorktreeNotice) {
try {
const sessionPath = config
.getSessionService()
.getWorktreeSessionPath(config.getSessionId());
const restored = await restoreWorktreeContext(
sessionPath,
(err) => {
// eslint-disable-next-line no-console
console.debug('worktree session restore warning:', err);
},
);
// Model: queue the notice for one-shot injection into the
// next user prompt (consumed by handleFinalSubmit). The INFO
// history item alone is UI-only — the model never sees it,
// so without this it could resume editing the parent
// checkout despite the user seeing the worktree path.
pendingWorktreeNoticeRef.current = restored.contextMessage;
if (restored.contextMessage) {
// UI: show the notice in the transcript so the user knows.
historyManager.addItem(
{ type: MessageType.INFO, text: restored.contextMessage },
Date.now(),
);
// Model: queue the notice for one-shot injection into the
// next user prompt (consumed by handleFinalSubmit). The INFO
// history item alone is UI-only — the model never sees it,
// so without this it could resume editing the parent
// checkout despite the user seeing the worktree path.
pendingWorktreeNoticeRef.current = restored.contextMessage;
}
} catch (error) {
// Best-effort: failures here only affect UI hint visibility,
// not the resumed conversation itself.
// eslint-disable-next-line no-console
console.debug('worktree session restore failed:', error);
}
} catch (error) {
// Best-effort: failures here only affect UI hint visibility,
// not the resumed conversation itself.
// eslint-disable-next-line no-console
console.debug('worktree session restore failed:', error);
}
}
})();
@ -1152,6 +1174,7 @@ export const AppContainer = (props: AppContainerProps) => {
extensionsUpdateStateInternal,
isConfigInitialized,
logger,
historyManager.updateItem,
setSessionName,
);
@ -2085,10 +2108,9 @@ export const AppContainer = (props: AppContainerProps) => {
const ac = new AbortController();
suggestionAbortRef.current = ac;
// Use curated history to avoid invalid/empty entries causing API errors
const fullHistory = geminiClient.getChat().getHistory(true);
const conversationHistory =
fullHistory.length > 40 ? fullHistory.slice(-40) : fullHistory;
// Only clone the tail — full structuredClone of a large resumed session
// causes transient heap peaks that trigger OOM (#4624).
const conversationHistory = geminiClient.getHistoryTail(40, true);
generatePromptSuggestion(config, conversationHistory, ac.signal, {
enableCacheSharing: settings.merged.ui?.enableCacheSharing === true,
})
@ -2281,7 +2303,8 @@ export const AppContainer = (props: AppContainerProps) => {
isRewindSelectorOpen ||
isDiffDialogOpen ||
bgTasksDialogOpen ||
showWorktreeExitDialog;
showWorktreeExitDialog ||
!!(settings.corruptedPath && !settings.corruptionDialogDismissed);
dialogsVisibleRef.current = dialogsVisible;
const shouldShowStickyTodos =
stickyTodos !== null &&
@ -2440,7 +2463,7 @@ export const AppContainer = (props: AppContainerProps) => {
apiTruncateIndex = computeApiTruncationIndex(
historyManager.history,
userItem.id,
geminiClient.getHistory(),
geminiClient.getHistoryShallow(),
);
if (apiTruncateIndex < 0) {
historyManager.addItem(

View File

@ -20,7 +20,7 @@ import type { LoadedSettings } from '../../config/settings.js';
import { createLoadedSettingsAdapter } from '../../config/loadedSettingsAdapter.js';
import { useQwenAuth } from '../hooks/useQwenAuth.js';
import { AuthState, MessageType } from '../types.js';
import type { HistoryItem } from '../types.js';
import type { HistoryItemWithoutId } from '../types.js';
import { t } from '../../i18n/index.js';
/**
@ -81,7 +81,7 @@ export type AuthController = {
export const useAuthCommand = (
settings: LoadedSettings,
config: Config,
addItem: (item: Omit<HistoryItem, 'id'>, timestamp: number) => void,
addItem: (item: HistoryItemWithoutId, timestamp: number) => void,
onAuthChange?: () => void,
) => {
const unAuthenticated = config.getAuthType() === undefined;

View File

@ -176,6 +176,11 @@ describe('btwCommand', () => {
.mockReturnValue([
{ role: 'user', parts: [{ text: '杭州天气如何?' }] },
]),
getHistoryTail: vi
.fn()
.mockReturnValue([
{ role: 'user', parts: [{ text: '杭州天气如何?' }] },
]),
getChat: vi.fn().mockReturnValue({
getGenerationConfig: vi.fn().mockReturnValue({
systemInstruction: 'You are helpful',
@ -229,6 +234,10 @@ describe('btwCommand', () => {
{ role: 'user', parts: [{ text: '杭州天气如何?' }] },
{ role: 'user', parts: [{ text: '请顺便解释一下湿度怎么看' }] },
]),
getHistoryTail: vi.fn().mockReturnValue([
{ role: 'user', parts: [{ text: '杭州天气如何?' }] },
{ role: 'user', parts: [{ text: '请顺便解释一下湿度怎么看' }] },
]),
getChat: vi.fn().mockReturnValue({
getGenerationConfig: vi.fn().mockReturnValue({
systemInstruction: 'live system prompt',

View File

@ -55,7 +55,7 @@ function getBtwCacheSafeParams(
geminiClient &&
typeof geminiClient === 'object' &&
typeof geminiClient.getChat === 'function' &&
typeof geminiClient.getHistory === 'function'
typeof geminiClient.getHistoryTail === 'function'
) {
const chat = geminiClient.getChat();
if (
@ -65,12 +65,7 @@ function getBtwCacheSafeParams(
) {
const generationConfig = chat.getGenerationConfig();
if (generationConfig) {
const fullHistory = geminiClient.getHistory(true);
const maxHistoryEntries = 40;
const history =
fullHistory.length > maxHistoryEntries
? fullHistory.slice(-maxHistoryEntries)
: fullHistory;
const history = geminiClient.getHistoryTail(40, true);
return {
generationConfig,

View File

@ -77,20 +77,60 @@ describe('collectContextData (contextCommand)', () => {
} as unknown as Config;
});
it('passes includeDeferred: true to getFunctionDeclarations', async () => {
// Pin the token-accounting invariant: the "all tools" total must
// line up with the per-tool breakdown (which iterates getAllTools
// unfiltered). Without `includeDeferred: true`, the total would
// exclude deferred tools while the per-tool sum still includes
// them — `displayBuiltinTools` (clamped Math.max(0, …)) would then
// collapse to 0 instead of reporting the real cost. A user-visible
// regression caught only by visual inspection of `/context detail`.
it('queries getFunctionDeclarations with no args, matching the actual API request', async () => {
// /context should reflect what's actually sent to the model. Deferred
// tools (MCP tools default to shouldDefer=true) are excluded from the
// prompt unless ToolSearch has revealed them this session — see
// client.ts which calls getFunctionDeclarations() with no options.
// Pinning the call here keeps the /context token estimate aligned with
// the real request, instead of overcounting by the full MCP tool pool.
await collectContextData(mockConfig, false);
expect(getFunctionDeclarationsSpy).toHaveBeenCalledTimes(1);
expect(getFunctionDeclarationsSpy).toHaveBeenCalledWith({
includeDeferred: true,
});
expect(getFunctionDeclarationsSpy).toHaveBeenCalledWith();
});
it('excludes deferred-but-not-revealed tools from the per-tool breakdown (#4508)', async () => {
// Regression: /context used to surface every deferred tool (MCP tools,
// plus low-frequency built-ins like web_fetch / monitor / cron_*) even
// when ToolSearch had not loaded any of them, inflating the displayed
// token count for the common default-on case.
const isDeferredToolRevealed = vi.fn().mockReturnValue(false);
const hiddenBuiltin = {
name: 'web_fetch',
schema: { name: 'web_fetch', description: 'large schema' },
shouldDefer: true,
alwaysLoad: false,
};
const hiddenMcp = {
name: 'mcp__server__tool',
schema: { name: 'mcp__server__tool', description: 'large schema' },
shouldDefer: true,
alwaysLoad: false,
};
const config = {
getModel: vi.fn().mockReturnValue('test-model'),
getContentGeneratorConfig: vi.fn().mockReturnValue({
contextWindowSize: 32_000,
}),
getToolRegistry: vi.fn().mockReturnValue({
getAllTools: vi.fn().mockReturnValue([hiddenBuiltin, hiddenMcp]),
getFunctionDeclarations: vi.fn().mockReturnValue([]),
isDeferredToolRevealed,
}),
getUserMemory: vi.fn().mockReturnValue(''),
getSkillManager: vi.fn().mockReturnValue({
listSkills: vi.fn().mockResolvedValue([]),
}),
getChatCompression: vi.fn().mockReturnValue(undefined),
} as unknown as Config;
const data = await collectContextData(config, true);
expect(data.builtinTools).toHaveLength(0);
expect(data.mcpTools).toHaveLength(0);
expect(isDeferredToolRevealed).toHaveBeenCalledWith('web_fetch');
expect(isDeferredToolRevealed).toHaveBeenCalledWith('mcp__server__tool');
});
});

View File

@ -116,13 +116,14 @@ export async function collectContextData(
const toolRegistry = config.getToolRegistry();
const allTools = toolRegistry ? toolRegistry.getAllTools() : [];
// Pass includeDeferred so this token estimate lines up with the per-tool
// breakdown below (which iterates getAllTools, unfiltered). Without it the
// "all tools" total would exclude deferred tools while the per-tool sum
// still includes them, and displayBuiltinTools = total - mcp would go
// negative.
// Match what's actually sent to the model: deferred tools — MCP tools and
// low-frequency built-ins like web_fetch / monitor / cron_* — are absent
// from the prompt unless ToolSearch has revealed them this session. See
// client.ts which calls getFunctionDeclarations() with no args. The
// per-tool loop below applies the same filter so allToolsTokens stays
// aligned with the breakdown sum.
const toolDeclarations = toolRegistry
? toolRegistry.getFunctionDeclarations({ includeDeferred: true })
? toolRegistry.getFunctionDeclarations()
: [];
const toolsJsonStr = JSON.stringify(toolDeclarations);
const allToolsTokens = estimateTokens(toolsJsonStr);
@ -130,6 +131,13 @@ export async function collectContextData(
const builtinTools: ContextToolDetail[] = [];
const mcpTools: ContextToolDetail[] = [];
for (const tool of allTools) {
if (
tool.shouldDefer &&
!tool.alwaysLoad &&
!toolRegistry?.isDeferredToolRevealed(tool.name)
) {
continue;
}
const toolJsonStr = JSON.stringify(tool.schema);
const tokens = estimateTokens(toolJsonStr);
if (tool instanceof DiscoveredMCPTool) {

View File

@ -351,10 +351,7 @@ describe('getDirPathCompletions', () => {
fs.mkdirSync(path.join(tempTestDir, 'sub1', 'deep'), { recursive: true });
// Add some non-directory files (should be filtered out)
fs.writeFileSync(path.join(tempTestDir, 'file.txt'), '');
fs.writeFileSync(
path.join(tempTestDir, 'sub1', 'nested.txt'),
'',
);
fs.writeFileSync(path.join(tempTestDir, 'sub1', 'nested.txt'), '');
});
afterAll(() => {

View File

@ -4,7 +4,11 @@
* SPDX-License-Identifier: Apache-2.0
*/
import type { SlashCommand, CommandContext, CommandCompletionItem } from './types.js';
import type {
SlashCommand,
CommandContext,
CommandCompletionItem,
} from './types.js';
import { CommandKind } from './types.js';
import { MessageType } from '../types.js';
import * as fs from 'node:fs';
@ -58,7 +62,9 @@ function findExistingWorkspaceDirectory(
* Returns directory path completions for the given partial argument.
* Supports comma-separated paths by completing only the last segment.
*/
export function getDirPathCompletions(partialArg: string): CommandCompletionItem[] {
export function getDirPathCompletions(
partialArg: string,
): CommandCompletionItem[] {
const lastComma = partialArg.lastIndexOf(',');
const prefix = lastComma >= 0 ? partialArg.substring(0, lastComma + 1) : '';
const partial =

View File

@ -17,7 +17,6 @@ describe('hooksCommand', () => {
beforeEach(() => {
vi.clearAllMocks();
// Create mock config with hook system
mockConfig = {
getHookSystem: vi.fn().mockReturnValue({
getRegistry: vi.fn().mockReturnValue({
@ -69,4 +68,173 @@ describe('hooksCommand', () => {
});
});
});
describe('non-interactive list output', () => {
function makeContext(opts: {
configHooks: Array<{
eventName: string;
matcher?: string;
source: string;
config: {
type: string;
command?: string;
url?: string;
name?: string;
};
}>;
sessionHooks?: Array<{
eventName: string;
matcher?: string;
config: { type: string; command?: string; name?: string };
}>;
}) {
const sessionConfig = {
getHookSystem: vi.fn().mockReturnValue({
getRegistry: vi.fn().mockReturnValue({
getAllHooks: vi.fn().mockReturnValue(opts.configHooks),
}),
getSessionHooksManager: vi.fn().mockReturnValue({
getAllSessionHooks: vi
.fn()
.mockReturnValue(opts.sessionHooks ?? []),
}),
}),
getSessionId: vi.fn().mockReturnValue('sid'),
};
return createMockCommandContext({
executionMode: 'non_interactive',
services: { config: sessionConfig },
});
}
it('groups hooks under matcher headings', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'PreToolUse',
matcher: 'Bash',
source: 'user',
config: { type: 'command', command: '/check-bash.sh' },
},
{
eventName: 'PreToolUse',
matcher: 'Edit|Write',
source: 'project',
config: { type: 'command', command: '/format.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
expect(result).toBeDefined();
const content = (result as { content: string }).content;
expect(content).toContain('### PreToolUse');
expect(content).toContain('#### Matcher: Bash');
expect(content).toContain('/check-bash.sh');
expect(content).toContain('#### Matcher: Edit|Write');
expect(content).toContain('/format.sh');
});
it('renders missing matcher as *', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'PreToolUse',
source: 'user',
config: { type: 'command', command: '/anything.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
const content = (result as { content: string }).content;
expect(content).toContain('#### Matcher: *');
expect(content).toContain('/anything.sh');
});
it('does not emit a Matcher heading for non-matcher events like Stop', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'Stop',
source: 'user',
config: { type: 'command', command: '/stop-hook.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
const content = (result as { content: string }).content;
expect(content).toContain('### Stop');
expect(content).not.toContain('Matcher:');
expect(content).toContain('/stop-hook.sh');
});
it('preserves registration order for non-matcher events with ignored matchers', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'Stop',
matcher: 'A',
source: 'user',
config: { type: 'command', command: '/first.sh' },
},
{
eventName: 'Stop',
matcher: 'B',
source: 'user',
config: { type: 'command', command: '/second.sh' },
},
{
eventName: 'Stop',
matcher: 'A',
source: 'user',
config: { type: 'command', command: '/third.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
const content = (result as { content: string }).content;
expect(content).not.toContain('Matcher:');
expect(content.indexOf('/first.sh')).toBeLessThan(
content.indexOf('/second.sh'),
);
expect(content.indexOf('/second.sh')).toBeLessThan(
content.indexOf('/third.sh'),
);
});
it('groups session hooks by their matcher alongside config hooks', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'PreToolUse',
matcher: 'Bash',
source: 'user',
config: { type: 'command', command: '/persistent.sh' },
},
],
sessionHooks: [
{
eventName: 'PreToolUse',
matcher: 'Bash',
config: { type: 'command', command: '/session.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
const content = (result as { content: string }).content;
const matcherOccurrences = content.match(/#### Matcher: Bash/g) ?? [];
expect(matcherOccurrences).toHaveLength(1);
expect(content).toContain('/persistent.sh');
expect(content).toContain('/session.sh');
});
});
});

Some files were not shown because too many files have changed in this diff Show More