Compare commits

..

18 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
105 changed files with 8941 additions and 1471 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

@ -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

@ -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

@ -196,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(),
@ -329,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);
@ -348,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);
@ -356,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',
@ -853,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
@ -1207,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
@ -1523,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())
@ -1584,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())
@ -1655,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());
@ -2405,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([
@ -2458,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());
@ -2503,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

@ -402,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,
@ -895,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,

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

@ -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,11 +1999,11 @@ 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();
});
@ -2017,19 +2024,111 @@ describe('Settings Loading and Merging', () => {
const result = loadSettings(MOCK_WORKSPACE_DIR);
const warnings = getSettingsWarnings(result);
// Warnings must be non-empty so the early stderr loop in gemini.tsx
// (before relaunchAppInChildProcess) actually emits something.
expect(warnings.length).toBeGreaterThan(0);
// Each warning should be a human-readable string suitable for stderr
for (const w of warnings) {
expect(typeof w).toBe('string');
expect(w.length).toBeGreaterThan(0);
}
expect(warnings.some((w) => w.includes('invalid JSON'))).toBe(true);
// 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 = {
@ -2176,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 = {

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;
@ -499,6 +516,8 @@ export function createMinimalSettings(): LoadedSettings {
false,
new Set(),
[],
undefined,
false,
);
}
@ -597,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
@ -804,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
@ -851,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(
@ -872,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 (
@ -953,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) {
@ -962,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;
@ -972,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({
@ -1033,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') {
@ -1122,6 +1262,8 @@ export function loadSettings(
isTrusted,
migratedInMemorScopes,
allMigrationWarnings,
userResult.corruptedPath,
userResult.wasRecovered ?? false,
);
}

View File

@ -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,
@ -105,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 {
@ -330,13 +337,13 @@ export async function startInteractiveUI(
<VimModeProvider settings={settings}>
<AgentViewProvider config={config}>
<BackgroundTaskViewProvider config={config}>
<AppContainer
config={config}
settings={settings}
startupWarnings={startupWarnings}
version={version}
initializationResult={initializationResult}
/>
<AppContainer
config={config}
settings={settings}
startupWarnings={startupWarnings}
version={version}
initializationResult={initializationResult}
/>
</BackgroundTaskViewProvider>
</AgentViewProvider>
</VimModeProvider>
@ -427,10 +434,19 @@ 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
@ -440,6 +456,15 @@ export async function main() {
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) {
@ -594,7 +619,9 @@ 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,
});
}
}
@ -955,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.

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

@ -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

@ -2108,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,
})
@ -2304,7 +2303,8 @@ export const AppContainer = (props: AppContainerProps) => {
isRewindSelectorOpen ||
isDiffDialogOpen ||
bgTasksDialogOpen ||
showWorktreeExitDialog;
showWorktreeExitDialog ||
!!(settings.corruptedPath && !settings.corruptionDialogDismissed);
dialogsVisibleRef.current = dialogsVisible;
const shouldShowStickyTodos =
stickyTodos !== null &&
@ -2463,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

@ -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

@ -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');
});
});
});

View File

@ -15,7 +15,10 @@ import { t } from '../../i18n/index.js';
import type {
HookRegistryEntry,
SessionHookEntry,
HookEventName,
} from '@qwen-code/qwen-code-core';
import { supportsMatchers } from '../components/hooks/constants.js';
import { normalizeMatcher } from '../components/hooks/matcherGrouping.js';
/**
* Format hook source for display
@ -71,7 +74,6 @@ const listCommand: SlashCommand = {
const registry = hookSystem.getRegistry();
const configHooks = registry.getAllHooks();
// Get session hooks
const sessionId = config.getSessionId();
const sessionHooksManager = hookSystem.getSessionHooksManager();
const sessionHooks = sessionId
@ -90,86 +92,94 @@ const listCommand: SlashCommand = {
};
}
// Group hooks by event
const hooksByEvent = new Map<
string,
Array<{ hook: HookRegistryEntry | SessionHookEntry; isSession: boolean }>
>();
// Add config hooks
for (const hook of configHooks) {
const eventName = hook.eventName;
if (!hooksByEvent.has(eventName)) {
hooksByEvent.set(eventName, []);
}
hooksByEvent.get(eventName)!.push({ hook, isSession: false });
interface FlattenedHook {
name: string;
source: string;
}
// Add session hooks
for (const hook of sessionHooks) {
const eventName = hook.eventName;
if (!hooksByEvent.has(eventName)) {
hooksByEvent.set(eventName, []);
const hooksByEvent = new Map<string, Map<string, FlattenedHook[]>>();
const addHook = (
eventName: string,
matcher: string,
hook: FlattenedHook,
): void => {
const matcherKey = supportsMatchers(eventName as HookEventName)
? matcher
: '*';
let matcherMap = hooksByEvent.get(eventName);
if (!matcherMap) {
matcherMap = new Map<string, FlattenedHook[]>();
hooksByEvent.set(eventName, matcherMap);
}
hooksByEvent.get(eventName)!.push({ hook, isSession: true });
let bucket = matcherMap.get(matcherKey);
if (!bucket) {
bucket = [];
matcherMap.set(matcherKey, bucket);
}
bucket.push(hook);
};
const extractName = (config: {
type: string;
command?: string;
url?: string;
name?: string;
}): string =>
config.name ||
(config.type === 'command' ? config.command : undefined) ||
(config.type === 'http' ? config.url : undefined) ||
'unnamed';
for (const hook of configHooks) {
const configHook = hook as HookRegistryEntry;
const config = configHook.config as {
type: string;
command?: string;
url?: string;
name?: string;
};
addHook(configHook.eventName, normalizeMatcher(configHook.matcher), {
name: extractName(config),
source: formatHookSource(configHook.source),
});
}
for (const hook of sessionHooks) {
const sessionHook = hook as SessionHookEntry;
const config = sessionHook.config as {
type: string;
command?: string;
url?: string;
name?: string;
};
addHook(sessionHook.eventName, normalizeMatcher(sessionHook.matcher), {
name: extractName(config),
source: formatHookSource('session'),
});
}
let output = `**Configured Hooks (${totalHooks} total)**\n\n`;
for (const [eventName, hooks] of hooksByEvent) {
output += `### ${eventName}\n`;
for (const { hook, isSession } of hooks) {
let name: string;
let source: string;
let matcher: string;
let config: {
type: string;
command?: string;
url?: string;
name?: string;
};
if (isSession) {
// Session hook
const sessionHook = hook as SessionHookEntry;
config = sessionHook.config as {
type: string;
command?: string;
url?: string;
name?: string;
};
name =
config.name ||
(config.type === 'command' ? config.command : undefined) ||
(config.type === 'http' ? config.url : undefined) ||
'unnamed';
source = formatHookSource('session');
matcher = sessionHook.matcher
? ` (matcher: ${sessionHook.matcher})`
: '';
} else {
// Config hook
const configHook = hook as HookRegistryEntry;
config = configHook.config as {
type: string;
command?: string;
url?: string;
name?: string;
};
name =
config.name ||
(config.type === 'command' ? config.command : undefined) ||
(config.type === 'http' ? config.url : undefined) ||
'unnamed';
source = formatHookSource(configHook.source);
matcher = configHook.matcher
? ` (matcher: ${configHook.matcher})`
: '';
for (const [eventName, matcherMap] of hooksByEvent) {
output += `### ${eventName}\n\n`;
const useMatchers = supportsMatchers(eventName as HookEventName);
if (useMatchers) {
for (const [matcher, hookList] of matcherMap) {
output += `#### ${t('Matcher:')} ${matcher}\n`;
for (const hook of hookList) {
output += `- **${hook.name}** [${hook.source}]\n`;
}
output += '\n';
}
output += `- **${name}** [${source}]${matcher}\n`;
} else {
for (const hookList of matcherMap.values()) {
for (const hook of hookList) {
output += `- **${hook.name}** [${hook.source}]\n`;
}
}
output += '\n';
}
output += '\n';
}
return {
@ -191,7 +201,6 @@ export const hooksCommand: SlashCommand = {
context: CommandContext,
args: string,
): Promise<SlashCommandActionReturn> => {
// In interactive mode, open the hooks dialog
const executionMode = context.executionMode ?? 'interactive';
if (executionMode === 'interactive') {
return {
@ -200,7 +209,6 @@ export const hooksCommand: SlashCommand = {
};
}
// In non-interactive mode, list hooks
const result = await listCommand.action?.(context, args);
return result ?? { type: 'message', messageType: 'info', content: '' };
},

View File

@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { act } from '@testing-library/react';
import { act } from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render } from 'ink-testing-library';
import { MemoryDialog } from './MemoryDialog.js';
@ -41,12 +41,24 @@ describe('MemoryDialog', () => {
mockedUseConfig.mockReturnValue({
getWorkingDir: vi.fn(() => '/tmp/project'),
getProjectRoot: vi.fn(() => '/tmp/project'),
getBareMode: vi.fn(() => false),
// Stale snapshot getters — the dialog must NOT read its toggle state
// from these; it reads from the live merged settings instead.
getManagedAutoMemoryEnabled: vi.fn(() => false),
getManagedAutoDreamEnabled: vi.fn(() => false),
getAutoSkillEnabled: vi.fn(() => false),
} as never);
mockedUseSettings.mockReturnValue({ setValue: vi.fn() } as never);
mockedUseSettings.mockReturnValue({
setValue: vi.fn(),
merged: {
memory: {
enableManagedAutoMemory: false,
enableManagedAutoDream: false,
enableAutoSkill: false,
},
},
} as never);
mockedUseLaunchEditor.mockReturnValue(vi.fn());
});
@ -90,10 +102,10 @@ describe('MemoryDialog', () => {
expect(lastFrame()).toContain('› 1. User memory');
});
it('renders the Auto-skill row with the status from config', () => {
it('renders the Auto-skill row with the status from merged settings', () => {
const { lastFrame } = render(<MemoryDialog onClose={vi.fn()} />);
// beforeEach mocks getAutoSkillEnabled => false
// beforeEach mocks merged.memory.enableAutoSkill => false
expect(lastFrame()).toContain('Auto-skill: off');
});
@ -131,7 +143,10 @@ describe('MemoryDialog', () => {
it('toggles Auto-skill on Enter and persists to workspace settings', () => {
const setValue = vi.fn();
mockedUseSettings.mockReturnValue({ setValue } as never);
mockedUseSettings.mockReturnValue({
setValue,
merged: { memory: { enableAutoSkill: false } },
} as never);
const { lastFrame } = render(<MemoryDialog onClose={vi.fn()} />);
@ -161,4 +176,44 @@ describe('MemoryDialog', () => {
);
expect(lastFrame()).toContain('› Auto-skill: on');
});
it('reflects the persisted value when the dialog is reopened (remounted)', () => {
// Emulate LoadedSettings: setValue writes through to the merged view,
// exactly like the real saveSettings + recomputeMerged path.
const merged = {
memory: {
enableManagedAutoMemory: false,
enableManagedAutoDream: false,
enableAutoSkill: false,
},
};
const setValue = vi.fn((_scope: unknown, key: string, value: boolean) => {
if (key === 'memory.enableAutoSkill') {
merged.memory.enableAutoSkill = value;
}
});
mockedUseSettings.mockReturnValue({ setValue, merged } as never);
const pressKey = (key: { name: string }) => {
const keypressHandler =
mockedUseKeypress.mock.calls[
mockedUseKeypress.mock.calls.length - 1
]![0];
act(() => {
keypressHandler(key as never);
});
};
// First open: toggle Auto-skill on, then close the dialog.
const first = render(<MemoryDialog onClose={vi.fn()} />);
expect(first.lastFrame()).toContain('Auto-skill: off');
pressKey({ name: 'up' }); // focus the Auto-skill row
pressKey({ name: 'return' }); // toggle on
expect(first.lastFrame()).toContain('› Auto-skill: on');
first.unmount();
// Reopen: a fresh mount must read the persisted value, not a stale snapshot.
const second = render(<MemoryDialog onClose={vi.fn()} />);
expect(second.lastFrame()).toContain('Auto-skill: on');
});
});

View File

@ -114,14 +114,20 @@ export function MemoryDialog({ onClose }: MemoryDialogProps) {
const [focusedSection, setFocusedSection] = useState<
'autoMemory' | 'autoDream' | 'autoSkill' | 'list'
>('list');
// Read the initial toggle state from the live merged settings rather than
// the Config snapshot: Config is frozen at startup and never reflects a
// setValue() write, so reopening the dialog would otherwise show stale state.
const bareMode = config.getBareMode();
const readToggle = (value: boolean | undefined): boolean =>
!bareMode && (value ?? true);
const [autoMemoryOn, setAutoMemoryOn] = useState(() =>
config.getManagedAutoMemoryEnabled(),
readToggle(loadedSettings.merged.memory?.enableManagedAutoMemory),
);
const [autoDreamOn, setAutoDreamOn] = useState(() =>
config.getManagedAutoDreamEnabled(),
readToggle(loadedSettings.merged.memory?.enableManagedAutoDream),
);
const [autoSkillOn, setAutoSkillOn] = useState(() =>
config.getAutoSkillEnabled(),
readToggle(loadedSettings.merged.memory?.enableAutoSkill),
);
const [lastDreamAt, setLastDreamAt] = useState<number | null>(null);

View File

@ -0,0 +1,263 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from 'ink-testing-library';
import { SettingsCorruptedDialog } from './SettingsCorruptedDialog.js';
import { KeypressProvider } from '../contexts/KeypressContext.js';
const wait = (ms = 50) => new Promise((resolve) => setTimeout(resolve, ms));
const lastFrameText = (lastFrame: () => string | undefined): string => {
const text = lastFrame();
if (text == null) {
throw new Error('lastFrame returned undefined');
}
return text;
};
const waitFor = async (
predicate: () => void,
options: { timeout?: number; interval?: number } = {},
) => {
const { timeout = 1000, interval = 10 } = options;
const start = Date.now();
let lastError: unknown;
while (Date.now() - start < timeout) {
try {
predicate();
return;
} catch (e) {
lastError = e;
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
if (lastError) {
throw lastError;
}
throw new Error('waitFor timed out');
};
enum TerminalKeys {
ENTER = '\u000D',
UP_ARROW = '\u001B[A',
DOWN_ARROW = '\u001B[B',
ESCAPE = '\u001B',
}
describe('SettingsCorruptedDialog', () => {
const mockCorruptedPath = '/home/user/.qwen/settings.json.corrupted';
const mockOnExit = vi.fn();
const mockOnContinue = vi.fn();
beforeEach(() => {
mockOnExit.mockClear();
mockOnContinue.mockClear();
});
it('should show recovered settings label when wasRecovered=true', async () => {
const { lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={true}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
await waitFor(() => {
expect(lastFrame()).toContain('Continue with recovered settings (esc)');
});
unmount();
});
it('should show empty settings label when wasRecovered=false', async () => {
const { lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
await waitFor(() => {
expect(lastFrame()).toContain('Continue with empty settings (esc)');
});
unmount();
});
it('should move selection with up/down arrows', async () => {
const { stdin, lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
// Initially EXIT is selected — the line containing "Exit and restore"
// must have '>' in it
await wait();
await waitFor(() => {
const lines = lastFrameText(lastFrame).split('\n');
const exitLine = lines.find((l) => l.includes('Exit and restore'));
expect(exitLine).toBeTruthy();
expect(exitLine).toContain('>');
});
// Press down — CONTINUE line gets '>'
stdin.write(TerminalKeys.DOWN_ARROW as string);
await wait();
await waitFor(() => {
const lines = lastFrameText(lastFrame).split('\n');
const continueLine = lines.find((l) => l.includes('Continue with'));
expect(continueLine).toBeTruthy();
expect(continueLine).toContain('>');
});
// Press up — EXIT line gets '>' back
stdin.write(TerminalKeys.UP_ARROW as string);
await wait();
await waitFor(() => {
const lines = lastFrameText(lastFrame).split('\n');
const exitLine = lines.find((l) => l.includes('Exit and restore'));
expect(exitLine).toBeTruthy();
expect(exitLine).toContain('>');
});
unmount();
});
it('should call onExit when pressing Enter on EXIT option', async () => {
const { stdin, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
stdin.write(TerminalKeys.ENTER as string);
await wait();
await waitFor(() => {
expect(mockOnExit).toHaveBeenCalled();
expect(mockOnContinue).not.toHaveBeenCalled();
});
unmount();
});
it('should call onContinue when pressing Enter on CONTINUE option', async () => {
const { stdin, lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
stdin.write(TerminalKeys.DOWN_ARROW as string);
await wait();
await waitFor(() => {
const lines = lastFrameText(lastFrame).split('\n');
const continueLine = lines.find((l) => l.includes('Continue with'));
expect(continueLine).toBeTruthy();
expect(continueLine).toContain('>');
});
await wait();
stdin.write(TerminalKeys.ENTER as string);
await wait();
await waitFor(() => {
expect(mockOnContinue).toHaveBeenCalled();
expect(mockOnExit).not.toHaveBeenCalled();
});
unmount();
});
it('should call onContinue when pressing escape', async () => {
const { stdin, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
stdin.write(TerminalKeys.ESCAPE as string);
await wait();
await waitFor(() => {
expect(mockOnContinue).toHaveBeenCalled();
expect(mockOnExit).not.toHaveBeenCalled();
});
unmount();
});
it('should call onExit when pressing Ctrl+C', async () => {
const { stdin, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
stdin.write('\x03');
await wait();
await waitFor(() => {
expect(mockOnExit).toHaveBeenCalled();
expect(mockOnContinue).not.toHaveBeenCalled();
});
unmount();
});
it('should display the corrupted file path', async () => {
const { lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
await waitFor(() => {
expect(lastFrame()).toContain(mockCorruptedPath);
});
unmount();
});
});

View File

@ -0,0 +1,123 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type React from 'react';
import { useState } from 'react';
import { Box, Text } from 'ink';
import { useKeypress } from '../hooks/useKeypress.js';
import { theme } from '../semantic-colors.js';
import { t } from '../../i18n/index.js';
const EXIT_INDEX = 0;
const CONTINUE_INDEX = 1;
interface SettingsCorruptedDialogProps {
corruptedPath: string;
wasRecovered: boolean;
onExit: () => void;
onContinue: () => void;
}
export const SettingsCorruptedDialog: React.FC<
SettingsCorruptedDialogProps
> = ({ corruptedPath, wasRecovered, onExit, onContinue }) => {
const [selectedIndex, setSelectedIndex] = useState(EXIT_INDEX);
useKeypress(
(key) => {
if (key.name === 'escape') {
onContinue();
return;
}
if (key.ctrl && key.name === 'c') {
onExit();
return;
}
if (key.name === 'up') {
setSelectedIndex(EXIT_INDEX);
}
if (key.name === 'down') {
setSelectedIndex(CONTINUE_INDEX);
}
if (key.name === 'return') {
if (selectedIndex === EXIT_INDEX) {
onExit();
} else {
onContinue();
}
}
},
{ isActive: true },
);
const continueLabel = wasRecovered
? t('Continue with recovered settings (esc)')
: t('Continue with empty settings (esc)');
return (
<Box
flexDirection="column"
borderStyle="round"
borderColor={theme.status.error}
padding={1}
width="100%"
marginLeft={1}
>
<Box marginBottom={1} flexDirection="column">
<Text>
<Text color={theme.status.error}>{'> '}</Text>
<Text bold color={theme.status.error}>
{t('Settings file corrupted')}
</Text>
</Text>
<Text color={theme.text.secondary}>
{t(
'Your settings file had invalid JSON. A copy of the corrupted file has been saved for reference.',
)}
</Text>
<Text color={theme.text.secondary}>{corruptedPath}</Text>
</Box>
<Box flexDirection="column">
<Box>
<Text>
{selectedIndex === EXIT_INDEX ? (
<Text color={theme.status.success}>{'> '}</Text>
) : (
' '
)}
</Text>
<Text
color={
selectedIndex === EXIT_INDEX
? theme.status.success
: theme.text.primary
}
>
{t('Exit and restore corrupted file')}
</Text>
</Box>
<Box>
<Text>
{selectedIndex === CONTINUE_INDEX ? (
<Text color={theme.status.success}>{'> '}</Text>
) : (
' '
)}
</Text>
<Text
color={
selectedIndex === CONTINUE_INDEX
? theme.status.success
: theme.text.primary
}
>
{continueLabel}
</Text>
</Box>
</Box>
</Box>
);
};

View File

@ -49,7 +49,10 @@ const config = {
getCliVersion: () => '1.2.3',
getModel: () => 'qwen3-code-plus',
getTargetDir: () => '/repo/project',
getContentGeneratorConfig: () => ({ contextWindowSize: 1000 }),
getContentGeneratorConfig: () => ({
contextWindowSize: 1000,
reasoning: { effort: 'high' },
}),
} as Config;
const uiState = {
@ -84,8 +87,26 @@ describe('StatusLineDialog', () => {
expect(lastFrame()).toContain('Configure Status Line');
expect(lastFrame()).toContain('Type to search');
const frame = lastFrame() ?? '';
expect(frame).toContain('model-with-reasoning');
expect(frame).toContain('model-only');
expect(frame).toContain('git-branch');
expect(frame).toContain('context-remaining');
expect(frame).toContain('current-dir');
expect(frame.indexOf('model-with-reasoning')).toBeLessThan(
frame.indexOf('model-only'),
);
expect(frame.indexOf('model-only')).toBeLessThan(
frame.indexOf('git-branch'),
);
expect(frame.indexOf('git-branch')).toBeLessThan(
frame.indexOf('context-remaining'),
);
expect(frame.indexOf('context-remaining')).toBeLessThan(
frame.indexOf('current-dir'),
);
expect(lastFrame()).toContain('Preview');
expect(lastFrame()).toContain('qwen3-code-plus');
expect(lastFrame()).toContain('qwen3-code-plus high');
});
it('persists selected presets on enter', async () => {
@ -117,10 +138,10 @@ describe('StatusLineDialog', () => {
useThemeColors: true,
items: [
'model-with-reasoning',
'git-branch',
'context-remaining',
'current-dir',
'context-used',
'git-branch',
],
});
expect(
@ -137,6 +158,53 @@ describe('StatusLineDialog', () => {
expect(onClose).toHaveBeenCalled();
});
it('keeps preset priority order after an item is toggled off and on', async () => {
const settings = createSettings();
const { stdin, lastFrame } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<StatusLineDialog
settings={settings}
config={config}
uiState={uiState}
addItem={vi.fn()}
onClose={vi.fn()}
availableTerminalHeight={18}
/>
</KeypressProvider>,
);
const press = async (input: string) => {
act(() => {
stdin.write(input);
});
await new Promise((resolve) => setTimeout(resolve, 0));
};
await press('j');
await press('j');
await press('j');
await press(' ');
await press(' ');
expect(lastFrame()).toContain(
'qwen3-code-plus high | feature/pr-4087-statusline | Context 75% left',
);
await press('\r');
expect(settings.merged.ui?.statusLine).toEqual({
type: 'preset',
useThemeColors: true,
items: [
'model-with-reasoning',
'git-branch',
'context-remaining',
'current-dir',
'context-used',
],
});
});
it('saves back to workspace settings when workspace config is effective', async () => {
const settings = createSettings();
settings.workspace.settings.ui = {

View File

@ -22,6 +22,7 @@ import {
buildStatusLinePresetLines,
DEFAULT_STATUS_LINE_PRESET_CONFIG,
normalizeStatusLinePresetConfig,
orderStatusLinePresetItems,
STATUS_LINE_PRESET_ITEMS,
type StatusLinePresetConfig,
type StatusLinePresetItemId,
@ -57,19 +58,11 @@ function buildInitialSelectedKeys(settings: LoadedSettings): string[] {
function buildConfigFromKeys(keys: readonly string[]): StatusLinePresetConfig {
const selected = new Set(keys);
const validItemIds = new Set(STATUS_LINE_PRESET_ITEMS.map((item) => item.id));
const items = [
...new Set(
keys.filter((key): key is StatusLinePresetItemId =>
validItemIds.has(key as StatusLinePresetItemId),
),
),
];
return {
type: 'preset',
useThemeColors: selected.has(THEME_COLORS_KEY),
items,
items: orderStatusLinePresetItems(keys),
};
}
@ -102,15 +95,16 @@ function getPreviewData(config: Config, uiState: UIState) {
const stats = uiState.sessionStats;
const metrics = stats.metrics;
const { totalInputTokens, totalOutputTokens } = aggregateModelTokens(metrics);
const contentGeneratorConfig = config.getContentGeneratorConfig();
return buildStatusLinePresetData({
sessionId: stats.sessionId,
version: config.getCliVersion(),
modelDisplayName: uiState.currentModel || config.getModel(),
reasoning: contentGeneratorConfig?.reasoning,
currentDir: config.getTargetDir(),
branch: uiState.branchName,
contextWindowSize:
config.getContentGeneratorConfig()?.contextWindowSize || 0,
contextWindowSize: contentGeneratorConfig?.contextWindowSize || 0,
currentUsage: stats.lastPromptTokenCount,
totalInputTokens,
totalOutputTokens,

View File

@ -22,7 +22,7 @@ function makeTodos(count: number): TodoItem[] {
}
describe('StickyTodoList', () => {
it('keeps each task number attached to the original task after sorting', () => {
it('keeps each visible task number attached to the original task after sorting', () => {
const todos: TodoItem[] = [
{
id: 'done',
@ -56,15 +56,10 @@ describe('StickyTodoList', () => {
expect(
lines.find((line) => line.includes('Run cli tests')) ?? '',
).toContain('2.');
expect(
lines.find((line) => line.includes('Summarize results')) ?? '',
).toContain('1.');
expect(output).not.toContain('Summarize results');
expect(output.indexOf('Run core tests')).toBeLessThan(
output.indexOf('Run cli tests'),
);
expect(output.indexOf('Run cli tests')).toBeLessThan(
output.indexOf('Summarize results'),
);
});
it('keeps long todo lists compact with a hidden item summary', () => {
@ -104,7 +99,7 @@ describe('StickyTodoList', () => {
expect(output).toContain('Run cli tests');
expect(output).not.toContain('Run core tests');
expect(output).not.toContain('Summarize results');
expect(output).toContain('... and 2 more');
expect(output).toContain('... and 1 more');
expect(lines).toHaveLength(6);
});
@ -120,7 +115,26 @@ describe('StickyTodoList', () => {
const output = lastFrame() ?? '';
expect(output).toContain('10. ◐ Task 10');
expect(output).toContain('... and 9 more');
expect(output).not.toContain('... and 9 more');
});
it('hides the sticky panel when every task is completed', () => {
const todos: TodoItem[] = [
{
id: 'done-1',
content: 'Run tests',
status: 'completed',
},
{
id: 'done-2',
content: 'Summarize results',
status: 'completed',
},
];
const { lastFrame } = render(<StickyTodoList todos={todos} width={60} />);
expect(lastFrame()).toBe('');
});
it('derives a viewport-aware visible item count', () => {

View File

@ -45,20 +45,26 @@ const StickyTodoListComponent: React.FC<StickyTodoListProps> = ({
width,
maxVisibleItems = STICKY_TODO_MAX_VISIBLE_ITEMS,
}) => {
const orderedTodos = useMemo(() => getOrderedStickyTodos(todos), [todos]);
const orderedOpenTodos = useMemo(
() =>
getOrderedStickyTodos(todos).filter(
(todo) => todo.status !== 'completed',
),
[todos],
);
const todoNumberById = useMemo(
() =>
new Map(todos.map((todo, index) => [todo.id, `${index + 1}.`] as const)),
[todos],
);
if (todos.length === 0) {
if (orderedOpenTodos.length === 0) {
return null;
}
const visibleTodoCount = clampVisibleTodoCount(maxVisibleItems);
const visibleTodos = orderedTodos.slice(0, visibleTodoCount);
const hiddenTodoCount = orderedTodos.length - visibleTodos.length;
const visibleTodos = orderedOpenTodos.slice(0, visibleTodoCount);
const hiddenTodoCount = orderedOpenTodos.length - visibleTodos.length;
const numberColumnWidth =
Math.max(
...visibleTodos.map(

View File

@ -0,0 +1,267 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from 'ink-testing-library';
import { HooksConfigSource, HookType } from '@qwen-code/qwen-code-core';
import { HandlerListBody } from './HandlerListBody.js';
import type { HookConfigDisplayInfo } from './types.js';
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 120, rows: 24 })),
}));
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: { primary: 'white', secondary: 'gray', accent: 'cyan' },
},
}));
function commandConfig(
command = '/cmd.sh',
async = false,
): HookConfigDisplayInfo {
return {
config: { type: HookType.Command, command, async },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
}
function httpConfig(
overrides: Partial<{ name: string; url: string }> = {},
): HookConfigDisplayInfo {
return {
config: {
type: HookType.Http,
url: overrides.url ?? 'https://example.test/hook',
...(overrides.name ? { name: overrides.name } : {}),
} as HookConfigDisplayInfo['config'],
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
}
function functionConfig(
overrides: Partial<{ name: string; id: string }> = {},
): HookConfigDisplayInfo {
return {
config: {
type: HookType.Function,
callback: async () => undefined,
errorMessage: 'fn failed',
id: overrides.id ?? 'fn-id',
...(overrides.name ? { name: overrides.name } : {}),
} as HookConfigDisplayInfo['config'],
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
}
function promptConfig(
overrides: Partial<{ name: string; prompt: string }> = {},
): HookConfigDisplayInfo {
return {
config: {
type: HookType.Prompt,
prompt: overrides.prompt ?? 'short prompt',
...(overrides.name ? { name: overrides.name } : {}),
} as HookConfigDisplayInfo['config'],
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
}
describe('HandlerListBody', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('describeHook (rendered as the row label)', () => {
it('renders the command path for command hooks', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[commandConfig('/check.sh')]}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('[command]');
expect(out).toContain('/check.sh');
});
it('marks async command hooks with " async" in the type column', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[commandConfig('/bg.sh', true)]}
selectedIndex={0}
/>,
);
expect(lastFrame() ?? '').toContain('[command async]');
});
it('prefers the http hook name over the URL', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[httpConfig({ name: 'webhook-A', url: 'https://x' })]}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('[http]');
expect(out).toContain('webhook-A');
expect(out).not.toContain('https://x');
});
it('falls back to the http URL when name is missing', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[httpConfig({ url: 'https://example.test/hook' })]}
selectedIndex={0}
/>,
);
expect(lastFrame() ?? '').toContain('https://example.test/hook');
});
it('prefers the function hook name over the id', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[functionConfig({ name: 'fn-name', id: 'fn-id' })]}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('[function]');
expect(out).toContain('fn-name');
expect(out).not.toContain('fn-id');
});
it('falls back to function id, then to "function-hook" placeholder', () => {
const withId = render(
<HandlerListBody
configs={[functionConfig({ id: 'only-id' })]}
selectedIndex={0}
/>,
);
expect(withId.lastFrame() ?? '').toContain('only-id');
const noNameNoId = render(
<HandlerListBody
configs={[
{
config: {
type: HookType.Function,
callback: async () => undefined,
errorMessage: 'fn failed',
} as HookConfigDisplayInfo['config'],
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
},
]}
selectedIndex={0}
/>,
);
expect(noNameNoId.lastFrame() ?? '').toContain('function-hook');
});
it('truncates long prompt text with "..." and keeps short prompts intact', () => {
const long = 'a'.repeat(80);
const { lastFrame: longFrame } = render(
<HandlerListBody
configs={[promptConfig({ prompt: long })]}
selectedIndex={0}
/>,
);
const longOut = longFrame() ?? '';
expect(longOut).toContain('a'.repeat(50) + '...');
expect(longOut).not.toContain('a'.repeat(51));
const { lastFrame: shortFrame } = render(
<HandlerListBody
configs={[promptConfig({ prompt: 'fits' })]}
selectedIndex={0}
/>,
);
const shortOut = shortFrame() ?? '';
expect(shortOut).toContain('fits');
expect(shortOut).not.toContain('...');
});
it('prefers the prompt name over the prompt text', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[
promptConfig({ name: 'classifier', prompt: 'should not appear' }),
]}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('classifier');
expect(out).not.toContain('should not appear');
});
});
describe('source column', () => {
it('appends the extension name for Extensions-source configs', () => {
const config: HookConfigDisplayInfo = {
config: { type: HookType.Command, command: '/ext.sh' },
source: HooksConfigSource.Extensions,
sourceDisplay: 'my-extension',
enabled: true,
};
const { lastFrame } = render(
<HandlerListBody configs={[config]} selectedIndex={0} />,
);
const out = lastFrame() ?? '';
expect(out).toContain('Extensions');
expect(out).toContain('my-extension');
});
it('uses the long "Session (temporary)" label for session-source configs', () => {
const config: HookConfigDisplayInfo = {
config: { type: HookType.Command, command: '/sess.sh' },
source: HooksConfigSource.Session,
sourceDisplay: 'Session (temporary)',
enabled: true,
};
const { lastFrame } = render(
<HandlerListBody configs={[config]} selectedIndex={0} />,
);
expect(lastFrame() ?? '').toContain('Session (temporary)');
});
});
it('renders numbered rows and footer hint, places arrow on selected', () => {
const configs = [commandConfig('/first.sh'), commandConfig('/second.sh')];
const { lastFrame } = render(
<HandlerListBody configs={configs} selectedIndex={1} />,
);
const out = lastFrame() ?? '';
expect(out).toContain('1.');
expect(out).toContain('2.');
expect(out).toContain('Configured hooks:');
expect(out).toContain('Enter to select · Esc to go back');
const arrowLine = out.split('\n').find((line) => line.includes('❯'));
expect(arrowLine).toBeDefined();
expect(arrowLine).toContain('/second.sh');
});
});

View File

@ -0,0 +1,106 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import { HookType } from '@qwen-code/qwen-code-core';
import type { HookConfigDisplayInfo } from './types.js';
import { getConfigSourceDisplay } from './sourceLabels.js';
import { t } from '../../../i18n/index.js';
interface HandlerListBodyProps {
configs: HookConfigDisplayInfo[];
selectedIndex: number;
}
export function HandlerListBody({
configs,
selectedIndex,
}: HandlerListBodyProps): React.JSX.Element {
const { columns: terminalWidth } = useTerminalSize();
const commandWidth = Math.floor(terminalWidth * 0.65);
const sourceWidth = Math.floor(terminalWidth * 0.3);
return (
<>
<Text bold color={theme.text.primary}>
{t('Configured hooks:')}
</Text>
{configs.map((config, index) => {
const isSelected = index === selectedIndex;
const sourceDisplay = getConfigSourceDisplay(config);
const hookDisplay = describeHook(config);
const typeDisplay = formatTypeDisplay(config);
return (
<Box key={index}>
<Box width={commandWidth}>
<Box minWidth={2}>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
>
{isSelected ? '❯' : ' '}
</Text>
</Box>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
bold={isSelected}
wrap="wrap"
>
{`${index + 1}. [${typeDisplay}] ${hookDisplay}`}
</Text>
</Box>
<Box width={2} />
<Box width={sourceWidth}>
<Text color={theme.text.secondary} wrap="wrap">
{sourceDisplay}
</Text>
</Box>
</Box>
);
})}
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('Enter to select · Esc to go back')}
</Text>
</Box>
</>
);
}
function describeHook(info: HookConfigDisplayInfo): string {
const { config } = info;
switch (config.type) {
case HookType.Command:
return config.command || '';
case HookType.Http:
return config.name || config.url || '';
case HookType.Function:
return config.name || config.id || 'function-hook';
case HookType.Prompt: {
const promptText = config.prompt || '';
const maxLength = 50;
return (
config.name ||
(promptText.length > maxLength
? promptText.slice(0, maxLength) + '...'
: promptText)
);
}
default: {
const _exhaustive: never = config;
void _exhaustive;
return '';
}
}
}
function formatTypeDisplay(info: HookConfigDisplayInfo): string {
const { config } = info;
const isAsync = config.type === HookType.Command && config.async === true;
return isAsync ? `${config.type} async` : String(config.type);
}

View File

@ -14,17 +14,14 @@ import {
import { HookConfigDetailStep } from './HookConfigDetailStep.js';
import type { HookEventDisplayInfo, HookConfigDisplayInfo } from './types.js';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
// Mock useTerminalSize
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 100, rows: 24 })),
}));
// Mock semantic-colors
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
@ -51,7 +48,7 @@ describe('HookConfigDetailStep', () => {
},
{ code: 'Other', description: 'show stderr to user only' },
],
configs: [],
matcherGroups: [],
});
const createMockHookConfig = (
@ -170,7 +167,6 @@ describe('HookConfigDetailStep', () => {
<HookConfigDetailStep hookEvent={hookEvent} hookConfig={hookConfig} />,
);
// Should not have Extension label for User Settings
const output = lastFrame();
const extensionMatch = output?.match(/Extension:/g);
expect(extensionMatch).toBeNull();
@ -252,6 +248,74 @@ describe('HookConfigDetailStep', () => {
expect(lastFrame()).toContain('Esc to go back');
});
it('should render Matcher field for matcher-capable events', () => {
const hookEvent = {
...createMockHookEvent(),
event: HookEventName.PreToolUse,
};
const hookConfig: HookConfigDisplayInfo = {
config: {
type: HookType.Command,
command: '/path/to/hook.sh',
},
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
matcher: 'Bash',
enabled: true,
};
const { lastFrame } = render(
<HookConfigDetailStep hookEvent={hookEvent} hookConfig={hookConfig} />,
);
expect(lastFrame()).toContain('Matcher:');
expect(lastFrame()).toContain('Bash');
});
it('should render Matcher as * when matcher is missing for matcher-capable events', () => {
const hookEvent = {
...createMockHookEvent(),
event: HookEventName.PreToolUse,
};
const hookConfig: HookConfigDisplayInfo = {
config: {
type: HookType.Command,
command: '/path/to/hook.sh',
},
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
const { lastFrame } = render(
<HookConfigDetailStep hookEvent={hookEvent} hookConfig={hookConfig} />,
);
expect(lastFrame()).toContain('Matcher:');
expect(lastFrame()).toContain('*');
});
it('should not render Matcher field for non-matcher events', () => {
const hookEvent = createMockHookEvent();
const hookConfig: HookConfigDisplayInfo = {
config: {
type: HookType.Command,
command: '/path/to/hook.sh',
},
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
matcher: '*',
enabled: true,
};
const output =
render(
<HookConfigDetailStep hookEvent={hookEvent} hookConfig={hookConfig} />,
).lastFrame() ?? '';
expect(output).not.toContain('Matcher:');
});
it('should handle different event types', () => {
const events = [
HookEventName.PreToolUse,
@ -266,7 +330,7 @@ describe('HookConfigDetailStep', () => {
shortDescription: 'Test',
description: '',
exitCodes: [],
configs: [],
matcherGroups: [],
};
const hookConfig = createMockHookConfig();

View File

@ -10,6 +10,10 @@ import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import type { HookConfigDisplayInfo, HookEventDisplayInfo } from './types.js';
import { HooksConfigSource } from '@qwen-code/qwen-code-core';
import { t } from '../../../i18n/index.js';
import {
getTranslatedSourceDisplayMap,
supportsMatchers,
} from './constants.js';
interface HookConfigDetailStepProps {
hookEvent: HookEventDisplayInfo;
@ -22,26 +26,10 @@ export function HookConfigDetailStep({
}: HookConfigDetailStepProps): React.JSX.Element {
const { columns: terminalWidth } = useTerminalSize();
// Get source display
const getSourceDisplay = (): string => {
switch (hookConfig.source) {
case HooksConfigSource.Project:
return t('Local Settings');
case HooksConfigSource.User:
return t('User Settings');
case HooksConfigSource.System:
return t('System Settings');
case HooksConfigSource.Extensions:
return t('Extensions');
default:
return hookConfig.source;
}
};
const sourceDisplay = getTranslatedSourceDisplayMap()[hookConfig.source];
// Check if this is from an extension
const isFromExtension = hookConfig.source === HooksConfigSource.Extensions;
// Get hook type display
const getHookTypeDisplay = (): string => {
switch (hookConfig.config.type) {
case 'command':
@ -51,7 +39,6 @@ export function HookConfigDetailStep({
}
};
// Get command to display
const getCommand = (): string => {
if (hookConfig.config.type === 'command') {
return hookConfig.config.command;
@ -59,7 +46,6 @@ export function HookConfigDetailStep({
return '';
};
// Get prompt to display
const getPrompt = (): string => {
if (hookConfig.config.type === 'prompt') {
return hookConfig.config.prompt;
@ -67,7 +53,6 @@ export function HookConfigDetailStep({
return '';
};
// Get URL to display
const getUrl = (): string => {
if (hookConfig.config.type === 'http') {
return hookConfig.config.url;
@ -75,22 +60,19 @@ export function HookConfigDetailStep({
return '';
};
// Calculate box width for command display
const commandBoxWidth = Math.min(terminalWidth - 6, 80);
// Label width for alignment (Extension: is the longest label)
const labelWidth = 12;
const showMatcher = supportsMatchers(hookEvent.event);
return (
<Box flexDirection="column" paddingX={1}>
{/* Title */}
<Box marginBottom={1}>
<Text bold color={theme.text.primary}>
{t('Hook details')}
</Text>
</Box>
{/* Event */}
<Box>
<Box width={labelWidth}>
<Text color={theme.text.secondary}>{t('Event:')}</Text>
@ -98,7 +80,15 @@ export function HookConfigDetailStep({
<Text color={theme.text.primary}>{hookEvent.event}</Text>
</Box>
{/* Type */}
{showMatcher && (
<Box>
<Box width={labelWidth}>
<Text color={theme.text.secondary}>{t('Matcher:')}</Text>
</Box>
<Text color={theme.text.primary}>{hookConfig.matcher || '*'}</Text>
</Box>
)}
<Box>
<Box width={labelWidth}>
<Text color={theme.text.secondary}>{t('Type:')}</Text>
@ -106,18 +96,16 @@ export function HookConfigDetailStep({
<Text color={theme.text.primary}>{getHookTypeDisplay()}</Text>
</Box>
{/* Source */}
<Box>
<Box width={labelWidth}>
<Text color={theme.text.secondary}>{t('Source:')}</Text>
</Box>
<Text color={theme.text.primary}>{getSourceDisplay()}</Text>
<Text color={theme.text.primary}>{sourceDisplay}</Text>
{hookConfig.sourcePath && (
<Text color={theme.text.secondary}> ({hookConfig.sourcePath})</Text>
)}
</Box>
{/* Extension name (only for extensions) */}
{isFromExtension && hookConfig.sourceDisplay && (
<Box>
<Box width={labelWidth}>
@ -127,7 +115,6 @@ export function HookConfigDetailStep({
</Box>
)}
{/* Name (if exists) */}
{hookConfig.config.name && (
<Box>
<Box width={labelWidth}>
@ -137,7 +124,6 @@ export function HookConfigDetailStep({
</Box>
)}
{/* Description (if exists) */}
{hookConfig.config.description && (
<Box>
<Box width={labelWidth}>
@ -149,7 +135,6 @@ export function HookConfigDetailStep({
</Box>
)}
{/* Command / Prompt / URL - based on hook type */}
{hookConfig.config.type === 'command' && (
<>
<Box marginTop={1}>
@ -201,7 +186,6 @@ export function HookConfigDetailStep({
</>
)}
{/* Help text */}
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t(
@ -210,7 +194,6 @@ export function HookConfigDetailStep({
</Text>
</Box>
{/* Footer hint */}
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>

View File

@ -12,19 +12,24 @@ import {
HookType,
} from '@qwen-code/qwen-code-core';
import { HookDetailStep } from './HookDetailStep.js';
import type { HookEventDisplayInfo } from './types.js';
import type { HookConfigDisplayInfo, HookEventDisplayInfo } from './types.js';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
t: vi.fn((key: string, options?: { count?: string }) => {
if (key === '{{count}} hook' && options?.count) {
return `${options.count} hook`;
}
if (key === '{{count}} hooks' && options?.count) {
return `${options.count} hooks`;
}
return key;
}),
}));
// Mock useTerminalSize
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 100, rows: 24 })),
}));
// Mock semantic-colors
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
@ -39,190 +44,282 @@ vi.mock('../../semantic-colors.js', () => ({
},
}));
describe('HookDetailStep', () => {
const createMockHookInfo = (
event: HookEventName,
configCount = 0,
hasDescription = true,
): HookEventDisplayInfo => ({
event,
shortDescription: `Short description for ${event}`,
description: hasDescription ? `Detailed description for ${event}` : '',
exitCodes: [
function makeConfig(
command: string,
source: HooksConfigSource = HooksConfigSource.User,
matcher = '*',
): HookConfigDisplayInfo {
return {
config: { command, type: HookType.Command },
source,
sourceDisplay:
source === HooksConfigSource.User ? 'User Settings' : 'Local Settings',
matcher,
enabled: true,
};
}
function makeHookInfo(
groups: Array<{
matcher: string;
configs: HookConfigDisplayInfo[];
sequential?: boolean;
}>,
opts: {
event?: HookEventName;
description?: string;
exitCodes?: HookEventDisplayInfo['exitCodes'];
flatConfigs?: HookConfigDisplayInfo[];
} = {},
): HookEventDisplayInfo {
const matcherGroups = opts.flatConfigs
? [{ matcher: '*', configs: opts.flatConfigs, sequential: false }]
: groups;
return {
event: opts.event ?? HookEventName.PreToolUse,
shortDescription: 'short',
description: opts.description ?? '',
exitCodes: opts.exitCodes ?? [
{ code: 0, description: 'Success' },
{ code: 2, description: 'Block' },
],
configs: Array(configCount)
.fill(null)
.map((_, i) => ({
config: { command: `hook-command-${i}`, type: HookType.Command },
source:
i % 2 === 0 ? HooksConfigSource.User : HooksConfigSource.Project,
sourceDisplay: i % 2 === 0 ? 'User Settings' : 'Local Settings',
enabled: true,
})),
});
matcherGroups,
};
}
describe('HookDetailStep', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should render hook event name as title', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse);
it('renders the "Event - Matchers" title', () => {
const hook = makeHookInfo([
{ matcher: '*', configs: [makeConfig('/x.sh')] },
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
expect(lastFrame()).toContain(HookEventName.PreToolUse);
expect(lastFrame()).toContain(`${HookEventName.PreToolUse} - Matchers`);
});
it('should render description when present', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 0, true);
it('renders event description when present', () => {
const hook = makeHookInfo(
[{ matcher: '*', configs: [makeConfig('/x.sh')] }],
{ description: 'desc-for-event' },
);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
expect(lastFrame()).toContain('Detailed description for PreToolUse');
expect(lastFrame()).toContain('desc-for-event');
});
it('should not render description section when empty', () => {
const hook = createMockHookInfo(HookEventName.Stop, 0, false);
it('renders inline exit code descriptions', () => {
const hook = makeHookInfo([
{ matcher: '*', configs: [makeConfig('/x.sh')] },
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('Exit code');
expect(out).toContain('Success');
expect(out).toContain('Block');
const hook2 = makeHookInfo(
[{ matcher: '*', configs: [makeConfig('/x.sh')] }],
{
exitCodes: [{ code: 'Other', description: 'other-desc' }],
},
);
// Stop event has empty description
const output = lastFrame();
expect(output).toContain(HookEventName.Stop);
const out2 =
render(<HookDetailStep hook={hook2} selectedIndex={0} />).lastFrame() ??
'';
expect(out2).toContain('Other exit codes');
expect(out2).toContain('other-desc');
});
it('should render exit codes', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse);
it('shows empty state when no matcher groups', () => {
const hook = makeHookInfo([]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('Exit codes');
expect(output).toContain('0');
expect(output).toContain('Success');
expect(output).toContain('2');
expect(output).toContain('Block');
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('No hooks configured for this event');
expect(out).toContain('Esc to go back');
});
it('should show empty state when no configs', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 0);
it('renders matcher rows with [Source] label and matcher', () => {
const hook = makeHookInfo([
{
matcher: '*',
configs: [makeConfig('/star.sh', HooksConfigSource.User, '*')],
},
{
matcher: 'Bash',
configs: [makeConfig('/bash.sh', HooksConfigSource.User, 'Bash')],
},
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('No hooks configured for this event');
expect(output).toContain('To add hooks, edit settings.json');
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('[User] *');
expect(out).toContain('[User] Bash');
});
it('should show configured hooks list when configs exist', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 2);
it('uses Project label for workspace-source matcher groups', () => {
const hook = makeHookInfo([
{
matcher: 'Bash',
configs: [makeConfig('/bash.sh', HooksConfigSource.Project, 'Bash')],
},
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('Configured hooks');
expect(output).toContain('[command]');
expect(output).toContain('hook-command-0');
expect(output).toContain('hook-command-1');
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('[Project] Bash');
});
it('should show source display for each config', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 2);
it('renders all unique source labels for mixed-source matcher groups', () => {
const hook = makeHookInfo([
{
matcher: 'Bash',
configs: [
makeConfig('/user.sh', HooksConfigSource.User, 'Bash'),
makeConfig('/project.sh', HooksConfigSource.Project, 'Bash'),
makeConfig('/user-two.sh', HooksConfigSource.User, 'Bash'),
],
},
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('User Settings');
expect(output).toContain('Local Settings');
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('[User, Project] Bash');
});
it('should show selection indicator for first config', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 3);
it('renders singular "1 hook" and plural "N hooks"', () => {
const hook = makeHookInfo([
{
matcher: '*',
configs: [makeConfig('/a.sh', HooksConfigSource.User, '*')],
},
{
matcher: 'Bash',
configs: [
makeConfig('/b.sh', HooksConfigSource.User, 'Bash'),
makeConfig('/c.sh', HooksConfigSource.User, 'Bash'),
],
},
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('❯');
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('1 hook');
expect(out).toContain('2 hooks');
});
it('should show keyboard hint for going back', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse);
it('does not render specific command text on the matcher list page', () => {
const hook = makeHookInfo([
{
matcher: 'Bash',
configs: [
makeConfig(
'/very-specific-command.sh',
HooksConfigSource.User,
'Bash',
),
],
},
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
expect(lastFrame()).toContain('Esc to go back');
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).not.toContain('/very-specific-command.sh');
});
it('should render with multiple configs', () => {
const hook = createMockHookInfo(HookEventName.PostToolUse, 5);
it('places the selection arrow on the selected matcher row', () => {
const hook = makeHookInfo([
{
matcher: '*',
configs: [makeConfig('/a.sh', HooksConfigSource.User, '*')],
},
{
matcher: 'Bash',
configs: [makeConfig('/b.sh', HooksConfigSource.User, 'Bash')],
},
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('1.');
expect(output).toContain('2.');
expect(output).toContain('3.');
expect(output).toContain('4.');
expect(output).toContain('5.');
const out =
render(<HookDetailStep hook={hook} selectedIndex={1} />).lastFrame() ??
'';
const arrowLine = out.split('\n').find((line) => line.includes('❯'));
expect(arrowLine).toBeDefined();
expect(arrowLine).toContain('Bash');
});
it('should handle hook with no exit codes', () => {
const hook: HookEventDisplayInfo = {
event: HookEventName.PreToolUse,
shortDescription: 'Test',
description: 'Test description',
exitCodes: [],
configs: [],
};
it('renders the Enter/Esc footer hint', () => {
const hook = makeHookInfo([
{ matcher: '*', configs: [makeConfig('/x.sh')] },
]);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).not.toContain('Exit codes');
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('Enter to select');
expect(out).toContain('Esc to go back');
});
it('should handle different hook event types', () => {
const events = [
HookEventName.Stop,
HookEventName.PreToolUse,
HookEventName.PostToolUse,
HookEventName.UserPromptSubmit,
HookEventName.SessionStart,
HookEventName.SessionEnd,
];
describe('non-matcher events (e.g. Stop)', () => {
it('does not append " - Matchers" to the title', () => {
const hook = makeHookInfo([], {
event: HookEventName.Stop,
flatConfigs: [makeConfig('/stop.sh', HooksConfigSource.User, '*')],
});
for (const event of events) {
const hook = createMockHookInfo(event, 1);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain(HookEventName.Stop);
expect(out).not.toContain('- Matchers');
});
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
it('renders the handler list directly (with command and source)', () => {
const hook = makeHookInfo([], {
event: HookEventName.Stop,
flatConfigs: [
makeConfig('/stop-one.sh', HooksConfigSource.User, '*'),
makeConfig('/stop-two.sh', HooksConfigSource.Project, '*'),
],
});
expect(lastFrame()).toContain(event);
}
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('[command]');
expect(out).toContain('/stop-one.sh');
expect(out).toContain('/stop-two.sh');
expect(out).toContain('User Settings');
expect(out).toContain('Local Settings');
expect(out).toContain('Enter to select');
});
it('shows empty state when a non-matcher event has no handlers', () => {
const hook = makeHookInfo([], {
event: HookEventName.Stop,
flatConfigs: [],
});
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('No hooks configured for this event');
});
});
});

View File

@ -4,13 +4,10 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import type { HookEventDisplayInfo } from './types.js';
import { HooksConfigSource, HookType } from '@qwen-code/qwen-code-core';
import { getTranslatedSourceDisplayMap } from './constants.js';
import { t } from '../../../i18n/index.js';
import { supportsMatchers } from './constants.js';
import { HookEventMatcherListStep } from './HookEventMatcherListStep.js';
import { HookEventHandlerListStep } from './HookEventHandlerListStep.js';
interface HookDetailStepProps {
hook: HookEventDisplayInfo;
@ -21,159 +18,10 @@ export function HookDetailStep({
hook,
selectedIndex,
}: HookDetailStepProps): React.JSX.Element {
const hasConfigs = hook.configs.length > 0;
const { columns: terminalWidth } = useTerminalSize();
// Get translated source display map
const sourceDisplayMap = getTranslatedSourceDisplayMap();
// Calculate column widths (command: 70%, source: 30%)
const commandWidth = Math.floor(terminalWidth * 0.65);
const sourceWidth = Math.floor(terminalWidth * 0.3);
// Get source display for config list
const getConfigSourceDisplay = (config: {
source: HooksConfigSource;
sourceDisplay: string;
}): string => {
if (config.source === HooksConfigSource.Extensions) {
// For extensions, sourceDisplay is the extension name
return `${sourceDisplayMap[HooksConfigSource.Extensions]} (${config.sourceDisplay})`;
}
return sourceDisplayMap[config.source] || config.source;
};
return (
<Box flexDirection="column" paddingX={1}>
{/* Title */}
<Box marginBottom={1}>
<Text bold color={theme.text.primary}>
{hook.event}
</Text>
</Box>
{/* Description */}
{hook.description && (
<Box marginBottom={1}>
<Text color={theme.text.secondary}>{hook.description}</Text>
</Box>
)}
{/* Exit codes */}
{hook.exitCodes.length > 0 && (
<Box flexDirection="column" marginBottom={1}>
<Text bold color={theme.text.primary}>
{t('Exit codes:')}
</Text>
{hook.exitCodes.map((ec, index) => (
<Box key={index}>
<Text color={theme.text.secondary}>
{` ${ec.code}: ${ec.description}`}
</Text>
</Box>
))}
</Box>
)}
<Box marginTop={1} />
{/* Configs or empty state */}
{hasConfigs ? (
<>
<Text bold color={theme.text.primary}>
{t('Configured hooks:')}
</Text>
{hook.configs.map((config, index) => {
const isSelected = index === selectedIndex;
const sourceDisplay = getConfigSourceDisplay(config);
// Get display text based on hook type
let hookDisplay = '';
const hookType = config.config.type;
if (hookType === HookType.Command) {
// For command hook, show command (truncate if too long)
hookDisplay = config.config.command || '';
} else if (hookType === HookType.Http) {
// For http hook, show name or url
hookDisplay = config.config.name || config.config.url || '';
} else if (hookType === HookType.Function) {
// For function hook, show name or id
hookDisplay =
config.config.name || config.config.id || 'function-hook';
} else if (hookType === HookType.Prompt) {
// For prompt hook, show name or prompt content (truncated)
const promptText = config.config.prompt || '';
const maxLength = 50;
hookDisplay =
config.config.name ||
(promptText.length > maxLength
? promptText.slice(0, maxLength) + '...'
: promptText);
}
// Check if this is an async hook (only command hooks support async)
const isAsync =
hookType === HookType.Command && config.config.async === true;
const typeDisplay = isAsync
? `${hookType} async`
: String(hookType);
return (
<Box key={index}>
{/* Left column: selector + display */}
<Box width={commandWidth}>
<Box minWidth={2}>
<Text
color={
isSelected ? theme.text.accent : theme.text.primary
}
>
{isSelected ? '❯' : ' '}
</Text>
</Box>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
bold={isSelected}
wrap="wrap"
>
{`${index + 1}. [${typeDisplay}] ${hookDisplay}`}
</Text>
</Box>
{/* Spacer between columns */}
<Box width={2} />
{/* Right column: source */}
<Box width={sourceWidth}>
<Text color={theme.text.secondary} wrap="wrap">
{sourceDisplay}
</Text>
</Box>
</Box>
);
})}
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('Enter to select · Esc to go back')}
</Text>
</Box>
</>
) : (
<>
<Box>
<Text color={theme.text.secondary}>
{t('No hooks configured for this event.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('To add hooks, edit settings.json directly or ask Qwen.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>
</>
)}
</Box>
);
if (supportsMatchers(hook.event)) {
return (
<HookEventMatcherListStep hook={hook} selectedIndex={selectedIndex} />
);
}
return <HookEventHandlerListStep hook={hook} selectedIndex={selectedIndex} />;
}

View File

@ -0,0 +1,56 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import type { HookEventDisplayInfo } from './types.js';
import { HookEventHeader } from './HookEventHeader.js';
import { HandlerListBody } from './HandlerListBody.js';
import { getAllConfigs } from './matcherGrouping.js';
import { t } from '../../../i18n/index.js';
interface HookEventHandlerListStepProps {
hook: HookEventDisplayInfo;
selectedIndex: number;
}
export function HookEventHandlerListStep({
hook,
selectedIndex,
}: HookEventHandlerListStepProps): React.JSX.Element {
const flatConfigs = getAllConfigs(hook);
const hasConfigs = flatConfigs.length > 0;
return (
<Box flexDirection="column" paddingX={1}>
<HookEventHeader
title={hook.event}
description={hook.description}
exitCodes={hook.exitCodes}
/>
{hasConfigs ? (
<HandlerListBody configs={flatConfigs} selectedIndex={selectedIndex} />
) : (
<>
<Box>
<Text color={theme.text.secondary}>
{t('No hooks configured for this event.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('To add hooks, edit settings.json directly or ask Qwen.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>
</>
)}
</Box>
);
}

View File

@ -0,0 +1,65 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import type { HookEventDisplayInfo } from './types.js';
import { t } from '../../../i18n/index.js';
interface HookEventHeaderProps {
title: string;
description: string;
exitCodes: HookEventDisplayInfo['exitCodes'];
}
export function HookEventHeader({
title,
description,
exitCodes,
}: HookEventHeaderProps): React.JSX.Element {
return (
<>
<Box marginBottom={1}>
<Text bold color={theme.text.primary}>
{title}
</Text>
</Box>
{description && (
<Box marginBottom={1}>
<Text color={theme.text.secondary}>{description}</Text>
</Box>
)}
<ExitCodesBlock exitCodes={exitCodes} />
</>
);
}
function ExitCodesBlock({
exitCodes,
}: {
exitCodes: HookEventDisplayInfo['exitCodes'];
}): React.JSX.Element | null {
if (exitCodes.length === 0) return null;
return (
<Box flexDirection="column" marginBottom={1}>
{exitCodes.map((ec, index) => {
const label =
typeof ec.code === 'number'
? `${t('Exit code')} ${ec.code}`
: `${t('Other exit codes')}`;
return (
<Box key={index}>
<Text color={theme.text.secondary}>
{label} - {ec.description}
</Text>
</Box>
);
})}
</Box>
);
}

View File

@ -0,0 +1,95 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import type { HookEventDisplayInfo } from './types.js';
import { HookEventHeader } from './HookEventHeader.js';
import { formatSourceLabels } from './sourceLabels.js';
import { t } from '../../../i18n/index.js';
interface HookEventMatcherListStepProps {
hook: HookEventDisplayInfo;
selectedIndex: number;
}
export function HookEventMatcherListStep({
hook,
selectedIndex,
}: HookEventMatcherListStepProps): React.JSX.Element {
const { columns: terminalWidth } = useTerminalSize();
const leftWidth = Math.floor(terminalWidth * 0.6);
const hasMatchers = hook.matcherGroups.length > 0;
return (
<Box flexDirection="column" paddingX={1}>
<HookEventHeader
title={`${hook.event} - ${t('Matchers')}`}
description={hook.description}
exitCodes={hook.exitCodes}
/>
{hasMatchers ? (
<>
{hook.matcherGroups.map((group, index) => {
const isSelected = index === selectedIndex;
const sourceLabel = formatSourceLabels(group.configs);
const count = group.configs.length;
const countLabel =
count === 1
? t('{{count}} hook', { count: String(count) })
: t('{{count}} hooks', { count: String(count) });
const rowText = `${index + 1}. [${sourceLabel}] ${group.matcher}`;
return (
<Box key={`${group.matcher}-${index}`}>
<Box minWidth={2}>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
>
{isSelected ? '❯' : ' '}
</Text>
</Box>
<Box width={leftWidth}>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
bold={isSelected}
wrap="wrap"
>
{rowText}
</Text>
</Box>
<Text color={theme.text.secondary}>{countLabel}</Text>
</Box>
);
})}
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('Enter to select · Esc to go back')}
</Text>
</Box>
</>
) : (
<>
<Box>
<Text color={theme.text.secondary}>
{t('No hooks configured for this event.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('To add hooks, edit settings.json directly or ask Qwen.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>
</>
)}
</Box>
);
}

View File

@ -0,0 +1,252 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from 'ink-testing-library';
import {
HookEventName,
HooksConfigSource,
HookType,
} from '@qwen-code/qwen-code-core';
import { HookMatcherDetailStep } from './HookMatcherDetailStep.js';
import type {
HookConfigDisplayInfo,
HookEventDisplayInfo,
HookMatcherDisplayInfo,
} from './types.js';
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 100, rows: 24 })),
}));
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
primary: 'white',
secondary: 'gray',
accent: 'cyan',
},
status: {
success: 'green',
error: 'red',
},
},
}));
function makeEvent(
overrides: Partial<HookEventDisplayInfo> = {},
): HookEventDisplayInfo {
return {
event: HookEventName.PreToolUse,
shortDescription: 'short',
description: 'Input to command is JSON of tool call arguments.',
exitCodes: [
{ code: 0, description: 'stdout/stderr not shown' },
{ code: 2, description: 'show stderr to model and block tool call' },
{
code: 'Other',
description: 'show stderr to user only but continue with tool call',
},
],
matcherGroups: [],
...overrides,
};
}
function makeConfig(
command: string,
source: HooksConfigSource = HooksConfigSource.User,
): HookConfigDisplayInfo {
return {
config: { command, type: HookType.Command },
source,
sourceDisplay:
source === HooksConfigSource.User ? 'User Settings' : 'Local Settings',
matcher: 'Bash',
enabled: true,
};
}
describe('HookMatcherDetailStep', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders the "Event - Matcher: <value>" title', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/x.sh')],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
);
expect(lastFrame()).toContain(
`${HookEventName.PreToolUse} - Matcher: Bash`,
);
});
it('keeps the "Matcher:" prefix when the matcher is the * fallback', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: '*',
configs: [makeConfig('/x.sh')],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
);
expect(lastFrame()).toContain(`${HookEventName.PreToolUse} - Matcher: *`);
});
it('keeps the event description visible on the matcher detail page', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/x.sh')],
};
const out =
render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
).lastFrame() ?? '';
expect(out).toContain('Input to command is JSON of tool call arguments.');
});
it('renders inline exit code descriptions on the matcher detail page', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/x.sh')],
};
const out =
render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
).lastFrame() ?? '';
expect(out).toContain('Exit code 0');
expect(out).toContain('stdout/stderr not shown');
expect(out).toContain('Exit code 2');
expect(out).toContain('show stderr to model and block tool call');
expect(out).toContain('Other exit codes');
expect(out).toContain(
'show stderr to user only but continue with tool call',
);
});
it('renders the handler command for command hooks', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/check.sh')],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('[command]');
expect(out).toContain('/check.sh');
});
it('renders multiple handler rows with numbering', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Edit|Write',
configs: [
makeConfig('/first.sh'),
makeConfig('/second.sh', HooksConfigSource.Project),
],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={1}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('1.');
expect(out).toContain('2.');
expect(out).toContain('/first.sh');
expect(out).toContain('/second.sh');
expect(out).toContain('User Settings');
expect(out).toContain('Local Settings');
});
it('places the selection arrow on the selected handler row', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/first.sh'), makeConfig('/second.sh')],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={1}
/>,
);
const out = lastFrame() ?? '';
const arrowLine = out.split('\n').find((line) => line.includes('❯'));
expect(arrowLine).toBeDefined();
expect(arrowLine).toContain('/second.sh');
});
it('renders empty state when the matcher group has no handlers', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('No hooks configured for this matcher');
expect(out).toContain('Esc to go back');
});
});

View File

@ -0,0 +1,54 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import type { HookEventDisplayInfo, HookMatcherDisplayInfo } from './types.js';
import { HookEventHeader } from './HookEventHeader.js';
import { HandlerListBody } from './HandlerListBody.js';
import { t } from '../../../i18n/index.js';
interface HookMatcherDetailStepProps {
hookEvent: HookEventDisplayInfo;
matcherGroup: HookMatcherDisplayInfo;
selectedIndex: number;
}
export function HookMatcherDetailStep({
hookEvent,
matcherGroup,
selectedIndex,
}: HookMatcherDetailStepProps): React.JSX.Element {
const hasConfigs = matcherGroup.configs.length > 0;
return (
<Box flexDirection="column" paddingX={1}>
<HookEventHeader
title={`${hookEvent.event} - ${t('Matcher:')} ${matcherGroup.matcher}`}
description={hookEvent.description}
exitCodes={hookEvent.exitCodes}
/>
{hasConfigs ? (
<HandlerListBody
configs={matcherGroup.configs}
selectedIndex={selectedIndex}
/>
) : (
<>
<Box>
<Text color={theme.text.secondary}>
{t('No hooks configured for this matcher.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>
</>
)}
</Box>
);
}

View File

@ -14,10 +14,8 @@ import {
import { HooksListStep } from './HooksListStep.js';
import type { HookEventDisplayInfo } from './types.js';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string, options?: { count?: string }) => {
// Handle pluralization
if (key === '{{count}} hook configured' && options?.count) {
return `${options.count} hook configured`;
}
@ -28,12 +26,10 @@ vi.mock('../../../i18n/index.js', () => ({
}),
}));
// Mock useTerminalSize
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 120, rows: 24 })),
}));
// Mock semantic-colors
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
@ -52,23 +48,30 @@ describe('HooksListStep', () => {
const createMockHookInfo = (
event: HookEventName,
configCount = 0,
): HookEventDisplayInfo => ({
event,
shortDescription: `Description for ${event}`,
description: `Detailed description for ${event}`,
exitCodes: [
{ code: 0, description: 'Success' },
{ code: 2, description: 'Block' },
],
configs: Array(configCount)
): HookEventDisplayInfo => {
const configs = Array(configCount)
.fill(null)
.map((_, i) => ({
config: { command: `hook-${i}`, type: HookType.Command },
config: {
command: `hook-${i}`,
type: HookType.Command as const,
},
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
matcher: '*',
enabled: true,
})),
});
}));
return {
event,
shortDescription: `Description for ${event}`,
description: `Detailed description for ${event}`,
exitCodes: [
{ code: 0, description: 'Success' },
{ code: 2, description: 'Block' },
],
matcherGroups: configs.length > 0 ? [{ matcher: '*', configs }] : [],
};
};
beforeEach(() => {
vi.clearAllMocks();

View File

@ -10,6 +10,13 @@ import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import type { HookEventDisplayInfo } from './types.js';
import { t } from '../../../i18n/index.js';
function configCountFor(hook: HookEventDisplayInfo): number {
return hook.matcherGroups.reduce(
(sum, group) => sum + group.configs.length,
0,
);
}
interface HooksListStepProps {
hooks: HookEventDisplayInfo[];
selectedIndex: number;
@ -21,7 +28,6 @@ export function HooksListStep({
}: HooksListStepProps): React.JSX.Element {
const { columns: terminalWidth } = useTerminalSize();
// Calculate responsive width for hook name column (min 20, max 35)
const hookNameWidth = Math.min(
35,
Math.max(20, Math.floor(terminalWidth * 0.25)),
@ -35,13 +41,11 @@ export function HooksListStep({
);
}
// Calculate total configured hooks
const totalConfigured = hooks.reduce(
(sum, hook) => sum + hook.configs.length,
(sum, hook) => sum + configCountFor(hook),
0,
);
// Get the correct plural/singular form
const hooksConfiguredText =
totalConfigured === 1
? t('{{count}} hook configured', { count: String(totalConfigured) })
@ -66,7 +70,7 @@ export function HooksListStep({
{hooks.map((hook, index) => {
const isSelected = index === selectedIndex;
const configCount = hook.configs.length;
const configCount = configCountFor(hook);
const maxDigits = String(hooks.length).length;
const paddedIndex = String(index + 1).padStart(maxDigits);

View File

@ -5,22 +5,46 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { cleanup } from 'ink-testing-library';
import { HooksManagementDialog } from './HooksManagementDialog.js';
import { renderWithProviders } from '../../../test-utils/render.js';
import { useKeypress } from '../../hooks/useKeypress.js';
import { useConfig } from '../../contexts/ConfigContext.js';
import { loadSettings, SettingScope } from '../../../config/settings.js';
import type { Key } from '../../contexts/KeypressContext.js';
// Mock useKeypress
vi.mock('../../hooks/useKeypress.js', () => ({
useKeypress: vi.fn(),
}));
const mockedUseKeypress = vi.mocked(useKeypress);
const mockedUseConfig = vi.mocked(useConfig);
const mockedLoadSettings = vi.mocked(loadSettings);
let keypressHandler: ((key: Key) => void) | null = null;
/**
* Returns a `useConfig` return value with `disableAllHooks` flipped on, while
* keeping every other method shaped like the default mock at the top of this
* file. Used with `mockReturnValueOnce` for the initial render — the dialog's
* navigation stack is seeded in a `useState` initializer that only consults
* `disableAllHooks` once, so subsequent renders falling back to the default
* mock is fine.
*/
function disabledHooksConfig(): ReturnType<typeof useConfig> {
return {
getExtensions: vi.fn(() => []),
getDisableAllHooks: vi.fn(() => true),
getHookSystem: vi.fn(() => ({
getSessionHooksManager: vi.fn(() => ({
getAllSessionHooks: vi.fn(() => []),
})),
})),
getSessionId: vi.fn(() => 'test-session-id'),
} as unknown as ReturnType<typeof useConfig>;
}
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string, options?: { count?: string }) => {
// Handle pluralization
if (key === '{{count}} hook configured' && options?.count) {
return `${options.count} hook configured`;
}
@ -33,7 +57,6 @@ vi.mock('../../../i18n/index.js', () => ({
if (key === '{{count}} configured hooks' && options?.count) {
return `${options.count} configured hooks`;
}
// Handle interpolation for disabled message
if (
key ===
'All hooks are currently disabled. You have {{count}} that are not running.' &&
@ -45,12 +68,10 @@ vi.mock('../../../i18n/index.js', () => ({
}),
}));
// Mock useTerminalSize
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 120, rows: 24 })),
}));
// Mock useConfig
vi.mock('../../contexts/ConfigContext.js', async (importOriginal) => {
const actual =
await importOriginal<typeof import('../../contexts/ConfigContext.js')>();
@ -69,7 +90,6 @@ vi.mock('../../contexts/ConfigContext.js', async (importOriginal) => {
};
});
// Mock loadSettings
vi.mock('../../../config/settings.js', async (importOriginal) => {
const actual =
await importOriginal<typeof import('../../../config/settings.js')>();
@ -81,7 +101,6 @@ vi.mock('../../../config/settings.js', async (importOriginal) => {
};
});
// Mock semantic-colors
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
@ -100,7 +119,6 @@ vi.mock('../../semantic-colors.js', () => ({
},
}));
// Mock createDebugLogger
vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
@ -108,12 +126,13 @@ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
...actual,
createDebugLogger: vi.fn(() => ({
log: vi.fn(),
debug: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
})),
};
});
// Helper to create a key object
function createKey(name: string, sequence = ''): Key {
return {
name,
@ -125,15 +144,28 @@ function createKey(name: string, sequence = ''): Key {
};
}
function mockSettingsHooks(userHooks: Record<string, unknown>): void {
mockedLoadSettings.mockReturnValue({
forScope: vi.fn((scope: SettingScope) => ({
settings:
scope === SettingScope.User ? { hooks: userHooks } : { hooks: {} },
})),
} as unknown as ReturnType<typeof loadSettings>);
}
function pressKey(name: string, sequence = ''): void {
const latestHandler = mockedUseKeypress.mock.calls.at(-1)?.[0];
expect(latestHandler).toBeDefined();
latestHandler!(createKey(name, sequence));
}
describe('HooksManagementDialog', () => {
const mockOnClose = vi.fn();
let keypressHandler: ((key: Key) => void) | null = null;
beforeEach(() => {
vi.clearAllMocks();
keypressHandler = null;
// Mock useKeypress to capture the handler
mockedUseKeypress.mockImplementation((handler) => {
keypressHandler = handler;
});
@ -141,119 +173,195 @@ describe('HooksManagementDialog', () => {
afterEach(() => {
keypressHandler = null;
cleanup();
});
describe('Initial rendering', () => {
it('should render loading state initially', () => {
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
it('should render loading state initially', () => {
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
expect(lastFrame()).toContain('Loading hooks');
expect(lastFrame()).toContain('Loading hooks');
});
it('should allow Escape to close during loading state', () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
expect(mockOnClose).toHaveBeenCalledTimes(1);
});
it('should register the keypress handler with isActive: true', () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
expect(mockedUseKeypress).toHaveBeenCalled();
expect(mockedUseKeypress.mock.calls[0][1]).toEqual({ isActive: true });
});
it('should render HOOKS_DISABLED step on first render when disableAllHooks is true', () => {
// `renderContent` checks the HOOKS_DISABLED branch before the isLoading
// branch, so the disabled view is visible synchronously on the initial
// render — no need to wait for the hooks-loading effect.
mockedUseConfig.mockReturnValueOnce(disabledHooksConfig());
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
expect(lastFrame()).toContain('Hook Configuration - Disabled');
});
it('should close dialog on Escape when disableAllHooks is true', () => {
mockedUseConfig.mockReturnValueOnce(disabledHooksConfig());
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
expect(mockOnClose).toHaveBeenCalledTimes(1);
});
it('should navigate from a matcher hook to matcher detail', async () => {
mockSettingsHooks({
PreToolUse: [
{
matcher: 'Read',
hooks: [{ type: 'command', command: 'echo read' }],
},
{
matcher: 'Bash',
hooks: [{ type: 'command', command: 'echo bash' }],
},
],
});
it('should render with border', async () => {
const { lastFrame, unmount } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
await new Promise((resolve) => setTimeout(resolve, 100));
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hooks');
});
// The dialog should have a border (rendered as box-drawing characters)
const output = lastFrame();
expect(output).toBeTruthy();
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('[User] Read');
});
unmount();
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 2. [User] Bash');
});
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('PreToolUse - Matcher: Bash');
expect(lastFrame()).toContain('echo bash');
});
pressKey('escape', '\x1b');
await vi.waitFor(() => {
expect(lastFrame()).toContain('PreToolUse - Matchers');
});
});
describe('Keyboard navigation - HOOKS_LIST step', () => {
it('should register keypress handler with isActive: true', async () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
await new Promise((resolve) => setTimeout(resolve, 100));
expect(mockedUseKeypress).toHaveBeenCalled();
const options = mockedUseKeypress.mock.calls[0][1];
expect(options).toEqual({ isActive: true });
it('should navigate from matcher detail to config detail', async () => {
mockSettingsHooks({
PreToolUse: [
{
matcher: 'Read',
hooks: [{ type: 'command', command: 'echo read' }],
},
{
matcher: 'Bash',
hooks: [
{ type: 'command', command: 'echo first' },
{ type: 'command', command: 'echo second' },
],
},
],
});
it('should close dialog on Escape key', async () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
await new Promise((resolve) => setTimeout(resolve, 100));
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
expect(mockOnClose).toHaveBeenCalledTimes(1);
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hooks');
});
it('should not go above first item when pressing up', async () => {
const { unmount } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('[User] Read');
});
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 2. [User] Bash');
});
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('PreToolUse - Matcher: Bash');
});
await new Promise((resolve) => setTimeout(resolve, 100));
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 2. [command] echo second');
});
pressKey('return');
// Press up multiple times from first item
keypressHandler!(createKey('up'));
keypressHandler!(createKey('up'));
keypressHandler!(createKey('up'));
// Should still be at first item (no crash)
unmount();
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hook details');
expect(lastFrame()).toContain('echo second');
});
});
describe('Keyboard navigation - HOOKS_DISABLED step', () => {
it('should show disabled state when disableAllHooks is true', async () => {
// Override the mock for this test
const configContext = await import('../../contexts/ConfigContext.js');
vi.mocked(configContext.useConfig).mockReturnValue({
getExtensions: vi.fn(() => []),
getDisableAllHooks: vi.fn(() => true),
} as unknown as ReturnType<typeof configContext.useConfig>);
const { lastFrame, unmount } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
await new Promise((resolve) => setTimeout(resolve, 100));
const output = lastFrame();
expect(output).toContain('Hook Configuration - Disabled');
unmount();
it('should navigate directly from a non-matcher hook to config detail', async () => {
mockSettingsHooks({
Stop: [
{
hooks: [{ type: 'command', command: 'echo stop one' }],
},
{
hooks: [{ type: 'command', command: 'echo stop two' }],
},
],
});
it('should close dialog on Escape key when hooks are disabled', async () => {
const configContext = await import('../../contexts/ConfigContext.js');
vi.mocked(configContext.useConfig).mockReturnValue({
getExtensions: vi.fn(() => []),
getDisableAllHooks: vi.fn(() => true),
} as unknown as ReturnType<typeof configContext.useConfig>);
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
await new Promise((resolve) => setTimeout(resolve, 100));
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
expect(mockOnClose).toHaveBeenCalledTimes(1);
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hooks');
});
});
describe('Loading and error states', () => {
it('should allow Escape to close during loading state', () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
for (let i = 0; i < 6; i++) {
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain(`❯ ${i + 2}.`);
});
}
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 7. Stop');
});
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('Stop');
expect(lastFrame()).toContain('echo stop one');
});
// Don't wait for loading to complete
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 2. [command] echo stop two');
});
pressKey('return');
expect(mockOnClose).toHaveBeenCalledTimes(1);
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hook details');
expect(lastFrame()).toContain('echo stop two');
});
});
});

View File

@ -25,28 +25,27 @@ import type {
HookEventDisplayInfo,
} from './types.js';
import { HOOKS_MANAGEMENT_STEPS } from './types.js';
import { addConfigToMatcherGroup, getAllConfigs } from './matcherGrouping.js';
import { HooksListStep } from './HooksListStep.js';
import { HookDetailStep } from './HookDetailStep.js';
import { HookMatcherDetailStep } from './HookMatcherDetailStep.js';
import { HookConfigDetailStep } from './HookConfigDetailStep.js';
import { HooksDisabledStep } from './HooksDisabledStep.js';
import {
DISPLAY_HOOK_EVENTS,
getTranslatedSourceDisplayMap,
createEmptyHookEventInfo,
supportsMatchers,
} from './constants.js';
import { t } from '../../../i18n/index.js';
const debugLogger = createDebugLogger('HOOKS_DIALOG');
/**
* Type guard to check if a value is a valid HookConfig
*/
function isValidHookConfig(config: unknown): config is HookConfig {
if (typeof config !== 'object' || config === null || !('type' in config)) {
return false;
}
const obj = config as Record<string, unknown>;
// Check based on type
if (obj['type'] === 'command') {
return 'command' in obj && typeof obj['command'] === 'string';
}
@ -62,52 +61,37 @@ function isValidHookConfig(config: unknown): config is HookConfig {
return false;
}
/**
* Type guard to check if a value is a valid HookDefinition
*/
function isValidHookDefinition(def: unknown): def is HookDefinition {
if (typeof def !== 'object' || def === null) {
return false;
}
const obj = def as Record<string, unknown>;
// hooks array is required
if (!('hooks' in obj) || !Array.isArray(obj['hooks'])) {
return false;
}
// Validate each hook config in the array
for (const hook of obj['hooks']) {
if (!isValidHookConfig(hook)) {
return false;
}
}
// matcher is optional but must be a string if present
if ('matcher' in obj && typeof obj['matcher'] !== 'string') {
return false;
}
// sequential is optional but must be a boolean if present
if ('sequential' in obj && typeof obj['sequential'] !== 'boolean') {
return false;
}
return true;
}
/**
* Type guard to check if a value is a valid hooks record
* Note: This validates the structure but allows individual events to have
* invalid configs - those will be filtered out during processing.
*/
function isValidHooksRecord(hooks: unknown): hooks is Record<string, unknown> {
if (typeof hooks !== 'object' || hooks === null) {
return false;
}
// Basic structure check - must be a record with array values for event keys
const record = hooks as Record<string, unknown>;
for (const [key, value] of Object.entries(record)) {
// Skip non-event configuration fields
if (HOOKS_CONFIG_FIELDS.includes(key)) {
continue;
}
// Event values should be arrays (even if contents are invalid)
if (!Array.isArray(value)) {
return false;
}
@ -115,10 +99,6 @@ function isValidHooksRecord(hooks: unknown): hooks is Record<string, unknown> {
return true;
}
/**
* Safely extract hook definitions for a specific event
* Returns empty array if the definitions are invalid
*/
function getValidHookDefinitions(
hooksRecord: Record<string, unknown>,
eventName: string,
@ -148,11 +128,6 @@ export function HooksManagementDialog({
const { columns: width } = useTerminalSize();
const boxWidth = width - 4;
// Check if hooks are disabled
// Note: This value is captured at dialog open time. If disableAllHooks
// changes while the dialog is open (e.g., via settings.json edit),
// the dialog will not react to the change until it's closed and reopened.
// This is intentional - the dialog represents a snapshot of the current state.
const disableAllHooks = config?.getDisableAllHooks() ?? false;
const [navigationStack, setNavigationStack] = useState<string[]>([
@ -161,20 +136,19 @@ export function HooksManagementDialog({
: HOOKS_MANAGEMENT_STEPS.HOOKS_LIST,
]);
const [selectedHookIndex, setSelectedHookIndex] = useState<number>(-1);
const [selectedMatcherIndex, setSelectedMatcherIndex] = useState<number>(-1);
const [selectedConfigIndex, setSelectedConfigIndex] = useState<number>(-1);
// Track selected index within each step for keyboard navigation
const [listSelectedIndex, setListSelectedIndex] = useState<number>(0);
const [detailSelectedIndex, setDetailSelectedIndex] = useState<number>(0);
const [matcherSelectedIndex, setMatcherSelectedIndex] = useState<number>(0);
const [hooks, setHooks] = useState<HookEventDisplayInfo[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [loadError, setLoadError] = useState<string | null>(null);
// Current step
const currentStep =
navigationStack[navigationStack.length - 1] ||
HOOKS_MANAGEMENT_STEPS.HOOKS_LIST;
// Selected hook event
const selectedHook = useMemo(() => {
if (selectedHookIndex >= 0 && selectedHookIndex < hooks.length) {
return hooks[selectedHookIndex];
@ -182,11 +156,20 @@ export function HooksManagementDialog({
return null;
}, [hooks, selectedHookIndex]);
// Centralized keyboard handler
const selectedMatcher = useMemo(() => {
if (
selectedHook &&
selectedMatcherIndex >= 0 &&
selectedMatcherIndex < selectedHook.matcherGroups.length
) {
return selectedHook.matcherGroups[selectedMatcherIndex];
}
return null;
}, [selectedHook, selectedMatcherIndex]);
useKeypress(
(key) => {
if (isLoading || loadError) {
// Allow Escape to close even during loading/error states
if (key.name === 'escape') {
onClose();
}
@ -210,8 +193,10 @@ export function HooksManagementDialog({
} else if (key.name === 'return') {
if (hooks.length > 0 && listSelectedIndex >= 0) {
setSelectedHookIndex(listSelectedIndex);
setSelectedMatcherIndex(-1);
setSelectedConfigIndex(-1);
setDetailSelectedIndex(0);
setMatcherSelectedIndex(0);
setNavigationStack((prev) => [
...prev,
HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL,
@ -225,15 +210,62 @@ export function HooksManagementDialog({
case HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL:
if (key.name === 'escape') {
handleNavigateBack();
} else if (selectedHook && selectedHook.configs.length > 0) {
} else if (selectedHook) {
const matcherMode = supportsMatchers(selectedHook.event);
if (matcherMode) {
if (selectedHook.matcherGroups.length === 0) {
break;
}
if (keyMatchers[Command.SELECTION_UP](key)) {
setDetailSelectedIndex((prev) => Math.max(0, prev - 1));
} else if (keyMatchers[Command.SELECTION_DOWN](key)) {
setDetailSelectedIndex((prev) =>
Math.min(selectedHook.matcherGroups.length - 1, prev + 1),
);
} else if (key.name === 'return') {
setSelectedMatcherIndex(detailSelectedIndex);
setMatcherSelectedIndex(0);
setSelectedConfigIndex(-1);
setNavigationStack((prev) => [
...prev,
HOOKS_MANAGEMENT_STEPS.HOOK_MATCHER_DETAIL,
]);
}
} else {
const flatConfigs = getAllConfigs(selectedHook);
if (flatConfigs.length === 0) {
break;
}
if (keyMatchers[Command.SELECTION_UP](key)) {
setDetailSelectedIndex((prev) => Math.max(0, prev - 1));
} else if (keyMatchers[Command.SELECTION_DOWN](key)) {
setDetailSelectedIndex((prev) =>
Math.min(flatConfigs.length - 1, prev + 1),
);
} else if (key.name === 'return') {
setSelectedMatcherIndex(-1);
setSelectedConfigIndex(detailSelectedIndex);
setNavigationStack((prev) => [
...prev,
HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL,
]);
}
}
}
break;
case HOOKS_MANAGEMENT_STEPS.HOOK_MATCHER_DETAIL:
if (key.name === 'escape') {
handleNavigateBack();
} else if (selectedMatcher && selectedMatcher.configs.length > 0) {
if (keyMatchers[Command.SELECTION_UP](key)) {
setDetailSelectedIndex((prev) => Math.max(0, prev - 1));
setMatcherSelectedIndex((prev) => Math.max(0, prev - 1));
} else if (keyMatchers[Command.SELECTION_DOWN](key)) {
setDetailSelectedIndex((prev) =>
Math.min(selectedHook.configs.length - 1, prev + 1),
setMatcherSelectedIndex((prev) =>
Math.min(selectedMatcher.configs.length - 1, prev + 1),
);
} else if (key.name === 'return') {
setSelectedConfigIndex(detailSelectedIndex);
setSelectedConfigIndex(matcherSelectedIndex);
setNavigationStack((prev) => [
...prev,
HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL,
@ -249,14 +281,12 @@ export function HooksManagementDialog({
break;
default:
// No action for unknown steps
break;
}
},
{ isActive: true },
);
// Load hooks data
const fetchHooksData = useCallback((): HookEventDisplayInfo[] => {
if (!config) return [];
@ -266,32 +296,36 @@ export function HooksManagementDialog({
SettingScope.Workspace,
).settings;
// Get translated source display map
const sourceDisplayMap = getTranslatedSourceDisplayMap();
const result: HookEventDisplayInfo[] = [];
for (const eventName of DISPLAY_HOOK_EVENTS) {
const hookInfo = createEmptyHookEventInfo(eventName);
const groupByMatcher = supportsMatchers(eventName);
// Get hooks from user settings (with per-event validation)
const userSettingsRecord = userSettings as Record<string, unknown>;
const userHooksRaw = userSettingsRecord?.['hooks'];
if (isValidHooksRecord(userHooksRaw)) {
const userDefs = getValidHookDefinitions(userHooksRaw, eventName);
for (const def of userDefs) {
for (const hookConfig of def.hooks) {
hookInfo.configs.push({
config: hookConfig,
source: HooksConfigSource.User,
sourceDisplay: sourceDisplayMap[HooksConfigSource.User],
enabled: true,
});
addConfigToMatcherGroup(
hookInfo,
def.matcher,
def.sequential,
{
config: hookConfig,
source: HooksConfigSource.User,
sourceDisplay: sourceDisplayMap[HooksConfigSource.User],
enabled: true,
},
groupByMatcher,
);
}
}
}
// Get hooks from workspace settings (with per-event validation)
const workspaceSettingsRecord = workspaceSettings as Record<
string,
unknown
@ -304,17 +338,22 @@ export function HooksManagementDialog({
);
for (const def of workspaceDefs) {
for (const hookConfig of def.hooks) {
hookInfo.configs.push({
config: hookConfig,
source: HooksConfigSource.Project,
sourceDisplay: sourceDisplayMap[HooksConfigSource.Project],
enabled: true,
});
addConfigToMatcherGroup(
hookInfo,
def.matcher,
def.sequential,
{
config: hookConfig,
source: HooksConfigSource.Project,
sourceDisplay: sourceDisplayMap[HooksConfigSource.Project],
enabled: true,
},
groupByMatcher,
);
}
}
}
// Get hooks from extensions (with type validation)
const extensions = config.getExtensions() || [];
for (const extension of extensions) {
if (extension.isActive && extension.hooks?.[eventName]) {
@ -323,13 +362,19 @@ export function HooksManagementDialog({
for (const def of extensionHooks) {
if (isValidHookDefinition(def)) {
for (const hookConfig of def.hooks) {
hookInfo.configs.push({
config: hookConfig,
source: HooksConfigSource.Extensions,
sourceDisplay: extension.name,
sourcePath: extension.path,
enabled: true,
});
addConfigToMatcherGroup(
hookInfo,
def.matcher,
def.sequential,
{
config: hookConfig,
source: HooksConfigSource.Extensions,
sourceDisplay: extension.name,
sourcePath: extension.path,
enabled: true,
},
groupByMatcher,
);
}
}
}
@ -337,7 +382,6 @@ export function HooksManagementDialog({
}
}
// Get session hooks from SessionHooksManager
const hookSystem = config.getHookSystem();
if (hookSystem) {
const sessionId = config.getSessionId();
@ -346,20 +390,23 @@ export function HooksManagementDialog({
const allSessionHooks =
sessionHooksManager.getAllSessionHooks(sessionId);
// Filter hooks for this event
const eventSessionHooks = allSessionHooks.filter(
(hook: SessionHookEntry) => hook.eventName === eventName,
);
for (const sessionHook of eventSessionHooks) {
// Session hooks have matcher stored separately from config
hookInfo.configs.push({
config: sessionHook.config as HookConfig,
source: HooksConfigSource.Session,
sourceDisplay: t('Session (temporary)'),
matcher: sessionHook.matcher,
enabled: true,
});
addConfigToMatcherGroup(
hookInfo,
sessionHook.matcher,
sessionHook.sequential,
{
config: sessionHook.config as HookConfig,
source: HooksConfigSource.Session,
sourceDisplay: t('Session (temporary)'),
enabled: true,
},
groupByMatcher,
);
}
}
}
@ -370,7 +417,6 @@ export function HooksManagementDialog({
return result;
}, [config]);
// Load hooks data on initial render
useEffect(() => {
let cancelled = false;
setIsLoading(true);
@ -399,7 +445,6 @@ export function HooksManagementDialog({
};
}, [fetchHooksData]);
// Navigation handler for going back
const handleNavigateBack = useCallback(() => {
setNavigationStack((prev) => {
if (prev.length <= 1) {
@ -410,27 +455,39 @@ export function HooksManagementDialog({
});
}, [onClose]);
// Selected hook config
const selectedConfig = useMemo(() => {
if (!selectedHook) return null;
if (!supportsMatchers(selectedHook.event)) {
const flatConfigs = getAllConfigs(selectedHook);
if (
selectedConfigIndex >= 0 &&
selectedConfigIndex < flatConfigs.length
) {
return flatConfigs[selectedConfigIndex];
}
return null;
}
if (
selectedHook &&
selectedMatcher &&
selectedConfigIndex >= 0 &&
selectedConfigIndex < selectedHook.configs.length
selectedConfigIndex < selectedMatcher.configs.length
) {
return selectedHook.configs[selectedConfigIndex];
return selectedMatcher.configs[selectedConfigIndex];
}
return null;
}, [selectedHook, selectedConfigIndex]);
}, [selectedHook, selectedMatcher, selectedConfigIndex]);
// Calculate total configured hooks count
const configuredHooksCount = useMemo(
() => hooks.reduce((sum, hook) => sum + hook.configs.length, 0),
() =>
hooks.reduce(
(sum, hook) =>
sum + hook.matcherGroups.reduce((s, g) => s + g.configs.length, 0),
0,
),
[hooks],
);
// Render based on current step
const renderContent = () => {
// Show disabled state first (before loading check)
if (currentStep === HOOKS_MANAGEMENT_STEPS.HOOKS_DISABLED) {
return <HooksDisabledStep configuredHooksCount={configuredHooksCount} />;
}
@ -478,6 +535,22 @@ export function HooksManagementDialog({
</Box>
);
case HOOKS_MANAGEMENT_STEPS.HOOK_MATCHER_DETAIL:
if (selectedHook && selectedMatcher) {
return (
<HookMatcherDetailStep
hookEvent={selectedHook}
matcherGroup={selectedMatcher}
selectedIndex={matcherSelectedIndex}
/>
);
}
return (
<Box flexDirection="column" paddingX={1}>
<Text color={theme.text.secondary}>{t('No matcher selected')}</Text>
</Box>
);
case HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL:
if (selectedHook && selectedConfig) {
return (

View File

@ -5,14 +5,16 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HookEventName, HooksConfigSource } from '@qwen-code/qwen-code-core';
import {
HookEventName,
HooksConfigSource,
hookEventSupportsMatcher,
} from '@qwen-code/qwen-code-core';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
// Import after mocking
import {
getHookExitCodes,
getHookShortDescription,
@ -20,6 +22,7 @@ import {
getTranslatedSourceDisplayMap,
createEmptyHookEventInfo,
DISPLAY_HOOK_EVENTS,
supportsMatchers,
} from './constants.js';
describe('hooks constants', () => {
@ -83,6 +86,24 @@ describe('hooks constants', () => {
expect(exitCodes).toHaveLength(3);
});
it('should return exit codes for PostCompact event', () => {
const exitCodes = getHookExitCodes(HookEventName.PostCompact);
expect(exitCodes).toHaveLength(2);
expect(exitCodes[0].code).toBe(0);
expect(exitCodes[1].code).toBe('Other');
});
it('should return exit codes for StopFailure event', () => {
// Fire-and-forget per hookAggregator — both rows are documented as ignored.
const exitCodes = getHookExitCodes(HookEventName.StopFailure);
expect(exitCodes).toHaveLength(2);
expect(exitCodes[0].code).toBe(0);
expect(exitCodes[1].code).toBe('Other');
for (const row of exitCodes) {
expect(row.description).toContain('fire-and-forget');
}
});
it('should return empty array for unknown event', () => {
const exitCodes = getHookExitCodes('unknown_event' as HookEventName);
expect(exitCodes).toEqual([]);
@ -110,6 +131,17 @@ describe('hooks constants', () => {
expect(desc).toBe('When a new session is started');
});
it('should return description for PostCompact', () => {
const desc = getHookShortDescription(HookEventName.PostCompact);
expect(desc).toBe('After conversation compaction');
});
it('should return description for StopFailure', () => {
const desc = getHookShortDescription(HookEventName.StopFailure);
expect(desc).toContain('API error');
expect(desc).toContain('Stop');
});
it('should return empty string for unknown event', () => {
const desc = getHookShortDescription('unknown_event' as HookEventName);
expect(desc).toBe('');
@ -133,6 +165,19 @@ describe('hooks constants', () => {
expect(desc).toBe('');
});
it('should return description for PostCompact', () => {
const desc = getHookDescription(HookEventName.PostCompact);
expect(desc).toContain('trigger');
expect(desc).toContain('compact_summary');
});
it('should return description for StopFailure', () => {
const desc = getHookDescription(HookEventName.StopFailure);
expect(desc).toContain('error');
expect(desc).toContain('rate_limit');
expect(desc).toContain('Fire-and-forget');
});
it('should return empty string for unknown event', () => {
const desc = getHookDescription('unknown_event' as HookEventName);
expect(desc).toBe('');
@ -152,7 +197,6 @@ describe('hooks constants', () => {
it('should return translated strings', () => {
const map = getTranslatedSourceDisplayMap();
// All values should be strings (translated)
Object.values(map).forEach((value) => {
expect(typeof value).toBe('string');
expect(value.length).toBeGreaterThan(0);
@ -186,6 +230,40 @@ describe('hooks constants', () => {
});
});
describe('supportsMatchers', () => {
it('returns true for events with meaningful matchers', () => {
expect(supportsMatchers(HookEventName.PreToolUse)).toBe(true);
expect(supportsMatchers(HookEventName.PostToolUse)).toBe(true);
expect(supportsMatchers(HookEventName.PostToolUseFailure)).toBe(true);
expect(supportsMatchers(HookEventName.PermissionRequest)).toBe(true);
expect(supportsMatchers(HookEventName.Notification)).toBe(true);
expect(supportsMatchers(HookEventName.SessionStart)).toBe(true);
expect(supportsMatchers(HookEventName.SessionEnd)).toBe(true);
expect(supportsMatchers(HookEventName.SubagentStart)).toBe(true);
expect(supportsMatchers(HookEventName.SubagentStop)).toBe(true);
expect(supportsMatchers(HookEventName.PreCompact)).toBe(true);
expect(supportsMatchers(HookEventName.PostCompact)).toBe(true);
expect(supportsMatchers(HookEventName.StopFailure)).toBe(true);
});
it('returns false for events without matchers', () => {
expect(supportsMatchers(HookEventName.Stop)).toBe(false);
expect(supportsMatchers(HookEventName.UserPromptSubmit)).toBe(false);
expect(supportsMatchers(HookEventName.TodoCreated)).toBe(false);
expect(supportsMatchers(HookEventName.TodoCompleted)).toBe(false);
});
it('returns false for unknown events', () => {
expect(supportsMatchers('unknown_event' as HookEventName)).toBe(false);
});
it('covers every HookEventName value and matches core dispatch', () => {
for (const event of Object.values(HookEventName)) {
expect(supportsMatchers(event)).toBe(hookEventSupportsMatcher(event));
}
});
});
describe('createEmptyHookEventInfo', () => {
it('should create empty info for PreToolUse', () => {
const info = createEmptyHookEventInfo(HookEventName.PreToolUse);
@ -196,7 +274,7 @@ describe('hooks constants', () => {
'Input to command is JSON of tool call arguments.',
);
expect(info.exitCodes).toHaveLength(3);
expect(info.configs).toEqual([]);
expect(info.matcherGroups).toEqual([]);
});
it('should create empty info for Stop', () => {
@ -208,7 +286,7 @@ describe('hooks constants', () => {
);
expect(info.description).toBe('');
expect(info.exitCodes).toHaveLength(3);
expect(info.configs).toEqual([]);
expect(info.matcherGroups).toEqual([]);
});
it('should create empty info for unknown event', () => {
@ -218,7 +296,7 @@ describe('hooks constants', () => {
expect(info.shortDescription).toBe('');
expect(info.description).toBe('');
expect(info.exitCodes).toEqual([]);
expect(info.configs).toEqual([]);
expect(info.matcherGroups).toEqual([]);
});
it('should create empty info for TodoCreated', () => {
@ -228,7 +306,7 @@ describe('hooks constants', () => {
expect(info.shortDescription).toBe('When a new todo item is created');
expect(info.description).toContain('todo_id');
expect(info.exitCodes).toHaveLength(3);
expect(info.configs).toEqual([]);
expect(info.matcherGroups).toEqual([]);
});
it('should create empty info for TodoCompleted', () => {
@ -240,7 +318,7 @@ describe('hooks constants', () => {
);
expect(info.description).toContain('previous_status');
expect(info.exitCodes).toHaveLength(3);
expect(info.configs).toEqual([]);
expect(info.matcherGroups).toEqual([]);
});
});
});

View File

@ -4,7 +4,11 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { HooksConfigSource, HookEventName } from '@qwen-code/qwen-code-core';
import {
HooksConfigSource,
HookEventName,
hookEventSupportsMatcher,
} from '@qwen-code/qwen-code-core';
import type { HookExitCode, HookEventDisplayInfo } from './types.js';
import { t } from '../../../i18n/index.js';
@ -90,6 +94,20 @@ export function getHookExitCodes(eventName: string): HookExitCode[] {
description: t('show stderr to user only but continue with compaction'),
},
],
[HookEventName.PostCompact]: [
{ code: 0, description: t('stdout/stderr not shown') },
{ code: 'Other', description: t('show stderr to user only') },
],
[HookEventName.StopFailure]: [
{
code: 0,
description: t('fire-and-forget; exit status is ignored'),
},
{
code: 'Other',
description: t('fire-and-forget; exit status is ignored'),
},
],
[HookEventName.PermissionRequest]: [
{ code: 0, description: t('use hook decision if provided') },
{ code: 'Other', description: t('show stderr to user only') },
@ -137,6 +155,10 @@ export function getHookShortDescription(eventName: string): string {
'Right before a subagent concludes its response',
),
[HookEventName.PreCompact]: t('Before conversation compaction'),
[HookEventName.PostCompact]: t('After conversation compaction'),
[HookEventName.StopFailure]: t(
'When the turn ends due to an API error (fires instead of Stop)',
),
[HookEventName.SessionEnd]: t('When a session is ending'),
[HookEventName.PermissionRequest]: t(
'When a permission dialog is displayed',
@ -186,6 +208,12 @@ export function getHookDescription(eventName: string): string {
[HookEventName.PreCompact]: t(
'Input to command is JSON with compaction details.',
),
[HookEventName.PostCompact]: t(
'Input to command is JSON with trigger (manual/auto) and compact_summary. Output is ignored for control purposes.',
),
[HookEventName.StopFailure]: t(
'Input to command is JSON with error (rate_limit, authentication_failed, billing_error, invalid_request, server_error, max_output_tokens, unknown) and optional error_details. Fire-and-forget: output and exit status are ignored.',
),
[HookEventName.PermissionRequest]: t(
'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.',
),
@ -218,19 +246,13 @@ export function getTranslatedSourceDisplayMap(): Record<
};
}
/**
* List of hook events to display in the UI
* Automatically synced with HookEventName enum from core.
* Note: Order follows the enum definition order. If UI presentation order
* needs to be different (e.g., grouped by lifecycle phase), consider using
* an explicit sorted array instead. Current enum order is acceptable for display.
*/
export const DISPLAY_HOOK_EVENTS: HookEventName[] =
Object.values(HookEventName);
/**
* Create empty hook event display info
*/
export function supportsMatchers(eventName: HookEventName): boolean {
return hookEventSupportsMatcher(eventName);
}
export function createEmptyHookEventInfo(
eventName: HookEventName,
): HookEventDisplayInfo {
@ -239,6 +261,6 @@ export function createEmptyHookEventInfo(
shortDescription: getHookShortDescription(eventName),
description: getHookDescription(eventName),
exitCodes: getHookExitCodes(eventName),
configs: [],
matcherGroups: [],
};
}

View File

@ -0,0 +1,244 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import {
HookEventName,
HooksConfigSource,
HookType,
} from '@qwen-code/qwen-code-core';
import type { HookEventDisplayInfo } from './types.js';
import {
addConfigToMatcherGroup,
getAllConfigs,
normalizeMatcher,
} from './matcherGrouping.js';
function emptyHookInfo(): HookEventDisplayInfo {
return {
event: HookEventName.PreToolUse,
shortDescription: '',
description: '',
exitCodes: [],
matcherGroups: [],
};
}
describe('normalizeMatcher', () => {
it('returns "*" when matcher is undefined', () => {
expect(normalizeMatcher(undefined)).toBe('*');
});
it('returns "*" when matcher is empty string', () => {
expect(normalizeMatcher('')).toBe('*');
});
it('returns "*" when matcher is only whitespace', () => {
expect(normalizeMatcher(' ')).toBe('*');
});
it('returns the trimmed matcher when set', () => {
expect(normalizeMatcher(' Bash ')).toBe('Bash');
});
it('preserves regex-style matchers', () => {
expect(normalizeMatcher('Edit|Write')).toBe('Edit|Write');
});
});
describe('addConfigToMatcherGroup', () => {
it('creates a new group for an unseen matcher', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/x.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups).toHaveLength(1);
expect(info.matcherGroups[0].matcher).toBe('Bash');
expect(info.matcherGroups[0].configs).toHaveLength(1);
expect(getAllConfigs(info)).toHaveLength(1);
});
it('reuses the existing group for the same matcher', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.Project,
sourceDisplay: 'Local Settings',
enabled: true,
});
expect(info.matcherGroups).toHaveLength(1);
expect(info.matcherGroups[0].configs).toHaveLength(2);
expect(getAllConfigs(info)).toHaveLength(2);
});
it('buckets undefined / empty matchers into "*"', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, undefined, undefined, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, '', undefined, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups).toHaveLength(1);
expect(info.matcherGroups[0].matcher).toBe('*');
expect(info.matcherGroups[0].configs).toHaveLength(2);
});
it('writes the normalized matcher onto the stored config', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, undefined, undefined, {
config: { type: HookType.Command, command: '/x.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(getAllConfigs(info)[0].matcher).toBe('*');
expect(info.matcherGroups[0].configs[0].matcher).toBe('*');
});
it('promotes group.sequential to true when any handler is sequential', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', false, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, 'Bash', true, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups[0].sequential).toBe(true);
});
it('normalizes missing sequential to a false boolean, not undefined', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, 'Bash', false, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups[0].sequential).toBe(false);
expect(info.matcherGroups[0].sequential).not.toBe(undefined);
const flat = getAllConfigs(info);
expect(flat[0].sequential).toBe(false);
expect(flat[1].sequential).toBe(false);
});
it('preserves insertion order across matchers', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, 'Edit|Write', undefined, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, undefined, undefined, {
config: { type: HookType.Command, command: '/c.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups.map((g) => g.matcher)).toEqual([
'Bash',
'Edit|Write',
'*',
]);
});
it('keeps non-matcher events in original handler order', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(
info,
'A',
undefined,
{
config: { type: HookType.Command, command: '/first.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
},
false,
);
addConfigToMatcherGroup(
info,
'B',
undefined,
{
config: { type: HookType.Command, command: '/second.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
},
false,
);
addConfigToMatcherGroup(
info,
'A',
undefined,
{
config: { type: HookType.Command, command: '/third.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
},
false,
);
expect(info.matcherGroups).toHaveLength(1);
expect(info.matcherGroups[0].matcher).toBe('*');
expect(
getAllConfigs(info).map((config) =>
config.config.type === HookType.Command ? config.config.command : '',
),
).toEqual(['/first.sh', '/second.sh', '/third.sh']);
});
});

View File

@ -0,0 +1,50 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import type { HookConfigDisplayInfo, HookEventDisplayInfo } from './types.js';
export function normalizeMatcher(matcher?: string): string {
const trimmed = matcher?.trim();
return trimmed ? trimmed : '*';
}
export function addConfigToMatcherGroup(
hookInfo: HookEventDisplayInfo,
matcher: string | undefined,
sequential: boolean | undefined,
configInfo: HookConfigDisplayInfo,
groupByMatcher = true,
): void {
const normalizedMatcher = groupByMatcher ? normalizeMatcher(matcher) : '*';
const normalizedSequential = sequential ?? false;
const normalizedConfig: HookConfigDisplayInfo = {
...configInfo,
matcher: normalizedMatcher,
sequential: normalizedSequential,
};
let group = hookInfo.matcherGroups.find(
(candidate) => candidate.matcher === normalizedMatcher,
);
if (!group) {
group = {
matcher: normalizedMatcher,
sequential: normalizedSequential,
configs: [],
};
hookInfo.matcherGroups.push(group);
} else if (normalizedSequential) {
group.sequential = true;
}
group.configs.push(normalizedConfig);
}
export function getAllConfigs(
hookInfo: HookEventDisplayInfo,
): HookConfigDisplayInfo[] {
return hookInfo.matcherGroups.flatMap((group) => group.configs);
}

View File

@ -0,0 +1,115 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HooksConfigSource, HookType } from '@qwen-code/qwen-code-core';
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
import {
formatSourceLabel,
formatSourceLabels,
getConfigSourceDisplay,
} from './sourceLabels.js';
import type { HookConfigDisplayInfo } from './types.js';
function makeConfig(
source: HooksConfigSource,
sourceDisplay = '',
): HookConfigDisplayInfo {
return {
config: { type: HookType.Command, command: '/x.sh' },
source,
sourceDisplay,
enabled: true,
};
}
describe('sourceLabels', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('formatSourceLabel', () => {
it('returns short label for each known source', () => {
expect(formatSourceLabel(HooksConfigSource.User)).toBe('User');
expect(formatSourceLabel(HooksConfigSource.Project)).toBe('Project');
expect(formatSourceLabel(HooksConfigSource.System)).toBe('System');
expect(formatSourceLabel(HooksConfigSource.Extensions)).toBe('Extension');
expect(formatSourceLabel(HooksConfigSource.Session)).toBe('Session');
});
it('falls back to the raw source string for unknown values', () => {
expect(formatSourceLabel('mystery' as HooksConfigSource)).toBe('mystery');
});
});
describe('formatSourceLabels', () => {
it('returns a single label for a single-source group', () => {
const configs = [
makeConfig(HooksConfigSource.User),
makeConfig(HooksConfigSource.User),
];
expect(formatSourceLabels(configs)).toBe('User');
});
it('joins distinct labels with comma + space for multi-source groups', () => {
const configs = [
makeConfig(HooksConfigSource.User),
makeConfig(HooksConfigSource.Project),
makeConfig(HooksConfigSource.Extensions),
];
expect(formatSourceLabels(configs)).toBe('User, Project, Extension');
});
it('preserves insertion order across distinct sources', () => {
const configs = [
makeConfig(HooksConfigSource.Project),
makeConfig(HooksConfigSource.User),
];
expect(formatSourceLabels(configs)).toBe('Project, User');
});
it('returns empty string when there are no configs', () => {
expect(formatSourceLabels([])).toBe('');
});
});
describe('getConfigSourceDisplay', () => {
it('returns the translated long label for non-extension sources', () => {
expect(getConfigSourceDisplay(makeConfig(HooksConfigSource.User))).toBe(
'User Settings',
);
expect(
getConfigSourceDisplay(makeConfig(HooksConfigSource.Project)),
).toBe('Local Settings');
expect(getConfigSourceDisplay(makeConfig(HooksConfigSource.System))).toBe(
'System Settings',
);
});
it('appends the extension name for Extensions-source configs', () => {
expect(
getConfigSourceDisplay(
makeConfig(HooksConfigSource.Extensions, 'my-ext'),
),
).toBe('Extensions (my-ext)');
});
it('uses the long "Session (temporary)" label for session-source configs', () => {
expect(
getConfigSourceDisplay(makeConfig(HooksConfigSource.Session)),
).toBe('Session (temporary)');
});
it('falls back to the raw source string for unknown sources', () => {
const config = makeConfig('mystery' as HooksConfigSource);
expect(getConfigSourceDisplay(config)).toBe('mystery');
});
});
});

View File

@ -0,0 +1,44 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { HooksConfigSource } from '@qwen-code/qwen-code-core';
import type { HookConfigDisplayInfo } from './types.js';
import { getTranslatedSourceDisplayMap } from './constants.js';
import { t } from '../../../i18n/index.js';
export function formatSourceLabel(source: HooksConfigSource): string {
switch (source) {
case HooksConfigSource.User:
return t('User');
case HooksConfigSource.Project:
return t('Project');
case HooksConfigSource.System:
return t('System');
case HooksConfigSource.Extensions:
return t('Extension');
case HooksConfigSource.Session:
return t('Session');
default:
return source;
}
}
export function formatSourceLabels(configs: HookConfigDisplayInfo[]): string {
return Array.from(
new Set(configs.map((config) => formatSourceLabel(config.source))),
).join(', ');
}
export function getConfigSourceDisplay(config: {
source: HooksConfigSource;
sourceDisplay: string;
}): string {
const sourceDisplayMap = getTranslatedSourceDisplayMap();
if (config.source === HooksConfigSource.Extensions) {
return `${sourceDisplayMap[HooksConfigSource.Extensions]} (${config.sourceDisplay})`;
}
return sourceDisplayMap[config.source] || config.source;
}

View File

@ -10,53 +10,46 @@ import type {
HookEventName,
} from '@qwen-code/qwen-code-core';
/**
* Exit code description for hooks
*/
export interface HookExitCode {
code: number | string;
description: string;
}
/**
* UI display information for a hook event
*/
export interface HookEventDisplayInfo {
event: HookEventName;
shortDescription: string;
description: string;
exitCodes: HookExitCode[];
matcherGroups: HookMatcherDisplayInfo[];
}
export interface HookMatcherDisplayInfo {
matcher: string;
sequential?: boolean;
configs: HookConfigDisplayInfo[];
}
/**
* UI display information for a hook configuration
*/
export interface HookConfigDisplayInfo {
config: HookConfig;
source: HooksConfigSource;
sourceDisplay: string;
sourcePath?: string;
matcher?: string;
sequential?: boolean;
enabled: boolean;
}
/**
* Hook management dialog step names
*/
export const HOOKS_MANAGEMENT_STEPS = {
HOOKS_DISABLED: 'hooks_disabled',
HOOKS_LIST: 'hooks_list',
HOOK_DETAIL: 'hook_detail',
HOOK_MATCHER_DETAIL: 'hook_matcher_detail',
HOOK_CONFIG_DETAIL: 'hook_config_detail',
} as const;
export type HooksManagementStep =
(typeof HOOKS_MANAGEMENT_STEPS)[keyof typeof HOOKS_MANAGEMENT_STEPS];
/**
* Props for HooksManagementDialog
*/
export interface HooksManagementDialogProps {
onClose: () => void;
}

View File

@ -2462,7 +2462,7 @@ export const useGeminiStream = (
const toolName = toolCall.request.name;
const fileName = path.basename(filePath);
const toolCallWithSnapshotFileName = `${timestamp}-${fileName}-${toolName}.json`;
const clientHistory = await geminiClient?.getHistory();
const clientHistory = geminiClient?.getHistoryShallow();
const toolCallWithSnapshotFilePath = path.join(
checkpointDir,
toolCallWithSnapshotFileName,

View File

@ -8,6 +8,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import * as child_process from 'child_process';
import { StreamingState } from '../types.js';
import type { StatusLinePresetReasoning } from '../statusLinePresets.js';
const debugLogMock = vi.hoisted(() => ({
log: vi.fn(),
@ -49,11 +50,20 @@ vi.mock('../contexts/UIStateContext.js', () => ({
useUIState: () => mockUIState,
}));
type MockContentGeneratorConfig = {
contextWindowSize: number;
reasoning?: StatusLinePresetReasoning;
};
const getMockContentGeneratorConfig = (): MockContentGeneratorConfig => ({
contextWindowSize: 131072,
});
const mockConfig = {
getTargetDir: vi.fn(() => '/test/dir'),
getModel: vi.fn(() => 'test-model'),
getCliVersion: vi.fn(() => '1.0.0'),
getContentGeneratorConfig: vi.fn(() => ({ contextWindowSize: 131072 })),
getContentGeneratorConfig: vi.fn(getMockContentGeneratorConfig),
};
vi.mock('../contexts/ConfigContext.js', () => ({
useConfig: () => mockConfig,
@ -149,6 +159,9 @@ describe('useStatusLine', () => {
mockUIState.sessionStats.metrics.files.totalLinesRemoved = 0;
mockVimMode.vimEnabled = false;
mockVimMode.vimMode = 'INSERT';
mockConfig.getContentGeneratorConfig.mockReturnValue({
contextWindowSize: 131072,
});
// Dynamic import to get fresh module after mocks
const mod = await import('./useStatusLine.js');
@ -236,6 +249,21 @@ describe('useStatusLine', () => {
expect(result.current.lines).toEqual(['test-model']);
});
it('renders model-with-reasoning and model-only together', () => {
mockConfig.getContentGeneratorConfig.mockReturnValue({
contextWindowSize: 131072,
reasoning: { effort: 'high' },
});
setStatusLineConfig({
type: 'preset',
items: ['model', 'model-with-reasoning'],
});
const { result } = renderHook(() => useStatusLine());
expect(child_process.exec).not.toHaveBeenCalled();
expect(result.current.lines).toEqual(['test-model high | test-model']);
});
it('refreshes when status line settings are saved in the same process', async () => {
mockUIState.branchName = 'dragon/feat-reproduce-skill';
setStatusLineConfig({

View File

@ -373,12 +373,13 @@ export function useStatusLine(): {
const { totalInputTokens, totalOutputTokens } = aggregateModelTokens(m);
const contextWindowSize =
cfg.getContentGeneratorConfig()?.contextWindowSize || 0;
const contentGeneratorConfig = cfg.getContentGeneratorConfig();
const contextWindowSize = contentGeneratorConfig?.contextWindowSize || 0;
const data = buildStatusLinePresetData({
sessionId: stats.sessionId,
version: cfg.getCliVersion(),
modelDisplayName: ui.currentModel || cfg.getModel(),
reasoning: contentGeneratorConfig?.reasoning,
currentDir,
branch: ui.branchName,
pullRequestNumber: pullRequestNumberRef.current,

View File

@ -11,15 +11,18 @@ import {
buildStatusLinePresetData,
buildStatusLinePresetLines,
DEFAULT_STATUS_LINE_PRESET_CONFIG,
formatModelWithReasoning,
formatTokenCount,
getRunStateLabel,
inferPullRequestNumber,
normalizeStatusLinePresetConfig,
orderStatusLinePresetItems,
STATUS_LINE_PRESET_ITEM_IDS,
STATUS_LINE_PRESET_ITEMS,
} from './statusLinePresets.js';
describe('statusLinePresets', () => {
it('normalizes valid preset configs and drops unknown items', () => {
it('normalizes valid preset configs and orders items by priority', () => {
expect(
normalizeStatusLinePresetConfig({
type: 'preset',
@ -54,7 +57,51 @@ describe('statusLinePresets', () => {
).toEqual(DEFAULT_STATUS_LINE_PRESET_CONFIG);
});
it('renders available preset items and omits unavailable optional fields', () => {
it('keeps default preset items in priority order', () => {
expect(DEFAULT_STATUS_LINE_PRESET_CONFIG.items).toEqual(
orderStatusLinePresetItems(
[...DEFAULT_STATUS_LINE_PRESET_CONFIG.items].reverse(),
),
);
});
it('orders preset items directly', () => {
expect(orderStatusLinePresetItems([])).toEqual([]);
expect(orderStatusLinePresetItems(['bogus'])).toEqual([]);
expect(orderStatusLinePresetItems([42, null])).toEqual([]);
expect(
orderStatusLinePresetItems([
'run-state',
'model',
'git-branch',
'model',
'context-remaining',
]),
).toEqual(['model', 'git-branch', 'context-remaining', 'run-state']);
});
it('formats model reasoning directly', () => {
expect(formatModelWithReasoning('qwen3-code-plus', false)).toBe(
'qwen3-code-plus reasoning off',
);
expect(
formatModelWithReasoning('qwen3-code-plus', { effort: 'high' }),
).toBe('qwen3-code-plus high');
expect(
formatModelWithReasoning('qwen3-code-plus', { effort: undefined }),
).toBe('qwen3-code-plus');
expect(formatModelWithReasoning('qwen3-code-plus', undefined)).toBe(
'qwen3-code-plus',
);
});
it('labels the plain model preset as model-only', () => {
expect(
STATUS_LINE_PRESET_ITEMS.find((item) => item.id === 'model')?.label,
).toBe('model-only');
});
it('renders available preset items in priority order', () => {
const data = buildStatusLinePresetData({
sessionId: 'session-123',
version: '1.2.3',
@ -75,12 +122,12 @@ describe('statusLinePresets', () => {
{
type: 'preset',
items: [
'model',
'context-remaining',
'current-dir',
'pull-request-number',
'branch-changes',
'run-state',
'model',
'branch-changes',
'pull-request-number',
'current-dir',
'context-remaining',
],
},
data,
@ -95,6 +142,7 @@ describe('statusLinePresets', () => {
sessionId: 'session-123',
version: '1.2.3',
modelDisplayName: 'qwen3-code-plus',
reasoning: { effort: 'high' },
currentDir: '/repo/project',
branch: 'feature/pr-4087-statusline',
contextWindowSize: 1000,
@ -115,11 +163,67 @@ describe('statusLinePresets', () => {
data,
),
).toEqual([
'qwen3-code-plus | Context 75% left | /repo/project | Context 25% used | feature/pr-4087-statusline | project | #4087 | +12 -3 | Ready | v1.2.3 | 1.0k window | 250 used | 1.2k in | 340 out | session-123',
'qwen3-code-plus high | qwen3-code-plus | feature/pr-4087-statusline | Context 75% left | 1.2k in | 340 out | /repo/project | project | #4087 | +12 -3 | Context 25% used | Ready | v1.2.3 | 1.0k window | 250 used | session-123',
]);
});
it('treats model and model-with-reasoning as mutually exclusive', () => {
it('renders model and model-with-reasoning together', () => {
const data = buildStatusLinePresetData({
sessionId: 'session-123',
version: '1.2.3',
modelDisplayName: 'qwen3-code-plus',
reasoning: { effort: 'high' },
currentDir: '/repo/project',
branch: undefined,
contextWindowSize: 0,
currentUsage: 0,
totalInputTokens: 0,
totalOutputTokens: 0,
totalLinesAdded: 0,
totalLinesRemoved: 0,
streamingState: StreamingState.Idle,
});
expect(
buildStatusLinePresetLines(
{
type: 'preset',
items: ['model', 'model-with-reasoning'],
},
data,
),
).toEqual(['qwen3-code-plus high | qwen3-code-plus']);
});
it('shows when reasoning is disabled', () => {
const data = buildStatusLinePresetData({
sessionId: 'session-123',
version: '1.2.3',
modelDisplayName: 'qwen3-code-plus',
reasoning: false,
currentDir: '/repo/project',
branch: undefined,
contextWindowSize: 0,
currentUsage: 0,
totalInputTokens: 0,
totalOutputTokens: 0,
totalLinesAdded: 0,
totalLinesRemoved: 0,
streamingState: StreamingState.Idle,
});
expect(
buildStatusLinePresetLines(
{
type: 'preset',
items: ['model-with-reasoning'],
},
data,
),
).toEqual(['qwen3-code-plus reasoning off']);
});
it('falls back to the model name when reasoning is unset', () => {
const data = buildStatusLinePresetData({
sessionId: 'session-123',
version: '1.2.3',
@ -139,7 +243,7 @@ describe('statusLinePresets', () => {
buildStatusLinePresetLines(
{
type: 'preset',
items: ['model-with-reasoning', 'model'],
items: ['model-with-reasoning'],
},
data,
),

View File

@ -9,20 +9,20 @@ import { StreamingState } from './types.js';
export const STATUS_LINE_PRESET_ITEM_IDS = [
'model-with-reasoning',
'context-remaining',
'current-dir',
'context-used',
'git-branch',
'model',
'git-branch',
'context-remaining',
'total-input-tokens',
'total-output-tokens',
'current-dir',
'project-name',
'pull-request-number',
'branch-changes',
'context-used',
'run-state',
'qwen-version',
'context-window-size',
'used-tokens',
'total-input-tokens',
'total-output-tokens',
'session-id',
] as const;
@ -42,10 +42,18 @@ export interface StatusLinePresetConfig {
useThemeColors?: boolean;
}
export type StatusLinePresetReasoning =
| false
| {
effort?: 'low' | 'medium' | 'high' | 'max';
}
| undefined;
export interface StatusLinePresetData {
sessionId: string;
version: string;
modelDisplayName: string;
reasoning: StatusLinePresetReasoning;
currentDir: string;
projectName: string | undefined;
branch: string | undefined;
@ -81,22 +89,9 @@ export const STATUS_LINE_PRESET_ITEMS: readonly StatusLinePresetItem[] = [
defaultSelected: true,
},
{
id: 'context-remaining',
label: 'context-remaining',
description: 'Percentage of context window remaining',
defaultSelected: true,
},
{
id: 'current-dir',
label: 'current-dir',
description: 'Current working directory',
defaultSelected: true,
},
{
id: 'context-used',
label: 'context-used',
description: 'Percentage of context window used',
defaultSelected: true,
id: 'model',
label: 'model-only',
description: 'Current model name without reasoning level',
},
{
id: 'git-branch',
@ -105,9 +100,26 @@ export const STATUS_LINE_PRESET_ITEMS: readonly StatusLinePresetItem[] = [
defaultSelected: true,
},
{
id: 'model',
label: 'model',
description: 'Current model name',
id: 'context-remaining',
label: 'context-remaining',
description: 'Percentage of context window remaining',
defaultSelected: true,
},
{
id: 'total-input-tokens',
label: 'total-input-tokens',
description: 'Total input tokens used in session',
},
{
id: 'total-output-tokens',
label: 'total-output-tokens',
description: 'Total output tokens used in session',
},
{
id: 'current-dir',
label: 'current-dir',
description: 'Current working directory',
defaultSelected: true,
},
{
id: 'project-name',
@ -124,6 +136,12 @@ export const STATUS_LINE_PRESET_ITEMS: readonly StatusLinePresetItem[] = [
label: 'branch-changes',
description: 'Session file changes added and removed',
},
{
id: 'context-used',
label: 'context-used',
description: 'Percentage of context window used',
defaultSelected: true,
},
{
id: 'run-state',
label: 'run-state',
@ -144,16 +162,6 @@ export const STATUS_LINE_PRESET_ITEMS: readonly StatusLinePresetItem[] = [
label: 'used-tokens',
description: 'Current prompt tokens used',
},
{
id: 'total-input-tokens',
label: 'total-input-tokens',
description: 'Total input tokens used in session',
},
{
id: 'total-output-tokens',
label: 'total-output-tokens',
description: 'Total output tokens used in session',
},
{
id: 'session-id',
label: 'session-id',
@ -165,11 +173,26 @@ const STATUS_LINE_PRESET_ITEM_ID_SET = new Set<string>(
STATUS_LINE_PRESET_ITEM_IDS,
);
export function orderStatusLinePresetItems(
items: readonly unknown[],
): StatusLinePresetItemId[] {
const selectedItems = new Set(
items.filter(
(item): item is StatusLinePresetItemId =>
typeof item === 'string' && STATUS_LINE_PRESET_ITEM_ID_SET.has(item),
),
);
return STATUS_LINE_PRESET_ITEM_IDS.filter((item) => selectedItems.has(item));
}
export const DEFAULT_STATUS_LINE_PRESET_CONFIG: StatusLinePresetConfig = {
type: 'preset',
useThemeColors: true,
items: STATUS_LINE_PRESET_ITEMS.filter((item) => item.defaultSelected).map(
(item) => item.id,
items: orderStatusLinePresetItems(
STATUS_LINE_PRESET_ITEMS.filter((item) => item.defaultSelected).map(
(item) => item.id,
),
),
};
@ -186,12 +209,8 @@ export function normalizeStatusLinePresetConfig(
}
const hasItemsArray = Array.isArray(candidate['items']);
const rawItems = hasItemsArray ? (candidate['items'] as unknown[]) : [];
const items = hasItemsArray
? rawItems.filter(
(item): item is StatusLinePresetItemId =>
typeof item === 'string' && STATUS_LINE_PRESET_ITEM_ID_SET.has(item),
)
? orderStatusLinePresetItems(candidate['items'] as unknown[])
: [];
return {
@ -200,9 +219,7 @@ export function normalizeStatusLinePresetConfig(
typeof candidate['useThemeColors'] === 'boolean'
? candidate['useThemeColors']
: true,
items: hasItemsArray
? [...new Set(items)]
: [...DEFAULT_STATUS_LINE_PRESET_CONFIG.items],
items: hasItemsArray ? items : [...DEFAULT_STATUS_LINE_PRESET_CONFIG.items],
};
}
@ -240,6 +257,19 @@ export function getRunStateLabel(state: StreamingState): string {
}
}
export function formatModelWithReasoning(
modelDisplayName: string,
reasoning: StatusLinePresetReasoning,
): string {
if (reasoning === false) {
return `${modelDisplayName} reasoning off`;
}
if (reasoning?.effort) {
return `${modelDisplayName} ${reasoning.effort}`;
}
return modelDisplayName;
}
export function inferPullRequestNumber(
branch: string | undefined,
): string | undefined {
@ -256,6 +286,7 @@ export function buildStatusLinePresetData(params: {
sessionId: string;
version: string | undefined;
modelDisplayName: string | undefined;
reasoning?: StatusLinePresetReasoning;
currentDir: string;
branch: string | undefined;
pullRequestNumber?: string | undefined;
@ -284,6 +315,7 @@ export function buildStatusLinePresetData(params: {
sessionId: params.sessionId,
version: params.version || 'unknown',
modelDisplayName: params.modelDisplayName || 'unknown',
reasoning: params.reasoning,
currentDir: params.currentDir,
projectName: nodePath.basename(params.currentDir) || undefined,
branch: params.branch,
@ -305,20 +337,16 @@ export function buildStatusLinePresetParts(
data: StatusLinePresetData,
): string[] {
const parts: string[] = [];
const seen = new Set<StatusLinePresetItemId>();
for (const item of config.items) {
if (seen.has(item)) {
continue;
}
seen.add(item);
for (const item of orderStatusLinePresetItems(config.items)) {
switch (item) {
case 'model-with-reasoning':
parts.push(
formatModelWithReasoning(data.modelDisplayName, data.reasoning),
);
break;
case 'model':
parts.push(data.modelDisplayName);
seen.add('model');
seen.add('model-with-reasoning');
break;
case 'context-remaining':
if (data.contextWindowSize > 0) {

View File

@ -234,7 +234,7 @@ describe('getStickyTodos', () => {
});
describe('sticky todo layout helpers', () => {
it('keeps the layout key stable for status-only updates', () => {
it('changes the layout key for status-only updates', () => {
const pendingTodos = [
{
id: 'todo-1',
@ -250,7 +250,7 @@ describe('sticky todo layout helpers', () => {
},
];
expect(getStickyTodosLayoutKey(pendingTodos, 64, 5)).toBe(
expect(getStickyTodosLayoutKey(pendingTodos, 64, 5)).not.toBe(
getStickyTodosLayoutKey(inProgressTodos, 64, 5),
);
expect(getStickyTodosRenderKey(pendingTodos)).not.toBe(
@ -258,6 +258,33 @@ describe('sticky todo layout helpers', () => {
);
});
it('uses the rendered open todos for the layout key', () => {
const todos = [
{
id: 'todo-1',
content: 'Finished task',
status: 'completed' as const,
},
{
id: 'todo-2',
content: 'Active task',
status: 'in_progress' as const,
},
{
id: 'todo-3',
content: 'Pending task',
status: 'pending' as const,
},
];
expect(getStickyTodosLayoutKey(todos, 64, 5)).toBe(
getStickyTodosLayoutKey(todos.slice(1), 64, 5),
);
expect(getStickyTodosLayoutKey(todos, 64, 1)).not.toBe(
getStickyTodosLayoutKey(todos, 64, 2),
);
});
it('changes the layout key when wrapping-sensitive inputs change', () => {
const todos = [
{

View File

@ -181,14 +181,17 @@ export function getStickyTodosLayoutKey(
}
const visibleTodoCount = clampStickyTodoVisibleItems(maxVisibleItems);
const visibleTodos = todos.slice(0, visibleTodoCount);
const hasHiddenTodos = todos.length > visibleTodos.length;
const orderedOpenTodos = getOrderedStickyTodos(todos).filter(
(todo) => todo.status !== 'completed',
);
const visibleTodos = orderedOpenTodos.slice(0, visibleTodoCount);
const hasHiddenTodos = orderedOpenTodos.length > visibleTodos.length;
return JSON.stringify({
width,
maxVisibleItems: visibleTodoCount,
hasHiddenTodos,
todos: visibleTodos.map((todo) => [todo.id, todo.content]),
todos: visibleTodos.map((todo) => [todo.id, todo.content, todo.status]),
});
}

View File

@ -20,9 +20,12 @@ import { spawn } from 'node:child_process';
vi.mock('node:child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:child_process')>();
const mockSpawn = vi.fn();
// Named re-exports must be spelled out for vitest ESM mocking to rebind them.
return {
...actual,
spawn: vi.fn(),
default: { ...actual, spawn: mockSpawn },
spawn: mockSpawn,
};
});
@ -275,6 +278,36 @@ describe('relaunchAppInChildProcess', () => {
// Note: Additional integration tests for spawn behavior are complex due to module mocking
// limitations with ES modules. The core logic is tested in relaunchOnExitCode tests.
it('should invoke afterSpawn immediately after spawn, before waiting for child exit', async () => {
process.argv = ['/usr/bin/node', '/app/cli.js'];
const afterSpawn = vi.fn();
let spawned = false;
const mockChild = createMockChildProcess(0, false);
mockedSpawn.mockImplementation(() => {
spawned = true;
return mockChild;
});
const promise = relaunchAppInChildProcess([], [], { afterSpawn });
// Wait until spawn has been called
await vi.waitFor(() => {
expect(spawned).toBe(true);
});
// afterSpawn must have been called before child exits
expect(afterSpawn).toHaveBeenCalledTimes(1);
// Close the child so the promise resolves
mockChild.emit('close', 0);
await expect(promise).rejects.toThrow('PROCESS_EXIT_CALLED');
// afterSpawn should still be called only once (first spawn)
expect(afterSpawn).toHaveBeenCalledTimes(1);
});
it('should handle null exit code from child process', async () => {
process.argv = ['/usr/bin/node', '/app/cli.js'];

View File

@ -28,6 +28,7 @@ export async function relaunchOnExitCode(runner: () => Promise<number>) {
export async function relaunchAppInChildProcess(
additionalNodeArgs: string[],
additionalScriptArgs: string[],
options?: { afterSpawn?: () => void },
) {
if (process.env['QWEN_CODE_NO_RELAUNCH']) {
return;
@ -56,6 +57,15 @@ export async function relaunchAppInChildProcess(
env: newEnv,
});
// Allow the parent to clean up process.env after spawn copies it
// but before the next relaunch iteration.
try {
options?.afterSpawn?.();
} catch (err) {
child.kill();
throw err;
}
return new Promise<number>((resolve, reject) => {
child.on('error', reject);
child.on('close', (code) => {

View File

@ -1,172 +0,0 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
/**
* Tests for the module-level `sessionEnvClaimed` guard in Config.
*
* The guard ensures that only the first Config instance in a process sets
* `process.env['QWEN_CODE_SESSION_ID']`, preventing throwaway instances
* (e.g. telemetry-only) from overwriting the real session's ID.
*
* We use `vi.isolateModules` to get a fresh module scope (resetting the
* module-level flag) for each test.
*/
// Shared mocks needed by Config constructor
vi.mock('node:fs');
vi.mock('node:fs/promises');
vi.mock('../telemetry/index.js', () => ({
QwenLogger: vi.fn().mockImplementation(() => ({
logStartSessionEvent: vi.fn().mockResolvedValue(undefined),
logEndSessionEvent: vi.fn().mockResolvedValue(undefined),
shutdown: vi.fn().mockResolvedValue(undefined),
})),
DEFAULT_TELEMETRY_TARGET: 'none',
DEFAULT_OTLP_ENDPOINT: '',
isTelemetrySdkInitialized: vi.fn().mockReturnValue(false),
shutdownTelemetry: vi.fn().mockResolvedValue(undefined),
refreshSessionContext: vi.fn(),
}));
vi.mock('../core/contentGenerator.js', () => ({
resolveContentGeneratorConfigWithSources: vi.fn().mockReturnValue({
config: { model: 'test-model', apiKey: 'test-key' },
sources: {},
}),
createContentGeneratorConfig: vi.fn().mockReturnValue({}),
createContentGenerator: vi.fn().mockReturnValue({}),
AuthType: { API_KEY: 'apiKey' },
}));
vi.mock('../core/baseLlmClient.js');
vi.mock('../core/toolHookTriggers.js', () => ({
fireNotificationHook: vi.fn().mockResolvedValue({}),
}));
vi.mock('../services/skillManager.js', () => {
const SkillManagerMock = vi.fn();
SkillManagerMock.prototype.startWatching = vi
.fn()
.mockResolvedValue(undefined);
SkillManagerMock.prototype.refreshCache = vi
.fn()
.mockResolvedValue(undefined);
SkillManagerMock.prototype.stopWatching = vi.fn();
SkillManagerMock.prototype.listSkills = vi.fn().mockResolvedValue([]);
SkillManagerMock.prototype.addChangeListener = vi.fn();
SkillManagerMock.prototype.removeChangeListener = vi.fn();
SkillManagerMock.prototype.matchAndActivateByPath = vi
.fn()
.mockResolvedValue([]);
SkillManagerMock.prototype.matchAndActivateByPaths = vi
.fn()
.mockResolvedValue([]);
return { SkillManager: SkillManagerMock };
});
vi.mock('../subagents/subagent-manager.js', () => {
const SubagentManagerMock = vi.fn();
SubagentManagerMock.prototype.loadSessionSubagents = vi.fn();
SubagentManagerMock.prototype.addChangeListener = vi
.fn()
.mockReturnValue(() => {});
SubagentManagerMock.prototype.listSubagents = vi.fn().mockResolvedValue([]);
return { SubagentManager: SubagentManagerMock };
});
vi.mock('../ide/ide-client.js', () => ({
IdeClient: {
getInstance: vi.fn().mockResolvedValue({
getConnectionStatus: vi.fn(),
initialize: vi.fn(),
shutdown: vi.fn(),
}),
},
}));
vi.mock('../memory/const.js', () => ({
setGeminiMdFilename: vi.fn(),
}));
import * as fs from 'node:fs';
import type { Mock } from 'vitest';
import type { ConfigParameters } from './config.js';
const baseParams: ConfigParameters = {
cwd: '/tmp',
targetDir: '/tmp',
debugMode: false,
model: 'test-model',
telemetry: { enabled: false },
usageStatisticsEnabled: false,
overrideExtensions: [],
};
describe('Config sessionEnvClaimed guard', () => {
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env['QWEN_CODE_SESSION_ID'];
delete process.env['QWEN_CODE_SESSION_ID'];
(fs.existsSync as Mock).mockReturnValue(true);
(fs.readdirSync as Mock).mockReturnValue([]);
(fs.statSync as Mock).mockReturnValue({
isDirectory: vi.fn().mockReturnValue(true),
});
vi.mocked(fs.realpathSync).mockImplementation((p) => String(p));
(fs.mkdirSync as Mock).mockImplementation(() => undefined);
(fs.writeFileSync as Mock).mockImplementation(() => undefined);
(fs.renameSync as Mock).mockImplementation(() => undefined);
(fs.copyFileSync as Mock).mockImplementation(() => undefined);
(fs.unlinkSync as Mock).mockImplementation(() => undefined);
(fs.readFileSync as Mock).mockImplementation(() => undefined);
});
afterEach(() => {
if (originalEnv !== undefined) {
process.env['QWEN_CODE_SESSION_ID'] = originalEnv;
} else {
delete process.env['QWEN_CODE_SESSION_ID'];
}
vi.resetModules();
});
it('first Config sets process.env QWEN_CODE_SESSION_ID to its sessionId', async () => {
const { Config } = await import('./config.js');
const config = new Config({ ...baseParams });
expect(process.env['QWEN_CODE_SESSION_ID']).toBe(config.getSessionId());
});
it('subsequent Config does not overwrite the env var set by the first', async () => {
const { Config } = await import('./config.js');
const firstConfig = new Config({ ...baseParams });
const firstSessionId = firstConfig.getSessionId();
// Second Config (e.g. telemetry-only throwaway instance)
const secondConfig = new Config({
...baseParams,
sessionId: 'throwaway-session-id',
});
// The env var should still be the first config's session ID
expect(process.env['QWEN_CODE_SESSION_ID']).toBe(firstSessionId);
expect(process.env['QWEN_CODE_SESSION_ID']).not.toBe(
secondConfig.getSessionId(),
);
});
it('startNewSession updates env var to the new session ID', async () => {
const { Config } = await import('./config.js');
const config = new Config({ ...baseParams });
const originalSessionId = config.getSessionId();
expect(process.env['QWEN_CODE_SESSION_ID']).toBe(originalSessionId);
// Simulate /clear or session switch
config.startNewSession('new-session-uuid-123');
expect(process.env['QWEN_CODE_SESSION_ID']).toBe('new-session-uuid-123');
expect(process.env['QWEN_CODE_SESSION_ID']).not.toBe(originalSessionId);
});
});

View File

@ -16,6 +16,7 @@ import {
} from './config.js';
import { Storage } from './storage.js';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { setGeminiMdFilename as mockSetGeminiMdFilename } from '../memory/const.js';
import {
@ -288,6 +289,13 @@ vi.mock('../ide/ide-client.js', () => ({
import { BaseLlmClient } from '../core/baseLlmClient.js';
const MEMORY_PRESSURE_ENV_KEYS = [
'QWEN_MEMORY_PRESSURE_SOFT',
'QWEN_MEMORY_PRESSURE_HARD',
'QWEN_MEMORY_PRESSURE_CRITICAL',
'QWEN_MEMORY_ENABLE_GC',
];
vi.mock('../core/baseLlmClient.js');
// Mock fireNotificationHook from toolHookTriggers
vi.mock('../core/toolHookTriggers.js', () => ({
@ -328,6 +336,9 @@ describe('Server Config (config.ts)', () => {
beforeEach(() => {
// Reset mocks if necessary
vi.clearAllMocks();
for (const envName of MEMORY_PRESSURE_ENV_KEYS) {
delete process.env[envName];
}
(fs.existsSync as Mock).mockReturnValue(true);
(fs.readdirSync as Mock).mockReturnValue([]);
(fs.statSync as Mock).mockReturnValue({
@ -422,6 +433,192 @@ describe('Server Config (config.ts)', () => {
});
});
describe('MemoryPressureMonitor isolation', () => {
it('returns a distinct monitor for child Configs created via Object.create', async () => {
const parent = new Config(baseParams);
await parent.initialize({ skipGeminiInitialization: true });
const child = Object.create(parent) as Config;
const parentMonitor = parent.getMemoryPressureMonitor();
const childMonitor = child.getMemoryPressureMonitor();
expect(parentMonitor).toBeDefined();
expect(childMonitor).toBeDefined();
expect(childMonitor).not.toBe(parentMonitor);
expect(child.getMemoryPressureMonitor()).toBe(childMonitor);
});
it('resets monitor cleanup state when starting a new session', async () => {
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
const monitor = config.getMemoryPressureMonitor();
expect(monitor).toBeDefined();
const resetSpy = vi.spyOn(monitor!, 'resetForNewSession');
config.startNewSession();
expect(resetSpy).toHaveBeenCalledTimes(1);
});
});
describe('MemoryPressure configuration environment', () => {
const restorers: Array<() => void> = [];
const originalEnv = new Map<string, string | undefined>();
beforeEach(() => {
originalEnv.clear();
for (const envName of MEMORY_PRESSURE_ENV_KEYS) {
originalEnv.set(envName, process.env[envName]);
delete process.env[envName];
}
});
afterEach(() => {
while (restorers.length > 0) {
restorers.pop()?.();
}
for (const [envName, value] of originalEnv) {
if (value === undefined) {
delete process.env[envName];
} else {
process.env[envName] = value;
}
}
originalEnv.clear();
});
function mockMemoryRatio(rssRatio: number, heapUsedBytes = 0): void {
const spy = vi.spyOn(process, 'memoryUsage').mockReturnValue({
rss: Math.ceil(os.totalmem() * rssRatio),
heapTotal: 512 * 1024 * 1024,
heapUsed: heapUsedBytes,
external: 0,
arrayBuffers: 0,
});
restorers.push(() => spy.mockRestore());
}
function mockStderrWrite(): Mock {
const spy = vi
.spyOn(process.stderr, 'write')
.mockImplementation(() => true);
restorers.push(() => spy.mockRestore());
return spy as unknown as Mock;
}
it('applies valid memory pressure env overrides', async () => {
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.3';
process.env['QWEN_MEMORY_PRESSURE_HARD'] = '0.6';
process.env['QWEN_MEMORY_PRESSURE_CRITICAL'] = '0.9';
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
mockMemoryRatio(0.35);
expect(config.getMemoryPressureMonitor()?.getPressureLevel()).toBe(
'soft',
);
});
it('falls back to defaults and warns on strict env parse failures', async () => {
const stderrSpy = mockStderrWrite();
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.3extra';
process.env['QWEN_MEMORY_PRESSURE_HARD'] = '0.6';
process.env['QWEN_MEMORY_PRESSURE_CRITICAL'] = '0.9';
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
mockMemoryRatio(0.35);
expect(config.getMemoryPressureMonitor()?.getPressureLevel()).toBe(
'normal',
);
expect(stderrSpy).toHaveBeenCalledWith(
expect.stringContaining('Invalid memory pressure config'),
);
});
it('falls back to defaults and warns on invalid threshold ordering', async () => {
const stderrSpy = mockStderrWrite();
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.7';
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
expect(config.getMemoryPressureMonitor()).toBeDefined();
expect(stderrSpy).toHaveBeenCalledWith(
expect.stringContaining(
'softPressureRatio must be < hardPressureRatio',
),
);
});
it.each(['NaN', 'Infinity', '0'])(
'falls back to defaults for invalid soft threshold %s',
async (value) => {
const stderrSpy = mockStderrWrite();
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = value;
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
mockMemoryRatio(0.35);
expect(config.getMemoryPressureMonitor()?.getPressureLevel()).toBe(
'normal',
);
expect(stderrSpy).toHaveBeenCalledWith(
expect.stringContaining('Invalid memory pressure config'),
);
},
);
it('enables explicit GC when requested by env', async () => {
process.env['QWEN_MEMORY_ENABLE_GC'] = '1';
const globalWithGc = global as typeof global & { gc?: () => void };
const originalGc = globalWithGc.gc;
const gcSpy = vi.fn();
Object.defineProperty(globalWithGc, 'gc', {
value: gcSpy,
configurable: true,
});
restorers.push(() => {
if (originalGc) {
Object.defineProperty(globalWithGc, 'gc', {
value: originalGc,
configurable: true,
});
} else {
delete globalWithGc.gc;
}
});
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
mockMemoryRatio(0.85);
config.getMemoryPressureMonitor()?.performCheck();
await Promise.resolve();
expect(gcSpy).toHaveBeenCalledTimes(1);
});
it('child Config monitors inherit the parent memory pressure config snapshot', async () => {
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.3';
process.env['QWEN_MEMORY_PRESSURE_HARD'] = '0.6';
process.env['QWEN_MEMORY_PRESSURE_CRITICAL'] = '0.9';
const parent = new Config(baseParams);
await parent.initialize({ skipGeminiInitialization: true });
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.9';
process.env['QWEN_MEMORY_PRESSURE_HARD'] = '0.95';
process.env['QWEN_MEMORY_PRESSURE_CRITICAL'] = '0.97';
const child = Object.create(parent) as Config;
mockMemoryRatio(0.35);
expect(child.getMemoryPressureMonitor()?.getPressureLevel()).toBe('soft');
});
});
describe('startNewSession', () => {
it('clears the FileReadCache so a new session does not inherit prior reads', () => {
// Regression guard: the file-read cache backs ReadFile's

View File

@ -48,6 +48,12 @@ import { GitService } from '../services/gitService.js';
import { GitWorktreeService } from '../services/gitWorktreeService.js';
import { cleanupStaleAgentWorktrees } from '../services/worktreeCleanup.js';
import { CronScheduler } from '../services/cronScheduler.js';
import {
MemoryPressureMonitor,
DEFAULT_PRESSURE_CONFIG,
validateMemoryPressureConfig,
type MemoryPressureConfig,
} from '../services/memoryPressureMonitor.js';
// Tools — only lightweight imports; tool classes are lazy-loaded via dynamic import
import {
@ -156,6 +162,7 @@ import { MemoryManager } from '../memory/manager.js';
import { CommitAttributionService } from '../services/commitAttribution.js';
const gitCoAuthorLogger = createDebugLogger('GIT_CO_AUTHOR');
const memoryPressureConfigLogger = createDebugLogger('MEMORY_PRESSURE');
import {
ModelsConfig,
@ -849,6 +856,53 @@ function normalizeConfigOutputFormat(
}
}
function loadMemoryPressureConfig(): MemoryPressureConfig {
const config: MemoryPressureConfig = { ...DEFAULT_PRESSURE_CONFIG };
try {
config.softPressureRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_SOFT',
config.softPressureRatio,
);
config.hardPressureRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_HARD',
config.hardPressureRatio,
);
config.criticalRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_CRITICAL',
config.criticalRatio,
);
if (process.env['QWEN_MEMORY_ENABLE_GC'] === '1') {
config.enableExplicitGC = true;
}
validateMemoryPressureConfig(config);
} catch (err) {
const fallbackMsg =
'[QWEN] WARNING: Invalid memory pressure config; using defaults. ' +
`Error: ${getErrorMessage(err)}`;
process.stderr.write(`${fallbackMsg}\n`);
memoryPressureConfigLogger.warn(fallbackMsg);
return { ...DEFAULT_PRESSURE_CONFIG };
}
return config;
}
function readMemoryPressureRatioEnv(envName: string, fallback: number): number {
const raw = process.env[envName];
if (!raw) {
return fallback;
}
const parsed = Number(raw);
if (!Number.isFinite(parsed)) {
throw new Error(`${envName} must be a finite number`);
}
return parsed;
}
/**
* Options for Config.initialize()
*/
@ -872,12 +926,6 @@ const DEFAULT_BARE_CORE_TOOLS = [
ToolNames.SHELL,
];
// Tracks whether the first Config in this process has claimed the global
// QWEN_CODE_SESSION_ID env var. Prevents throwaway Config instances from
// overwriting the real session's ID while still allowing nested qwen-code
// processes to claim their own (they start with a fresh module scope).
let sessionEnvClaimed = false;
export class Config {
private sessionId: string;
private sessionData?: ResumedSessionData;
@ -910,6 +958,8 @@ export class Config {
private pendingMcpBudgetCallback?: (event: McpBudgetEvent) => void;
private promptRegistry!: PromptRegistry;
private subagentManager!: SubagentManager;
private memoryPressureConfig?: MemoryPressureConfig;
private memoryPressureMonitor?: MemoryPressureMonitor;
private readonly backgroundTaskRegistry = new BackgroundTaskRegistry();
private readonly monitorRegistry = new MonitorRegistry();
private backgroundAgentResumeService?: BackgroundAgentResumeService;
@ -1080,16 +1130,6 @@ export class Config {
constructor(params: ConfigParameters) {
this.sessionId = params.sessionId ?? randomUUID();
// Only set the global env marker once per process lifetime, so
// throwaway Config instances (e.g. telemetry-only) don't clobber
// the real interactive session's ID. Uses a module-level flag
// rather than checking env existence — otherwise a nested qwen-code
// launched from within a session would inherit the parent's ID and
// never claim its own.
if (!sessionEnvClaimed && process.env) {
process.env['QWEN_CODE_SESSION_ID'] = this.sessionId;
sessionEnvClaimed = true;
}
this.sessionData = params.sessionData;
setDebugLogSession(this);
this.debugLogger = createDebugLogger();
@ -1523,6 +1563,12 @@ export class Config {
}
this.debugLogger.debug('Skill manager initialized');
this.memoryPressureConfig = loadMemoryPressureConfig();
this.memoryPressureMonitor = new MemoryPressureMonitor(
this,
this.memoryPressureConfig,
);
this.permissionManager = new PermissionManager(this);
this.permissionManager.initialize();
this.debugLogger.debug('Permission manager initialized');
@ -2002,12 +2048,6 @@ export class Config {
const previousSessionId = this.sessionId;
this.sessionId = sessionId ?? randomUUID();
// Unconditional: startNewSession is only called on the canonical Config
// instance (the one that already claimed via sessionEnvClaimed), so this
// correctly updates the env var to reflect the new active session.
if (process.env) {
process.env['QWEN_CODE_SESSION_ID'] = this.sessionId;
}
this.sessionData = sessionData;
setDebugLogSession(this);
this.debugLogger = createDebugLogger();
@ -2024,6 +2064,7 @@ export class Config {
// constructed via Object.create — those should clear their own
// cache, not the parent's.
this.getFileReadCache().clear();
this.getMemoryPressureMonitor()?.resetForNewSession();
this.fileHistoryService = undefined;
refreshSessionContext(this.sessionId);
// The commit-attribution singleton accumulates per-file AI edits
@ -2697,6 +2738,10 @@ export class Config {
return this.userMemory;
}
getOutputLanguageFilePath(): string | undefined {
return this.outputLanguageFilePath;
}
setUserMemory(newUserMemory: string): void {
this.userMemory = newUserMemory;
}
@ -3077,6 +3122,33 @@ export class Config {
return this.geminiClient;
}
/**
* Session-scoped memory pressure monitor. Child Configs created with
* `Object.create(parent)` inherit the parent's monitor through the prototype
* chain until this getter installs an own monitor backed by the inherited
* pressure config snapshot. This mirrors getFileReadCache()'s isolation
* contract while keeping type-safe direct field assignment inside the class.
*/
getMemoryPressureMonitor(): MemoryPressureMonitor | undefined {
if (!Object.prototype.hasOwnProperty.call(this, 'memoryPressureMonitor')) {
const inheritedMonitor = this.memoryPressureMonitor;
if (inheritedMonitor) {
const inheritedConfig = this.memoryPressureConfig;
if (!inheritedConfig) {
throw new Error(
'Inherited memory pressure monitor is missing config',
);
}
this.memoryPressureConfig = { ...inheritedConfig };
this.memoryPressureMonitor = new MemoryPressureMonitor(
this,
this.memoryPressureConfig,
);
}
}
return this.memoryPressureMonitor;
}
getCronScheduler(): CronScheduler {
if (!this.cronScheduler) {
this.cronScheduler = new CronScheduler();

View File

@ -22,7 +22,10 @@ vi.mock('../../utils/request-tokenizer/index.js', () => ({
RequestTokenEstimator: vi.fn(() => mockTokenizer),
}));
type AnthropicCreateArgs = [unknown, { signal?: AbortSignal }?];
type AnthropicCreateArgs = [
unknown,
{ signal?: AbortSignal; headers?: Record<string, string> }?,
];
const anthropicMockState: {
constructorOptions?: Record<string, unknown>;
@ -1013,9 +1016,16 @@ describe('AnthropicContentGenerator', () => {
// generateContent(); make sure the per-request header attaches there
// too so streaming Anthropic/DeepSeek requests stay consistent.
const { AnthropicContentGenerator } = await importGenerator();
// Use message_delta (not bare message_stop) so the empty-stream
// fallback is not triggered — bare message_stop now indicates an empty
// stream and causes a non-streaming retry.
anthropicState.createImpl.mockResolvedValue(
(async function* () {
yield { type: 'message_stop' };
yield {
type: 'message_delta',
delta: { stop_reason: 'end_turn' },
usage: { output_tokens: 1 },
};
})(),
);
@ -1036,6 +1046,10 @@ describe('AnthropicContentGenerator', () => {
void _chunk;
}
// Regression guard: normal streams must NOT trigger the empty-stream
// fallback (which would double latency + API cost).
expect(anthropicState.createImpl).toHaveBeenCalledTimes(1);
const [, options] = anthropicState.lastCreateArgs as AnthropicCreateArgs;
const headers = ((options as { headers?: Record<string, string> })
?.headers || {}) as Record<string, string>;
@ -2416,5 +2430,97 @@ describe('AnthropicContentGenerator', () => {
cachedContentTokenCount: 32_088,
});
});
it('falls back to non-streaming when the stream is empty and surfaces provider errors', async () => {
const { AnthropicContentGenerator } = await importGenerator();
anthropicState.createImpl
.mockResolvedValueOnce(
(async function* () {
// Empty stream: compatible gateways can return HTTP 200 with no SSE
// events when the real failure body is only available non-streaming.
})(),
)
.mockRejectedValueOnce(new Error('400 quota exceeded'));
const generator = new AnthropicContentGenerator(
{
model: 'claude-test',
apiKey: 'test-key',
timeout: 10_000,
maxRetries: 2,
samplingParams: { max_tokens: 123 },
schemaCompliance: 'auto',
},
mockConfig,
);
const stream = await generator.generateContentStream({
model: 'models/ignored',
contents: 'Hello',
} as unknown as GenerateContentParameters);
await expect(async () => {
for await (const _chunk of stream) {
void _chunk;
}
}).rejects.toThrow('400 quota exceeded');
expect(anthropicState.createImpl).toHaveBeenCalledTimes(2);
const [streamingRequest] = anthropicState.createImpl.mock
.calls[0] as AnthropicCreateArgs;
const [fallbackRequest] = anthropicState.createImpl.mock
.calls[1] as AnthropicCreateArgs;
expect(streamingRequest).toEqual(
expect.objectContaining({ stream: true }),
);
expect(fallbackRequest).not.toHaveProperty('stream');
});
it('converts the non-streaming fallback response when an empty stream is recoverable', async () => {
const { AnthropicContentGenerator } = await importGenerator();
anthropicState.createImpl
.mockResolvedValueOnce(
(async function* () {
yield { type: 'message_stop' };
})(),
)
.mockResolvedValueOnce({
id: 'msg-fallback',
model: 'claude-test',
stop_reason: 'end_turn',
content: [{ type: 'text', text: 'fallback ok' }],
usage: { input_tokens: 3, output_tokens: 2 },
});
const generator = new AnthropicContentGenerator(
{
model: 'claude-test',
apiKey: 'test-key',
timeout: 10_000,
maxRetries: 2,
samplingParams: { max_tokens: 123 },
schemaCompliance: 'auto',
},
mockConfig,
);
const stream = await generator.generateContentStream({
model: 'models/ignored',
contents: 'Hello',
} as unknown as GenerateContentParameters);
const chunks: GenerateContentResponse[] = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
expect(anthropicState.createImpl).toHaveBeenCalledTimes(2);
expect(chunks).toHaveLength(1);
expect(chunks[0]?.responseId).toBe('msg-fallback');
expect(chunks[0]?.candidates?.[0]?.content?.parts).toEqual([
{ text: 'fallback ok' },
]);
expect(chunks[0]?.candidates?.[0]?.finishReason).toBe(FinishReason.STOP);
});
});
});

View File

@ -266,7 +266,12 @@ export class AnthropicContentGenerator implements ContentGenerator {
throw redactProxyError(error);
}
return this.processStream(this.redactStreamErrors(stream));
return this.processStreamWithEmptyFallback(
this.redactStreamErrors(stream),
anthropicRequest,
request.config?.abortSignal,
headers,
);
}
async countTokens(
@ -968,6 +973,59 @@ export class AnthropicContentGenerator implements ContentGenerator {
}
}
// Some Anthropic-compatible gateways close the SSE stream with HTTP 200
// but emit no assistant content or stop reason (e.g. billing / quota
// limits hit mid-proxy). When that happens we probe once with the same
// request in non-streaming mode so the real provider error surfaces
// instead of the generic "stream ended without a finish reason".
private async *processStreamWithEmptyFallback(
stream: AsyncIterable<RawMessageStreamEvent>,
fallbackRequest: MessageCreateParamsWithThinking,
abortSignal: AbortSignal | undefined,
headers: Record<string, string> | undefined,
): AsyncGenerator<GenerateContentResponse> {
let hasAssistantPayload = false;
let hasFinishReason = false;
for await (const chunk of this.processStream(stream)) {
const candidates = chunk.candidates ?? [];
hasFinishReason ||= candidates.some(
(candidate) => candidate.finishReason !== undefined,
);
hasAssistantPayload ||= candidates.some((candidate) =>
candidate.content?.parts?.some(
(part) =>
part.text ||
part.thought ||
part.thoughtSignature ||
part.functionCall,
),
);
yield chunk;
}
if (hasAssistantPayload || hasFinishReason) {
return;
}
debugLogger.warn(
'Anthropic stream ended without assistant payload or finish reason; ' +
'probing once with a non-streaming request to surface provider errors.',
);
let response: Message;
try {
runtimeDiagnostics.recordAnthropicWireRequest(fallbackRequest);
response = (await this.client.messages.create(fallbackRequest, {
signal: abortSignal,
...(headers ? { headers } : {}),
})) as Message;
yield this.converter.convertAnthropicResponseToGemini(response);
} catch (error) {
throw redactProxyError(error);
}
}
private buildGeminiChunk(
part?: {
text?: string;

View File

@ -499,6 +499,7 @@ describe('CoreToolScheduler', () => {
disableHooks?: boolean;
onAllToolCallsComplete?: ReturnType<typeof vi.fn>;
onToolCallsUpdate?: ReturnType<typeof vi.fn>;
memoryMonitor?: { scheduleCheck: () => void };
}) {
const ensureTool = vi.fn(
async (name: string) =>
@ -549,6 +550,7 @@ describe('CoreToolScheduler', () => {
getUseModelRouter: () => false,
getGeminiClient: () => null,
getChatRecordingService: () => undefined,
getMemoryPressureMonitor: () => options.memoryMonitor,
getMessageBus: vi.fn().mockReturnValue(options.messageBus),
getHookSystem: vi.fn().mockReturnValue(options.hookSystem),
getDisableAllHooks: vi
@ -630,6 +632,43 @@ describe('CoreToolScheduler', () => {
);
});
it('schedules a memory pressure check after tool execution', async () => {
const execute = vi.fn().mockResolvedValue({
llmContent: 'ok',
returnDisplay: 'ok',
});
const toolsByName = new Map<string, MockTool>([
[
'mockTool',
new MockTool({
name: 'mockTool',
execute,
}),
],
]);
const scheduleCheck = vi.fn();
const { scheduler } = createSchedulerForLegacyToolTests({
toolsByName,
memoryMonitor: { scheduleCheck },
});
await scheduler.schedule(
[
{
callId: 'memory-check',
name: 'mockTool',
args: {},
isClientInitiated: false,
prompt_id: 'prompt-memory-check',
},
],
new AbortController().signal,
);
expect(execute).toHaveBeenCalledOnce();
expect(scheduleCheck).toHaveBeenCalledTimes(1);
});
it('applies canonical legacy tool names to the deny-list fallback', async () => {
const execute = vi.fn().mockResolvedValue({
llmContent: 'edited',

View File

@ -51,6 +51,7 @@ import { fileURLToPath } from 'node:url';
import { ToolNames, ToolNamesMigration } from '../tools/tool-names.js';
import { escapeSystemReminderTags, escapeXml } from '../utils/xml.js';
import { unescapePath, PATH_ARG_KEYS } from '../utils/paths.js';
import type { MemoryPressureMonitor } from '../services/memoryPressureMonitor.js';
import { CONCURRENCY_SAFE_KINDS } from '../tools/tools.js';
import { isShellCommandReadOnly } from '../utils/shellReadOnlyChecker.js';
import { stripShellWrapper } from '../utils/shell-utils.js';
@ -840,6 +841,10 @@ export class CoreToolScheduler {
this.chatRecordingService = options.chatRecordingService;
}
private get memoryMonitor(): MemoryPressureMonitor | undefined {
return this.config.getMemoryPressureMonitor?.();
}
private setStatusInternal(
targetCallId: string,
status: 'success',
@ -2599,6 +2604,7 @@ export class CoreToolScheduler {
// _executeToolCallBody pre-sets status (OK / FAILURE / CANCELLED) via
// setToolSpan*; finalize without metadata to preserve that.
this.finalizeToolSpan(callId);
this.memoryMonitor?.scheduleCheck();
}
}

View File

@ -1633,6 +1633,11 @@ describe('GeminiChat', async () => {
});
it('seeds inherited token count via setLastPromptTokenCount', async () => {
vi.mocked(mockConfig.getContentGeneratorConfig).mockReturnValue({
authType: AuthType.USE_GEMINI,
model: 'test-model',
contextWindowSize: 200_000,
});
const subagentChat = new GeminiChat(mockConfig, config, [
{ role: 'user', parts: [{ text: 'inherited' }] },
{ role: 'model', parts: [{ text: 'inherited reply' }] },
@ -2383,6 +2388,17 @@ describe('GeminiChat', async () => {
{ role: 'user', parts: [{ text: 'summary' }] },
{ role: 'model', parts: [{ text: 'ack' }] },
];
const recordChatCompression = vi.fn();
const chatWithRecording = new GeminiChat(
mockConfig,
config,
[],
{
recordAssistantTurn: vi.fn(),
recordChatCompression,
} as unknown as ConstructorParameters<typeof GeminiChat>[3],
uiTelemetryService,
);
const compressSpy = vi
.spyOn(ChatCompressionService.prototype, 'compress')
.mockResolvedValueOnce({
@ -2400,10 +2416,10 @@ describe('GeminiChat', async () => {
// Seed lastPromptTokenCount JUST under the 177K hard threshold; the
// pending user message adds a handful of estimate-tokens that pushes
// effective >= 177K, so the rescue must trigger.
chat.setLastPromptTokenCount(176_999);
chatWithRecording.setLastPromptTokenCount(176_999);
const userMessage = 'this is the next user message';
const stream = await chat.sendMessageStream(
const stream = await chatWithRecording.sendMessageStream(
'test-model',
{ message: userMessage },
'prompt-id-hard-rescue-forces',
@ -2427,6 +2443,164 @@ describe('GeminiChat', async () => {
(part) => part.text === userMessage,
),
).toBe(true);
expect(recordChatCompression).toHaveBeenCalledTimes(1);
const recordPayload = recordChatCompression.mock.calls[0][0];
expect(recordPayload.info).toEqual(
expect.objectContaining({
compressionStatus: CompressionStatus.COMPRESSED,
newTokenCount: 40_000,
}),
);
expect(recordPayload.compressedHistory).toEqual([
{ role: 'user', parts: [{ text: 'summary' }] },
{ role: 'model', parts: [{ text: 'ack' }] },
]);
});
it('rejects before request serialization when oversized resumed history cannot be compressed', async () => {
const oversizedResumedHistory: Content[] = [
{ role: 'user', parts: [{ text: 'x'.repeat(720_000) }] },
{ role: 'model', parts: [{ text: 'ack' }] },
];
chat.setHistory(oversizedResumedHistory);
expect(chat.getLastPromptTokenCount()).toBe(0);
const compressSpy = vi
.spyOn(ChatCompressionService.prototype, 'compress')
.mockResolvedValueOnce({
newHistory: null,
info: {
originalTokenCount: 180_000,
newTokenCount: 180_000,
compressionStatus:
CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY,
},
});
vi.mocked(mockContentGenerator.generateContentStream).mockRejectedValue(
new Error('Invalid string length'),
);
await expect(
chat.sendMessageStream(
'test-model',
{ message: 'continue' },
'prompt-id-oversized-resume-guard',
),
).rejects.toThrow(
/compression status: COMPRESSION_FAILED_EMPTY_SUMMARY/i,
);
expect(compressSpy).toHaveBeenCalledTimes(1);
expect(compressSpy.mock.calls[0][1].force).toBe(true);
expect(mockContentGenerator.generateContentStream).not.toHaveBeenCalled();
expect(chat.getLastPromptTokenCount()).toBe(0);
expect(chat.getHistory()).toHaveLength(2);
});
it('rejects before request serialization and restores history when hard-rescue compression is still oversized', async () => {
const originalHistory: Content[] = [
{ role: 'user', parts: [{ text: 'x'.repeat(720_000) }] },
{ role: 'model', parts: [{ text: 'ack' }] },
];
const recordChatCompression = vi.fn();
const chatWithRecording = new GeminiChat(
mockConfig,
config,
[],
{
recordAssistantTurn: vi.fn(),
recordChatCompression,
} as unknown as ConstructorParameters<typeof GeminiChat>[3],
uiTelemetryService,
);
chatWithRecording.setHistory(originalHistory);
chatWithRecording.setLastPromptTokenCount(176_999);
vi.spyOn(
ChatCompressionService.prototype,
'compress',
).mockResolvedValueOnce({
newHistory: [
{ role: 'user', parts: [{ text: 'still large summary' }] },
{ role: 'model', parts: [{ text: 'ack' }] },
],
info: {
originalTokenCount: 180_000,
newTokenCount: 177_000,
compressionStatus: CompressionStatus.COMPRESSED,
},
});
vi.mocked(mockContentGenerator.generateContentStream).mockRejectedValue(
new Error('Invalid string length'),
);
await expect(
chatWithRecording.sendMessageStream(
'test-model',
{ message: 'continue' },
'prompt-id-oversized-after-compression',
),
).rejects.toThrow(/compression status: COMPRESSED/i);
expect(mockContentGenerator.generateContentStream).not.toHaveBeenCalled();
expect(recordChatCompression).not.toHaveBeenCalled();
expect(chatWithRecording.getLastPromptTokenCount()).toBe(176_999);
expect(chatWithRecording.getHistory()[0].parts?.[0].text).toBe(
originalHistory[0].parts?.[0].text,
);
});
it('rejects when compressed history is below hard but the pending user message pushes it over', async () => {
const originalHistory: Content[] = [
{ role: 'user', parts: [{ text: 'x'.repeat(720_000) }] },
{ role: 'model', parts: [{ text: 'ack' }] },
];
const recordChatCompression = vi.fn();
const chatWithRecording = new GeminiChat(
mockConfig,
config,
[],
{
recordAssistantTurn: vi.fn(),
recordChatCompression,
} as unknown as ConstructorParameters<typeof GeminiChat>[3],
uiTelemetryService,
);
chatWithRecording.setHistory(originalHistory);
chatWithRecording.setLastPromptTokenCount(175_500);
vi.spyOn(
ChatCompressionService.prototype,
'compress',
).mockResolvedValueOnce({
newHistory: [
{ role: 'user', parts: [{ text: 'summary' }] },
{ role: 'model', parts: [{ text: 'ack' }] },
],
info: {
originalTokenCount: 180_000,
newTokenCount: 176_000,
compressionStatus: CompressionStatus.COMPRESSED,
},
});
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
makeStreamResponse('should not send'),
);
await expect(
chatWithRecording.sendMessageStream(
'test-model',
{ message: 'x'.repeat(8_000) },
'prompt-id-oversized-after-compression-and-user',
),
).rejects.toThrow(/Estimated prompt tokens: 178000; hard limit: 177000/i);
expect(mockContentGenerator.generateContentStream).not.toHaveBeenCalled();
expect(recordChatCompression).not.toHaveBeenCalled();
expect(chatWithRecording.getLastPromptTokenCount()).toBe(175_500);
expect(chatWithRecording.getHistory()[0].parts?.[0].text).toBe(
originalHistory[0].parts?.[0].text,
);
});
it('forwards latched consecutiveFailures into hard-rescue (no pre-call reset); success recovers via the post-call branch', async () => {

View File

@ -106,6 +106,38 @@ function isCompressionFailureStatus(status: CompressionStatus): boolean {
);
}
function shouldStopAfterHardRescue(
shouldForceFromHard: boolean,
hardLimit: number,
localPromptTokensAfterCompression: number,
): boolean {
return shouldForceFromHard && localPromptTokensAfterCompression >= hardLimit;
}
function getHardRescueFailureMessage(
effectiveTokens: number,
hardLimit: number,
compressionInfo: ChatCompressionInfo,
localPromptTokensAfterCompression: number,
): string {
const compressionStatus =
CompressionStatus[compressionInfo.compressionStatus] ??
String(compressionInfo.compressionStatus);
const tokenCount =
compressionInfo.compressionStatus === CompressionStatus.COMPRESSED
? Math.max(
compressionInfo.newTokenCount,
localPromptTokensAfterCompression,
)
: Math.max(effectiveTokens, localPromptTokensAfterCompression);
return (
`Context is too large to send safely after automatic compression. ` +
`Estimated prompt tokens: ${tokenCount}; hard limit: ${hardLimit}; ` +
`compression status: ${compressionStatus}. ` +
`Start a new session or reduce the resumed history before continuing.`
);
}
export enum StreamEventType {
/** A regular content chunk from the API. */
CHUNK = 'chunk',
@ -157,6 +189,11 @@ interface TryCompressOptions {
* `getHistory(true)` clone per send. (review #4168 R1.3 / R1.4)
*/
precomputedEffectiveTokens?: number;
/**
* Delay writing the compression checkpoint until the caller has run any
* post-compression guards that may roll the in-memory chat state back.
*/
deferChatCompressionRecord?: boolean;
}
const INVALID_CONTENT_RETRY_OPTIONS: ContentRetryOptions = {
@ -1325,9 +1362,11 @@ export class GeminiChat {
*
* Returns the compression info regardless of outcome. On a successful
* compaction (`COMPRESSED`), this method has already mutated the chat's
* history, recorded the event to `chatRecordingService` (if wired), and
* updated both the per-chat token count and (when wired) the global
* telemetry singleton.
* history, recorded the event to `chatRecordingService` (if wired and
* unless `options.deferChatCompressionRecord` is set), and updated both
* the per-chat token count and (when wired) the global telemetry singleton.
* Deferred callers are responsible for recording after their own
* post-compression guards pass.
*/
async tryCompress(
promptId: string,
@ -1352,10 +1391,12 @@ export class GeminiChat {
});
if (info.compressionStatus === CompressionStatus.COMPRESSED && newHistory) {
this.chatRecordingService?.recordChatCompression({
info,
compressedHistory: newHistory,
});
if (!options?.deferChatCompressionRecord) {
this.chatRecordingService?.recordChatCompression({
info,
compressedHistory: newHistory,
});
}
this.setHistory(newHistory);
debugLogger.debug('[FILE_READ_CACHE] clear after auto tryCompress');
this.config.getFileReadCache().clear();
@ -1525,9 +1566,13 @@ export class GeminiChat {
imageTokenEstimate,
);
const shouldForceFromHard = effectiveTokens >= hard;
const historyBeforeHardRescue = shouldForceFromHard
? this.getHistoryShallow()
: undefined;
const lastPromptTokenCountBeforeHardRescue = this.lastPromptTokenCount;
if (shouldForceFromHard) {
debugLogger.warn(
`[compaction] hard-tier rescue triggered: effectiveTokens=${effectiveTokens}, hard=${hard}, consecutiveFailures=${this.consecutiveFailures}.`,
`[compaction] hard-tier rescue triggered: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, consecutiveFailures=${this.consecutiveFailures}.`,
);
}
@ -1539,6 +1584,7 @@ export class GeminiChat {
{
pendingUserMessage: userContent,
precomputedEffectiveTokens: effectiveTokens,
deferChatCompressionRecord: shouldForceFromHard,
// Hard-rescue is force=true to bypass the cheap-gate breaker
// but it remains a semantically AUTOMATIC trigger. Tag the
// compactTrigger explicitly as 'auto' so the PostCompact
@ -1553,6 +1599,66 @@ export class GeminiChat {
},
);
const localPromptTokensAfterCompression = shouldForceFromHard
? estimatePromptTokens(
this.lastPromptTokenCount > 0 ? [] : this.getHistoryShallow(true),
userContent,
this.lastPromptTokenCount,
imageTokenEstimate,
)
: 0;
if (
shouldStopAfterHardRescue(
shouldForceFromHard,
hard,
localPromptTokensAfterCompression,
)
) {
const message = getHardRescueFailureMessage(
effectiveTokens,
hard,
compressionInfo,
localPromptTokensAfterCompression,
);
if (
compressionInfo.compressionStatus === CompressionStatus.COMPRESSED &&
historyBeforeHardRescue
) {
// Hard-rescue compression mutates in-memory history before this
// guard can compare the compressed prompt size. If the compressed
// prompt is still too large to send, restore the pre-compression
// state. The JSONL compression checkpoint is intentionally not
// written because the send is about to be rejected.
this.setHistory(historyBeforeHardRescue);
this.lastPromptTokenCount = lastPromptTokenCountBeforeHardRescue;
this.telemetryService?.setLastPromptTokenCount(
lastPromptTokenCountBeforeHardRescue,
);
}
const compressionStatus =
CompressionStatus[compressionInfo.compressionStatus] ??
String(compressionInfo.compressionStatus);
debugLogger.warn(
`[compaction] hard-tier rescue stopped oversized prompt: ` +
`prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, ` +
`hard=${hard}, localPromptTokensAfterCompression=` +
`${localPromptTokensAfterCompression}, compressionStatus=` +
`${compressionStatus}, newTokenCount=` +
`${compressionInfo.newTokenCount}, consecutiveFailures=` +
`${this.consecutiveFailures}. ${message}`,
);
throw new Error(message);
}
if (
shouldForceFromHard &&
compressionInfo.compressionStatus === CompressionStatus.COMPRESSED
) {
this.chatRecordingService?.recordChatCompression({
info: compressionInfo,
compressedHistory: this.getHistoryShallow(),
});
}
// Add user content to history ONCE before any attempts.
this.history.push(userContent);
userContentAdded = true;

View File

@ -1474,6 +1474,504 @@ describe('OpenAIContentConverter', () => {
});
});
it('should drop tool responses that are not adjacent to their assistant tool call', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{
functionCall: {
id: 'call_a',
name: 'read_file',
args: { path: 'a.txt' },
},
},
{
functionCall: {
id: 'call_b',
name: 'grep',
args: { pattern: 'needle' },
},
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_a',
name: 'read_file',
response: { output: 'A' },
},
},
],
},
{
role: 'user',
parts: [{ text: 'history text inserted between tool results' }],
},
{
role: 'model',
parts: [
{
functionCall: {
id: 'call_c',
name: 'list_files',
args: {},
},
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_c',
name: 'list_files',
response: { output: 'C' },
},
},
{
functionResponse: {
id: 'call_b',
name: 'grep',
response: { output: 'B' },
},
},
],
},
],
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
requestContext,
);
const assistantWithCallA = messages.find(
(message): message is OpenAI.Chat.ChatCompletionAssistantMessageParam =>
message.role === 'assistant' &&
'tool_calls' in message &&
Array.isArray(message.tool_calls) &&
message.tool_calls.some((toolCall) => toolCall.id === 'call_a'),
);
expect(
assistantWithCallA?.tool_calls?.map((toolCall) => toolCall.id),
).toEqual(['call_a']);
const toolCallIds = messages
.filter(
(message): message is OpenAI.Chat.ChatCompletionToolMessageParam =>
message.role === 'tool' && 'tool_call_id' in message,
)
.map((message) => message.tool_call_id);
expect(toolCallIds).toEqual(['call_a', 'call_c']);
});
it('should keep assistant text when all tool calls are orphaned', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{ text: 'I can answer without the tool.' },
{
functionCall: {
id: 'call_missing',
name: 'read_file',
args: { path: 'missing.txt' },
},
},
],
},
{
role: 'user',
parts: [{ text: 'continue' }],
},
],
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
requestContext,
);
const assistant = messages.find(
(message): message is OpenAI.Chat.ChatCompletionAssistantMessageParam =>
message.role === 'assistant',
);
expect(assistant?.content).toBe('I can answer without the tool.');
expect('tool_calls' in (assistant ?? {})).toBe(false);
expect(messages.some((message) => message.role === 'tool')).toBe(false);
});
it('should drop assistant-only tool calls when all responses are orphaned', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{
functionCall: {
id: 'call_missing',
name: 'read_file',
args: { path: 'missing.txt' },
},
},
],
},
{
role: 'user',
parts: [{ text: 'break adjacency' }],
},
{
role: 'user',
parts: [{ text: 'continue' }],
},
],
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
requestContext,
);
expect(messages.some((message) => message.role === 'assistant')).toBe(
false,
);
expect(messages.some((message) => message.role === 'tool')).toBe(false);
});
it('should keep a tool response after an empty-id tool message', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{
functionCall: {
id: 'call_a',
name: 'read_file',
args: { path: 'a.txt' },
},
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
name: 'empty_id',
response: { output: 'no id' },
},
},
{
functionResponse: {
id: 'call_a',
name: 'read_file',
response: { output: 'A' },
},
},
],
},
],
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
requestContext,
);
const toolCallIds = messages
.filter(
(message): message is OpenAI.Chat.ChatCompletionToolMessageParam =>
message.role === 'tool' && 'tool_call_id' in message,
)
.map((message) => message.tool_call_id);
expect(toolCallIds).toEqual(['call_a']);
});
it('should clean after merging consecutive assistant turns', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{
functionCall: {
id: 'call_a',
name: 'read_file',
args: { path: 'a.txt' },
},
},
],
},
{
role: 'model',
parts: [{ text: 'A short follow-up.' }],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_a',
name: 'read_file',
response: { output: 'A' },
},
},
],
},
],
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
requestContext,
);
expect(messages[0]).toMatchObject({
role: 'assistant',
content: 'A short follow-up.',
});
expect(
(
messages[0] as OpenAI.Chat.ChatCompletionAssistantMessageParam
).tool_calls?.map((toolCall) => toolCall.id),
).toEqual(['call_a']);
expect(messages[1]).toMatchObject({
role: 'tool',
tool_call_id: 'call_a',
});
});
it('should keep split media after all adjacent tool responses across content items', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{
functionCall: { id: 'call_a', name: 'shot_a', args: {} },
},
{
functionCall: { id: 'call_b', name: 'shot_b', args: {} },
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_a',
name: 'shot_a',
response: { output: 'A' },
parts: [
{ inlineData: { mimeType: 'image/png', data: 'aaa' } },
],
},
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_b',
name: 'shot_b',
response: { output: 'B' },
parts: [
{ inlineData: { mimeType: 'image/png', data: 'bbb' } },
],
},
},
],
},
],
};
const strictContext: RequestContext = {
...requestContext,
splitToolMedia: true,
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
strictContext,
);
const assistantIndex = messages.findIndex(
(message) => message.role === 'assistant',
);
expect(messages[assistantIndex + 1]).toMatchObject({
role: 'tool',
tool_call_id: 'call_a',
});
expect(messages[assistantIndex + 2]).toMatchObject({
role: 'tool',
tool_call_id: 'call_b',
});
expect(messages[assistantIndex + 3]?.role).toBe('user');
expect(messages[assistantIndex + 4]?.role).toBe('user');
});
it('should not keep split media from orphaned tool responses', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{
functionCall: { id: 'call_a', name: 'shot_a', args: {} },
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_x',
name: 'shot_x',
response: { output: 'X' },
parts: [
{ inlineData: { mimeType: 'image/png', data: 'xxx' } },
],
},
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_a',
name: 'shot_a',
response: { output: 'A' },
},
},
],
},
],
};
const strictContext: RequestContext = {
...requestContext,
splitToolMedia: true,
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
strictContext,
);
expect(messages.map((message) => message.role)).toEqual([
'assistant',
'tool',
]);
expect(messages[1]).toMatchObject({
role: 'tool',
tool_call_id: 'call_a',
});
});
it('should merge assistant turns created by orphan cleanup', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{
functionCall: { id: 'call_a', name: 'read_file', args: {} },
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_a',
name: 'read_file',
response: { output: 'A' },
},
},
],
},
{
role: 'model',
parts: [{ text: 'Next I will call another tool.' }],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_orphan',
name: 'stale_tool',
response: { output: 'stale' },
},
},
],
},
{
role: 'model',
parts: [
{
functionCall: { id: 'call_b', name: 'grep', args: {} },
},
],
},
{
role: 'user',
parts: [
{
functionResponse: {
id: 'call_b',
name: 'grep',
response: { output: 'B' },
},
},
],
},
],
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
requestContext,
);
for (let index = 1; index < messages.length; index += 1) {
expect([messages[index - 1].role, messages[index].role]).not.toEqual([
'assistant',
'assistant',
]);
}
expect(
messages
.filter(
(message): message is OpenAI.Chat.ChatCompletionToolMessageParam =>
message.role === 'tool' && 'tool_call_id' in message,
)
.map((message) => message.tool_call_id),
).toEqual(['call_a', 'call_b']);
});
describe('assistant message with reasoning-only content (issue #3421)', () => {
/**
* Regression tests for https://github.com/QwenLM/qwen-code/issues/3421
@ -1514,6 +2012,41 @@ describe('OpenAIContentConverter', () => {
).toBe('I reasoned about it.');
});
it('should keep reasoning content when orphaned tool calls are removed', () => {
const request: GenerateContentParameters = {
model: 'models/test',
contents: [
{
role: 'model',
parts: [
{ text: 'I need to inspect this.', thought: true },
{
functionCall: {
id: 'call_missing',
name: 'read_file',
args: {},
},
},
],
},
{ role: 'user', parts: [{ text: 'break adjacency' }] },
],
};
const messages = converter.convertGeminiRequestToOpenAI(
request,
requestContext,
);
const assistantMsg = messages.find((m) => m.role === 'assistant');
expect(assistantMsg).toBeDefined();
expect((assistantMsg as { content: unknown }).content).toBe('');
expect(
(assistantMsg as { reasoning_content?: string }).reasoning_content,
).toBe('I need to inspect this.');
expect('tool_calls' in (assistantMsg ?? {})).toBe(false);
});
it('should keep content null when assistant has only tool_calls and no reasoning', () => {
const request: GenerateContentParameters = {
model: 'models/test',

View File

@ -29,6 +29,7 @@ import {
} from '../../utils/schemaConverter.js';
const debugLogger = createDebugLogger('CONVERTER');
const SPLIT_TOOL_MEDIA_TEXT = '(attached media from previous tool call)';
/**
* Extended usage type that supports both OpenAI standard format and alternative formats
@ -380,11 +381,11 @@ export function convertGeminiRequestToOpenAI(
// Handle contents
processContents(request.contents, messages, requestContext);
// Clean up orphaned tool calls and merge consecutive assistant messages
messages = mergeConsecutiveAssistantMessages(messages);
if (options.cleanOrphanToolCalls) {
messages = cleanOrphanedToolCalls(messages);
messages = mergeConsecutiveAssistantMessages(messages);
}
messages = mergeConsecutiveAssistantMessages(messages);
return messages;
}
@ -645,7 +646,7 @@ function processContent(
content: [
{
type: 'text',
text: '(attached media from previous tool call)',
text: SPLIT_TOOL_MEDIA_TEXT,
},
...accumulatedSplitMedia,
] as unknown as OpenAI.Chat.ChatCompletionContentPartText[],
@ -1387,51 +1388,126 @@ function mapGeminiFinishReasonToOpenAI(
}
}
/** Type guard: is this an assistant message with at least one tool call? */
function hasToolCalls(
message: OpenAI.Chat.ChatCompletionMessageParam,
): message is OpenAI.Chat.ChatCompletionAssistantMessageParam & {
tool_calls: OpenAI.Chat.ChatCompletionMessageToolCall[];
} {
return (
message.role === 'assistant' &&
'tool_calls' in message &&
Array.isArray(message.tool_calls) &&
message.tool_calls.length > 0
);
}
function isSplitToolMediaMessage(
message: OpenAI.Chat.ChatCompletionMessageParam,
): boolean {
if (
message.role !== 'user' ||
!('content' in message) ||
!Array.isArray(message.content)
) {
return false;
}
const firstPart = message.content[0] as
| { type?: string; text?: string }
| undefined;
return firstPart?.type === 'text' && firstPart.text === SPLIT_TOOL_MEDIA_TEXT;
}
/**
* Clean up orphaned tool calls from message history to prevent OpenAI API errors.
*
* Assumes consecutive assistant messages have already been merged.
*/
function cleanOrphanedToolCalls(
messages: OpenAI.Chat.ChatCompletionMessageParam[],
): OpenAI.Chat.ChatCompletionMessageParam[] {
const cleaned: OpenAI.Chat.ChatCompletionMessageParam[] = [];
const toolCallIds = new Set<string>();
const toolResponseIds = new Set<string>();
const adjacentToolResponseIdsByAssistant = new Map<number, Set<string>>();
const validToolResponseIndexesByAssistant = new Map<number, number[]>();
const splitMediaIndexesByAssistant = new Map<number, number[]>();
const emittedWithAssistant = new Set<number>();
// First pass: collect all tool call IDs and tool response IDs
for (const message of messages) {
if (
message.role === 'assistant' &&
'tool_calls' in message &&
message.tool_calls
) {
for (const toolCall of message.tool_calls) {
if (toolCall.id) {
toolCallIds.add(toolCall.id);
for (let index = 0; index < messages.length; index += 1) {
const message = messages[index];
if (hasToolCalls(message)) {
const toolCallIds = new Set(
message.tool_calls
.map((toolCall) => toolCall.id)
.filter((id): id is string => Boolean(id)),
);
const adjacentToolResponseIds = new Set<string>();
const toolResponseIndexes: number[] = [];
const splitMediaIndexes: number[] = [];
let lastToolResponseMatchesAssistant = false;
for (
let nextIndex = index + 1;
nextIndex < messages.length;
nextIndex += 1
) {
const nextMessage = messages[nextIndex];
if (nextMessage.role === 'tool' && 'tool_call_id' in nextMessage) {
if (!nextMessage.tool_call_id) {
lastToolResponseMatchesAssistant = false;
continue;
}
if (toolCallIds.has(nextMessage.tool_call_id)) {
adjacentToolResponseIds.add(nextMessage.tool_call_id);
toolResponseIndexes.push(nextIndex);
lastToolResponseMatchesAssistant = true;
} else {
lastToolResponseMatchesAssistant = false;
}
// Other tool responses in this block may belong to another assistant.
continue;
}
if (isSplitToolMediaMessage(nextMessage)) {
if (lastToolResponseMatchesAssistant) {
splitMediaIndexes.push(nextIndex);
}
continue;
}
if (nextMessage.role === 'assistant' && !hasToolCalls(nextMessage)) {
// Consecutive assistant turns are merged before cleanup.
continue;
}
break;
}
} else if (
message.role === 'tool' &&
'tool_call_id' in message &&
message.tool_call_id
) {
toolResponseIds.add(message.tool_call_id);
adjacentToolResponseIdsByAssistant.set(index, adjacentToolResponseIds);
validToolResponseIndexesByAssistant.set(index, toolResponseIndexes);
splitMediaIndexesByAssistant.set(index, splitMediaIndexes);
}
}
// Second pass: filter out orphaned messages
for (const message of messages) {
if (
message.role === 'assistant' &&
'tool_calls' in message &&
message.tool_calls
) {
// Filter out tool calls that don't have corresponding responses
for (let index = 0; index < messages.length; index += 1) {
if (emittedWithAssistant.has(index)) {
continue;
}
const message = messages[index];
if (hasToolCalls(message)) {
const reasoningContent = (
message as ExtendedChatCompletionAssistantMessageParam
).reasoning_content;
const adjacentToolResponseIds =
adjacentToolResponseIdsByAssistant.get(index) ?? new Set<string>();
const validToolCalls = message.tool_calls.filter(
(toolCall) => toolCall.id && toolResponseIds.has(toolCall.id),
(toolCall) => toolCall.id && adjacentToolResponseIds.has(toolCall.id),
);
if (validToolCalls.length > 0) {
// Keep the message but only with valid tool calls
const cleanedMessage = { ...message };
(
cleanedMessage as OpenAI.Chat.ChatCompletionMessageParam & {
@ -1439,11 +1515,30 @@ function cleanOrphanedToolCalls(
}
).tool_calls = validToolCalls;
cleaned.push(cleanedMessage);
for (const toolResponseIndex of validToolResponseIndexesByAssistant.get(
index,
) ?? []) {
const toolResponse = messages[toolResponseIndex];
if (toolResponse) {
cleaned.push(toolResponse);
emittedWithAssistant.add(toolResponseIndex);
}
}
for (const splitMediaIndex of splitMediaIndexesByAssistant.get(index) ??
[]) {
const splitMediaMessage = messages[splitMediaIndex];
if (splitMediaMessage) {
cleaned.push(splitMediaMessage);
emittedWithAssistant.add(splitMediaIndex);
}
}
} else if (
typeof message.content === 'string' &&
message.content.trim()
(typeof message.content === 'string' && message.content.trim()) ||
reasoningContent
) {
// Keep the message if it has text content, but remove tool calls
// Keep text/reasoning content, but remove orphaned tool calls.
const cleanedMessage = { ...message };
delete (
cleanedMessage as OpenAI.Chat.ChatCompletionMessageParam & {
@ -1451,91 +1546,25 @@ function cleanOrphanedToolCalls(
}
).tool_calls;
cleaned.push(cleanedMessage);
} else {
debugLogger.debug(
`cleanOrphanedToolCalls: dropping assistant with ${message.tool_calls.length} orphaned tool call(s) and no text/reasoning content`,
);
}
// If no valid tool calls and no content, skip the message entirely
} else if (
message.role === 'tool' &&
'tool_call_id' in message &&
message.tool_call_id
) {
// Only keep tool responses that have corresponding tool calls
if (toolCallIds.has(message.tool_call_id)) {
cleaned.push(message);
}
} else if (message.role === 'tool' && 'tool_call_id' in message) {
debugLogger.debug(
`cleanOrphanedToolCalls: dropping orphaned tool response ${message.tool_call_id || '<empty>'}`,
);
} else if (isSplitToolMediaMessage(message)) {
debugLogger.debug(
'cleanOrphanedToolCalls: dropping orphaned split tool media message',
);
} else {
// Keep all other messages as-is
cleaned.push(message);
}
}
// Final validation: ensure every assistant message with tool_calls has corresponding tool responses
const finalCleaned: OpenAI.Chat.ChatCompletionMessageParam[] = [];
const finalToolCallIds = new Set<string>();
// Collect all remaining tool call IDs
for (const message of cleaned) {
if (
message.role === 'assistant' &&
'tool_calls' in message &&
message.tool_calls
) {
for (const toolCall of message.tool_calls) {
if (toolCall.id) {
finalToolCallIds.add(toolCall.id);
}
}
}
}
// Verify all tool calls have responses
const finalToolResponseIds = new Set<string>();
for (const message of cleaned) {
if (
message.role === 'tool' &&
'tool_call_id' in message &&
message.tool_call_id
) {
finalToolResponseIds.add(message.tool_call_id);
}
}
// Remove any remaining orphaned tool calls
for (const message of cleaned) {
if (
message.role === 'assistant' &&
'tool_calls' in message &&
message.tool_calls
) {
const finalValidToolCalls = message.tool_calls.filter(
(toolCall) => toolCall.id && finalToolResponseIds.has(toolCall.id),
);
if (finalValidToolCalls.length > 0) {
const cleanedMessage = { ...message };
(
cleanedMessage as OpenAI.Chat.ChatCompletionMessageParam & {
tool_calls?: OpenAI.Chat.ChatCompletionMessageToolCall[];
}
).tool_calls = finalValidToolCalls;
finalCleaned.push(cleanedMessage);
} else if (
typeof message.content === 'string' &&
message.content.trim()
) {
const cleanedMessage = { ...message };
delete (
cleanedMessage as OpenAI.Chat.ChatCompletionMessageParam & {
tool_calls?: OpenAI.Chat.ChatCompletionMessageToolCall[];
}
).tool_calls;
finalCleaned.push(cleanedMessage);
}
} else {
finalCleaned.push(message);
}
}
return finalCleaned;
return cleaned;
}
/**

View File

@ -15,7 +15,7 @@ import { OpenAIContentConverter } from './converter.js';
import { openaiRequestCaptureContext } from './requestCaptureContext.js';
import { StreamingToolCallParser } from './streamingToolCallParser.js';
import type { Config } from '../../config/config.js';
import type { ContentGeneratorConfig, AuthType } from '../contentGenerator.js';
import { AuthType, type ContentGeneratorConfig } from '../contentGenerator.js';
import type { OpenAICompatibleProvider } from './provider/index.js';
// Mock dependencies
@ -463,15 +463,31 @@ describe('ContentGenerationPipeline', () => {
});
it('should override enable_thinking when thinkingConfig disables it', async () => {
// Arrange — provider injects enable_thinking: true via extra_body,
// but request explicitly disables thinking
// Arrange — provider injects enable_thinking: true via extra_body
// (e.g. user configured `enableThinking: true` via setup wizard,
// see provider-config.ts), but request explicitly disables thinking.
// DashScope hostname + qwen model name are both required: the gate
// is hostname + model-name to avoid leaking the qwen-specific
// `enable_thinking` field to non-qwen routings (off-DashScope, or
// GLM/DeepSeek on the same DashScope hostname).
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
model: 'qwen3.5-flash',
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
(mockProvider.buildRequest as Mock).mockImplementation((req) => ({
...req,
enable_thinking: true, // Simulates extra_body injection
}));
const request: GenerateContentParameters = {
model: 'test-model',
model: 'qwen3.5-flash',
contents: [{ parts: [{ text: 'Suggest next' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
@ -747,6 +763,375 @@ describe('ContentGenerationPipeline', () => {
expect(apiCall.thinking).toBeUndefined();
});
it('emits enable_thinking:false on DashScope hostname when includeThoughts is false', async () => {
// Regression for #4501: qwen3 hybrid models (e.g. qwen3.5-flash)
// default to thinking-on. Provider buildRequest never auto-injects
// `enable_thinking`, so a previous guarded `'enable_thinking' in typed`
// check never fired and side-queries burned reasoning tokens (24-95x
// output bloat in production). The disable must be emitted explicitly.
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
model: 'qwen3.5-flash',
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
// Provider passes the request through unchanged — simulates the
// common case where the user has not configured
// `extra_body.enable_thinking` (so the field never appears on the
// wire body unless we add it here).
const request: GenerateContentParameters = {
model: 'qwen3.5-flash',
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Summarize' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'forked_query');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBe(false);
});
it('emits enable_thinking:false on DashScope hostname when reasoning is configured to false', async () => {
// Config-level opt-out (`reasoning: false`) should also disable
// qwen3 thinking, mirroring the DeepSeek pair above.
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
model: 'qwen3.5-flash',
reasoning: false,
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
const request: GenerateContentParameters = {
model: 'qwen3.5-flash',
contents: [{ parts: [{ text: 'Hello' }], role: 'user' }],
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Hello' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'main');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBe(false);
});
it('emits enable_thinking:false on QWEN_OAUTH with the default coder-model', async () => {
// QWEN_OAUTH is the default auth flow for first-time users and
// ships with `model: 'coder-model'` (DEFAULT_QWEN_MODEL in
// config/models.ts — aliased to Qwen 3.6 Plus hybrid). The string
// doesn't start with `qwen`, so the gate must special-case it;
// otherwise the exact regression that #4501 fixes (side-queries
// burning reasoning tokens on the default flow) remains live.
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
authType: AuthType.QWEN_OAUTH,
baseUrl: 'https://some-oauth-issued-endpoint.example/v1',
model: 'coder-model',
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
const request: GenerateContentParameters = {
model: 'coder-model',
contents: [{ parts: [{ text: 'Hi' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Hi' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'forked_query');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBe(false);
});
it('emits enable_thinking:false on internal alibaba-inc.com hostname', async () => {
// Internal Alibaba domains proxy to DashScope-compatible APIs and
// are treated as DashScope by design (provider/dashscope.ts:75-78).
// Cover the internal-origin path explicitly so a future tightening
// of the hostname rules does not silently drop coverage for
// internal users.
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
baseUrl: 'https://gateway.alibaba-inc.com/v1',
model: 'qwen3.5-flash',
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
const request: GenerateContentParameters = {
model: 'qwen3.5-flash',
contents: [{ parts: [{ text: 'Hi' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Hi' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'forked_query');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBe(false);
});
it('does NOT emit enable_thinking on a non-DashScope hostname', async () => {
// `enable_thinking` is a qwen-specific extension. Pushing it at a
// strict OpenAI-compatible backend could trip an unknown-key 400
// and would also pollute logs with a meaningless field. Mirror of
// the DeepSeek negative test above.
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
baseUrl: 'https://api.openai.com/v1',
model: 'gpt-5',
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
const request: GenerateContentParameters = {
model: 'test-model',
contents: [{ parts: [{ text: 'Suggest' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Suggest' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'forked_query');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBeUndefined();
});
it('does NOT emit enable_thinking on a non-qwen model routed through DashScope', async () => {
// DashScope's compatible-mode endpoint routes multiple model families
// (qwen3, GLM, DeepSeek). Hostname alone is not enough — GLM uses
// `extra_body.thinking.enabled` and DeepSeek-on-DashScope uses
// `thinking: { type: 'disabled' }`, so sending `enable_thinking` is
// at best a no-op and at worst forwarded upstream and rejected.
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
model: 'glm-5',
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
const request: GenerateContentParameters = {
model: 'glm-5',
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Summarize' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'forked_query');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBeUndefined();
});
it('gates on the wire model, not config: qwen config + non-qwen request.model does NOT emit', async () => {
// buildRequest ships `context.model` (= request.model || config.model).
// A qwen *config* with a non-qwen *request* model must gate on the
// request model — otherwise the qwen-only field leaks to the non-qwen
// routing that is actually on the wire (e.g. GLM rejecting it upstream).
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
model: 'qwen3.5-flash',
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
const request: GenerateContentParameters = {
model: 'glm-5', // request-level override to a non-qwen wire model
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Summarize' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'forked_query');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBeUndefined();
});
it('gates on the wire model, not config: non-qwen config + qwen request.model emits false', async () => {
// The mirror direction: a non-qwen *config* with a qwen *request* model
// must still emit the disable signal, since the wire model is qwen and
// would otherwise keep thinking-on (the #4501 regression).
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
model: 'glm-5',
} as ContentGeneratorConfig;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
const request: GenerateContentParameters = {
model: 'qwen3.5-flash', // request-level override to a qwen wire model
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Summarize' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'forked_query');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBe(false);
});
it('emits enable_thinking:false when baseUrl is unset (DashScope default)', async () => {
// `isDashScopeProvider` treats a missing baseUrl as DashScope
// (`dashscope.ts:49` returns true for `!baseUrl`). A fresh install
// that hasn't run the setup wizard hits this path. All other
// positive tests above explicitly set baseUrl, so pin this
// implicit-default branch separately to detect future tightening
// of the `!baseUrl` early-return.
mockContentGeneratorConfig = {
...mockContentGeneratorConfig,
model: 'qwen3.5-flash',
} as ContentGeneratorConfig;
delete (mockContentGeneratorConfig as { baseUrl?: string }).baseUrl;
mockConfig = {
...mockConfig,
contentGeneratorConfig: mockContentGeneratorConfig,
};
pipeline = new ContentGenerationPipeline(mockConfig);
const request: GenerateContentParameters = {
model: 'qwen3.5-flash',
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
config: { thinkingConfig: { includeThoughts: false } },
};
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
{ role: 'user', content: 'Summarize' },
]);
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
new GenerateContentResponse(),
);
(mockClient.chat.completions.create as Mock).mockResolvedValue({
id: 'r',
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
} as OpenAI.Chat.ChatCompletion);
await pipeline.execute(request, 'forked_query');
const apiCall = (mockClient.chat.completions.create as Mock).mock
.calls[0][0];
expect(apiCall.enable_thinking).toBe(false);
});
it('should handle errors and log them', async () => {
// Arrange
const request: GenerateContentParameters = {

View File

@ -11,6 +11,7 @@ import {
} from '@google/genai';
import type { ContentGeneratorConfig } from '../contentGenerator.js';
import { OpenAIContentConverter } from './converter.js';
import { DashScopeOpenAICompatibleProvider } from './provider/dashscope.js';
import { isDeepSeekHostname } from './provider/deepseek.js';
import { openaiRequestCaptureContext } from './requestCaptureContext.js';
import { StreamingToolCallParser } from './streamingToolCallParser.js';
@ -341,7 +342,33 @@ export class ContentGenerationPipeline {
this.contentGeneratorConfig.reasoning === false;
if (reasoningDisabled) {
const typed = providerRequest as unknown as Record<string, unknown>;
if ('enable_thinking' in typed) {
// Provider buildRequest doesn't auto-inject `enable_thinking`, so a
// guarded `in typed` check would never fire for default qwen3 configs.
// Hostname + model-name gate avoids leaking this qwen-specific field
// to non-qwen routings on the same DashScope hostname (GLM uses
// `extra_body.thinking.enabled`, DeepSeek-on-DashScope uses
// `thinking: { type: 'disabled' }`; sending `enable_thinking` to them
// is at best a no-op, at worst forwarded upstream and rejected).
//
// Gate on the *wire* model (`context.model`, i.e.
// `request.model || contentGeneratorConfig.model` — the same value
// baseRequest.model is built from above), not on the config model. A
// request-level model override would otherwise desync the gate from
// what actually ships: a qwen config with a non-qwen request model
// would leak the field, and a non-qwen config with a qwen request
// model would miss the disable signal (the #4501 regression).
//
// `coder-model` is the QWEN_OAUTH default (DEFAULT_QWEN_MODEL in
// config/models.ts, aliased to Qwen 3.6 Plus hybrid) — it doesn't
// start with `qwen` but is the most common hybrid-thinking model
// for first-time users, so it must be covered.
const model = (context.model ?? '').toLowerCase();
if (
DashScopeOpenAICompatibleProvider.isDashScopeProvider(
this.contentGeneratorConfig,
) &&
(model.startsWith('qwen') || model === 'coder-model')
) {
typed['enable_thinking'] = false;
}
// Strip reasoning config — extra_body could inject it, overriding
@ -451,7 +478,8 @@ export class ContentGenerationPipeline {
// - glm-4.7 — thinking is enabled by default; can be disabled via `extra_body.thinking.enabled`
// - kimi-k2-thinking — thinking is enabled by default and cannot be disabled
// - gpt-5.x series — thinking is enabled by default; can be disabled via `reasoning.effort`
// - qwen3 series — model-dependent; can be manually disabled via `extra_body.enable_thinking`
// - qwen3 series — model-dependent; emitted as `enable_thinking: false`
// on DashScope endpoints when reasoning is disabled
//
// Given this inconsistency, we avoid mapping values and only pass through the
// configured reasoning object when explicitly enabled. This keeps provider- and

View File

@ -70,6 +70,11 @@ export function getHookMatcherTarget(
}
}
export function hookEventSupportsMatcher(eventName: HookEventName): boolean {
const target = getHookMatcherTarget(eventName);
return typeof target === 'object' && target !== null;
}
/**
* Hook planner that selects matching hooks and creates execution plans
*/

View File

@ -29,7 +29,6 @@ import { FunctionHookRunner } from './functionHookRunner.js';
import { PromptHookRunner } from './promptHookRunner.js';
import { AsyncHookRegistry, generateHookId } from './asyncHookRegistry.js';
import type { Config } from '../config/config.js';
import { getShellContextEnvVars } from '../utils/shellContextEnv.js';
const debugLogger = createDebugLogger('TRUSTED_HOOKS');
@ -574,7 +573,6 @@ export class HookRunner {
GEMINI_PROJECT_DIR: input.cwd,
CLAUDE_PROJECT_DIR: input.cwd, // For compatibility
QWEN_PROJECT_DIR: input.cwd, // For Qwen Code compatibility
...getShellContextEnvVars(),
...hookConfig.env,
};

View File

@ -12,7 +12,7 @@ export { HookSystem } from './hookSystem.js';
export { HookRegistry } from './hookRegistry.js';
export { HookRunner } from './hookRunner.js';
export { HookAggregator } from './hookAggregator.js';
export { HookPlanner } from './hookPlanner.js';
export { HookPlanner, hookEventSupportsMatcher } from './hookPlanner.js';
export { HookEventHandler } from './hookEventHandler.js';
// Export new hook runners

View File

@ -388,7 +388,11 @@ export * from './test-utils/index.js';
// ============================================================================
export * from './hooks/types.js';
export { HookSystem, HookRegistry } from './hooks/index.js';
export {
HookSystem,
HookRegistry,
hookEventSupportsMatcher,
} from './hooks/index.js';
export type { HookRegistryEntry, SessionHookEntry } from './hooks/index.js';
export {
DEFAULT_STOP_HOOK_BLOCK_CAP,

View File

@ -704,4 +704,121 @@ describe('FileReadCache', () => {
expect(cache.check(makeStats({ ino: 0 })).state).not.toBe('unknown');
});
});
describe('evictNotAccessedSince', () => {
afterEach(() => {
vi.useRealTimers();
});
it('evicts entries with lastReadAt before the cutoff', () => {
const cache = new FileReadCache();
const now = 2_000_000_000;
const old = now - 100 * 60_000; // 100 minutes ago
const recent = now - 5 * 60_000; // 5 minutes ago
const oldStats = makeStats({ ino: 1 });
const recentStats = makeStats({ ino: 2 });
vi.useFakeTimers();
vi.setSystemTime(old);
cache.recordRead('/x/old.ts', oldStats, { full: true, cacheable: true });
vi.setSystemTime(recent);
cache.recordRead('/x/recent.ts', recentStats, {
full: true,
cacheable: true,
});
// Now set time to "now" and evict entries older than 30 minutes
vi.setSystemTime(now);
const evicted = cache.evictNotAccessedSince(30);
expect(evicted).toBe(1);
expect(cache.check(oldStats).state).toBe('unknown');
expect(cache.check(recentStats).state).toBe('fresh');
});
it('evicts entries that were only written, never read', () => {
const cache = new FileReadCache();
vi.useFakeTimers();
const pastWrite = 1000; // some fixed timestamp in the past
vi.setSystemTime(pastWrite);
cache.recordWrite('/x/old-write.ts', makeStats({ ino: 2 }));
// Advance time by 120 minutes
vi.setSystemTime(pastWrite + 120 * 60_000);
const evicted = cache.evictNotAccessedSince(60);
expect(evicted).toBe(1);
expect(cache.size()).toBe(0);
});
it('preserves recently accessed entries', () => {
const cache = new FileReadCache();
vi.useFakeTimers();
const now = Date.now();
vi.setSystemTime(now);
cache.recordRead('/x/recent.ts', makeStats({ ino: 1 }), {
full: true,
cacheable: true,
});
const evicted = cache.evictNotAccessedSince(30);
expect(evicted).toBe(0);
expect(cache.size()).toBe(1);
});
it('returns correct eviction count', () => {
const cache = new FileReadCache();
vi.useFakeTimers();
const now = Date.now();
vi.setSystemTime(now);
// 3 recent entries
for (let i = 0; i < 3; i++) {
cache.recordRead(`/x/recent-${i}.ts`, makeStats({ ino: i }), {
full: true,
cacheable: true,
});
}
// Jump 120 minutes back, add 2 old entries
vi.setSystemTime(now - 120 * 60_000);
for (let i = 10; i < 12; i++) {
cache.recordRead(`/x/old-${i}.ts`, makeStats({ ino: i }), {
full: true,
cacheable: true,
});
}
// Back to now
vi.setSystemTime(now);
const evicted = cache.evictNotAccessedSince(60);
expect(evicted).toBe(2);
expect(cache.size()).toBe(3);
});
it('returns 0 for empty cache', () => {
const cache = new FileReadCache();
expect(cache.evictNotAccessedSince(30)).toBe(0);
});
it('does not evict entries for sub-minute windows', () => {
const cache = new FileReadCache();
cache.recordRead('/x/recent.ts', makeStats({ ino: 1 }), {
full: true,
cacheable: true,
});
expect(cache.evictNotAccessedSince(0)).toBe(0);
expect(cache.evictNotAccessedSince(-30)).toBe(0);
expect(cache.evictNotAccessedSince(0.0000001)).toBe(0);
expect(cache.size()).toBe(1);
});
});
});

View File

@ -317,6 +317,36 @@ export class FileReadCache {
this.byInode.clear();
}
/**
* Evict entries whose most recent Read (or Write; both set
* {@link FileReadEntry.lastReadAt}) is older than `minutes`.
*
* This is a memory-pressure-driven eviction: it targets entries the
* model is least likely to need again, trading cache hit rate for lower
* memory footprint. Unlike {@link clear}, it preserves recently-read
* entries so the file_unchanged fast-path stays available for active
* files.
*
* @returns Number of entries evicted.
*/
evictNotAccessedSince(minutes: number): number {
if (!Number.isFinite(minutes) || minutes < 1) {
return 0;
}
const cutoff = Date.now() - minutes * 60 * 1000;
let evicted = 0;
for (const [key, entry] of this.byInode) {
if (entry.lastReadAt !== undefined && entry.lastReadAt < cutoff) {
this.byInode.delete(key);
evicted++;
}
}
return evicted;
}
/** Number of tracked entries. Diagnostic / test use only. */
size(): number {
return this.byInode.size;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,605 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import * as os from 'node:os';
import { readFileSync } from 'node:fs';
import { EventEmitter } from 'node:events';
import { getHeapStatistics } from 'node:v8';
import { createDebugLogger } from '../utils/debugLogger.js';
import { getErrorMessage } from '../utils/errors.js';
import type { Config } from '../config/config.js';
// Types
export interface MemoryPressureConfig {
/** RSS / totalmem ratio at which light cleanup begins. Default 0.50. */
softPressureRatio: number;
/** RSS / totalmem ratio at which moderate cleanup begins. Default 0.65. */
hardPressureRatio: number;
/** RSS / totalmem ratio at which aggressive cleanup begins. Default 0.80. */
criticalRatio: number;
/** Minimum ms between consecutive cleanups. Default 5000. */
cleanupCooldownMs: number;
/** Allow global.gc() in aggressive cleanup. Requires --expose-gc. */
enableExplicitGC: boolean;
}
export interface CleanupRecommendation {
action: 'none' | 'light' | 'moderate' | 'aggressive';
steps: CleanupStep[];
}
export type CleanupStep =
| 'clear_file_cache'
| 'evict_cold_cache'
| 'evict_stale_cache'
| 'trigger_gc';
export interface MemoryCleanupFailureEvent {
rss: number;
consecutiveFailures: number;
recommendation: CleanupRecommendation;
error: string;
}
export interface MemoryCleanupIneffectiveEvent {
rss: number;
freedBytes: number;
freedRatio: number;
consecutiveIneffectiveCleanups: number;
recommendation: CleanupRecommendation;
}
export const DEFAULT_PRESSURE_CONFIG: MemoryPressureConfig = {
softPressureRatio: 0.5,
hardPressureRatio: 0.65,
criticalRatio: 0.8,
cleanupCooldownMs: 5_000,
enableExplicitGC: false,
};
// Validation
export function validateMemoryPressureConfig(c: MemoryPressureConfig): void {
for (const [name, ratio] of [
['softPressureRatio', c.softPressureRatio],
['hardPressureRatio', c.hardPressureRatio],
['criticalRatio', c.criticalRatio],
] as const) {
if (!Number.isFinite(ratio) || ratio < 0.3 || ratio > 0.98) {
throw new Error(`${name} must be a finite ratio in [0.3, 0.98]`);
}
}
if (c.softPressureRatio >= c.hardPressureRatio) {
throw new Error('softPressureRatio must be < hardPressureRatio');
}
if (c.hardPressureRatio >= c.criticalRatio) {
throw new Error('hardPressureRatio must be < criticalRatio');
}
if (!Number.isFinite(c.cleanupCooldownMs) || c.cleanupCooldownMs < 0) {
throw new Error('cleanupCooldownMs must be a non-negative number');
}
}
const debugLogger = createDebugLogger('MEMORY_PRESSURE');
const MIN_CGROUP_MEMORY_LIMIT = 64 * 1024 * 1024;
// Monitor
export class MemoryPressureMonitor extends EventEmitter {
private readonly config: MemoryPressureConfig;
private readonly coreConfig: Config;
private pendingCheck = false;
private cleanupInProgress = false;
private activeCleanupAction: CleanupRecommendation['action'] = 'none';
private lastCleanupAction: CleanupRecommendation['action'] = 'none';
private queuedCleanupRecommendation?: CleanupRecommendation;
private lastCleanupTime = 0;
private consecutiveCleanupFailures = 0;
private consecutiveIneffectiveCleanups = 0;
private consecutiveIneffectiveAggressiveCleanups = 0;
private cleanupGeneration = 0;
private readonly effectiveMemoryLimit: number;
constructor(coreConfig: Config, pressureConfig?: MemoryPressureConfig) {
super();
this.coreConfig = coreConfig;
this.config = { ...(pressureConfig ?? DEFAULT_PRESSURE_CONFIG) };
validateMemoryPressureConfig(this.config);
this.effectiveMemoryLimit = this.computeEffectiveMemoryLimit();
const heapSizeLimit = getHeapStatistics().heap_size_limit;
debugLogger.info(
`Effective memory limit: ${formatMiB(this.effectiveMemoryLimit)} MiB; ` +
`V8 heap limit: ${formatMiB(heapSizeLimit)} MiB`,
);
if (this.effectiveMemoryLimit <= 0) {
debugLogger.warn(
'Effective memory limit is not positive; RSS pressure checks are disabled',
);
}
}
// Public API
getConsecutiveFailures(): number {
return this.consecutiveCleanupFailures;
}
resetConsecutiveFailures(): void {
this.consecutiveCleanupFailures = 0;
this.consecutiveIneffectiveCleanups = 0;
this.consecutiveIneffectiveAggressiveCleanups = 0;
}
/**
* Reset session-scoped cleanup state and invalidate any async cleanup tail
* that was queued against the previous session's cache.
*/
resetForNewSession(): void {
this.cleanupGeneration++;
this.resetConsecutiveFailures();
this.cleanupInProgress = false;
this.activeCleanupAction = 'none';
this.queuedCleanupRecommendation = undefined;
this.lastCleanupAction = 'none';
this.lastCleanupTime = 0;
}
/**
* Schedule a deferred memory check after a tool finishes execution.
* Uses queueMicrotask to batch checks across concurrently-completing
* tools within the same event-loop tick.
*/
scheduleCheck(): void {
if (this.pendingCheck) return;
this.pendingCheck = true;
queueMicrotask(() => {
try {
this.performCheck();
} finally {
this.pendingCheck = false;
}
});
}
/** Force an immediate check (e.g. after a concurrent batch completes). */
performCheck(): void {
try {
this.performCheckInternal();
} catch (err) {
debugLogger.error(
`Memory pressure check failed: ${getErrorMessage(err)}`,
);
}
}
private performCheckInternal(): void {
const pressure = this.getPressureLevel();
if (pressure !== 'critical') {
this.consecutiveIneffectiveAggressiveCleanups = 0;
}
if (pressure === 'normal') return;
const recommendation = this.recommendCleanup(pressure);
if (recommendation.action === 'none') return;
const now = Date.now();
const isEscalation =
cleanupActionRank(recommendation.action) >
cleanupActionRank(this.lastCleanupAction);
const cleanupCooldownMs = this.getCleanupCooldownMs(recommendation.action);
if (!isEscalation && now - this.lastCleanupTime < cleanupCooldownMs) {
return;
}
this.executeCleanup(recommendation);
}
/**
* Determine the current memory pressure level from the stronger of:
* - RSS as a fraction of the effective memory limit (cgroup-aware).
* - V8 heap usage as a fraction of V8's heap size limit.
*/
getPressureLevel(): 'normal' | 'soft' | 'hard' | 'critical' {
let mem: ReturnType<typeof process.memoryUsage>;
try {
mem = process.memoryUsage();
} catch (err) {
debugLogger.error(
`Failed to read memory usage for pressure check: ${getErrorMessage(err)}`,
);
return 'normal';
}
const rssRatio =
this.effectiveMemoryLimit > 0 ? mem.rss / this.effectiveMemoryLimit : 0;
const heapSizeLimit = getHeapStatistics().heap_size_limit;
const heapRatio = heapSizeLimit > 0 ? mem.heapUsed / heapSizeLimit : 0;
const ratio = Math.max(rssRatio, heapRatio);
if (ratio >= this.config.criticalRatio) return 'critical';
if (ratio >= this.config.hardPressureRatio) return 'hard';
if (ratio >= this.config.softPressureRatio) return 'soft';
return 'normal';
}
// Cleanup
private recommendCleanup(
pressure: 'soft' | 'hard' | 'critical',
): CleanupRecommendation {
switch (pressure) {
case 'critical':
return {
action: 'aggressive',
steps: [
'clear_file_cache',
...(this.config.enableExplicitGC ? ['trigger_gc' as const] : []),
],
};
case 'hard':
return {
action: 'moderate',
steps: ['evict_cold_cache'],
};
case 'soft':
return {
action: 'light',
steps: ['evict_stale_cache'],
};
default:
return assertNever(pressure);
}
}
private executeCleanup(recommendation: CleanupRecommendation): void {
if (this.cleanupInProgress) {
const recommendationRank = cleanupActionRank(recommendation.action);
const activeRank = cleanupActionRank(this.activeCleanupAction);
const queuedRank = this.queuedCleanupRecommendation
? cleanupActionRank(this.queuedCleanupRecommendation.action)
: 0;
if (recommendationRank > activeRank && recommendationRank > queuedRank) {
this.queuedCleanupRecommendation = recommendation;
debugLogger.debug(
`Queued escalated cleanup "${recommendation.action}" while ` +
`"${this.activeCleanupAction}" is in progress`,
);
} else {
debugLogger.debug('Cleanup already in progress, skipping');
}
return;
}
let memBefore: number;
try {
memBefore = process.memoryUsage().rss;
} catch (err) {
this.recordCleanupFailure(recommendation, err);
return;
}
this.cleanupInProgress = true;
this.activeCleanupAction = recommendation.action;
this.lastCleanupAction = recommendation.action;
this.lastCleanupTime = Date.now();
const cleanupGeneration = this.cleanupGeneration;
void this.runCleanupSteps(recommendation.steps, cleanupGeneration)
.then(() => {
if (cleanupGeneration !== this.cleanupGeneration) {
return;
}
this.consecutiveCleanupFailures = 0;
setImmediate(() => {
if (cleanupGeneration !== this.cleanupGeneration) {
return;
}
try {
const memAfter = process.memoryUsage().rss;
this.logCleanupResult(memBefore, memAfter, recommendation);
} catch (err) {
debugLogger.error(
`Cleanup measurement failed: ${getErrorMessage(err)}`,
);
} finally {
this.finishCleanupAndRunQueued(cleanupGeneration);
}
});
})
.catch((err) => {
if (cleanupGeneration !== this.cleanupGeneration) {
return;
}
this.recordCleanupFailure(recommendation, err);
this.finishCleanupAndRunQueued(cleanupGeneration);
});
}
private finishCleanupAndRunQueued(cleanupGeneration: number): void {
if (cleanupGeneration !== this.cleanupGeneration) {
return;
}
this.cleanupInProgress = false;
this.activeCleanupAction = 'none';
const queuedRecommendation = this.queuedCleanupRecommendation;
this.queuedCleanupRecommendation = undefined;
if (queuedRecommendation) {
try {
this.executeCleanup(queuedRecommendation);
} catch (err) {
this.recordCleanupFailure(queuedRecommendation, err);
}
}
}
private getCleanupCooldownMs(
action: CleanupRecommendation['action'],
): number {
const baseCooldownMs = this.config.cleanupCooldownMs;
if (
action !== 'aggressive' ||
baseCooldownMs === 0 ||
this.consecutiveIneffectiveAggressiveCleanups < 3
) {
return baseCooldownMs;
}
const exponent = Math.min(
this.consecutiveIneffectiveAggressiveCleanups - 2,
6,
);
return baseCooldownMs * 2 ** exponent;
}
private logCleanupResult(
memBefore: number,
memAfter: number,
recommendation: CleanupRecommendation,
): void {
const freed = memBefore - memAfter;
const freedRatio = memBefore > 0 ? freed / memBefore : 0;
debugLogger.info(
`Cleanup "${recommendation.action}" completed; RSS delta ${freed} bytes ` +
`(${(freedRatio * 100).toFixed(1)}%)`,
);
if (freedRatio < 0.01) {
this.consecutiveIneffectiveCleanups++;
if (recommendation.action === 'aggressive') {
this.consecutiveIneffectiveAggressiveCleanups++;
}
if (shouldEmitRepeatedDiagnostic(this.consecutiveIneffectiveCleanups)) {
const event = {
rss: memAfter,
freedBytes: freed,
freedRatio,
consecutiveIneffectiveCleanups: this.consecutiveIneffectiveCleanups,
recommendation,
} satisfies MemoryCleanupIneffectiveEvent;
debugLogger.warn(
`Cleanup "${recommendation.action}" has been ineffective ` +
`${this.consecutiveIneffectiveCleanups} times consecutively`,
);
this.emitSafely('memory-cleanup-ineffective', event);
}
return;
}
this.consecutiveIneffectiveCleanups = 0;
if (recommendation.action === 'aggressive') {
this.consecutiveIneffectiveAggressiveCleanups = 0;
}
}
private recordCleanupFailure(
recommendation: CleanupRecommendation,
err: unknown,
): void {
const error = getErrorMessage(err);
let rss = 0;
try {
rss = process.memoryUsage().rss;
} catch (rssErr) {
debugLogger.error(
`Failed to read RSS after cleanup failure: ${getErrorMessage(rssErr)}`,
);
}
this.consecutiveCleanupFailures++;
debugLogger.error(
`Cleanup "${recommendation.action}" failed: ${error}; ` +
`consecutive failures: ${this.consecutiveCleanupFailures}`,
);
if (shouldEmitRepeatedDiagnostic(this.consecutiveCleanupFailures)) {
this.emitSafely('memory-cleanup-failed', {
rss,
consecutiveFailures: this.consecutiveCleanupFailures,
recommendation,
error,
} satisfies MemoryCleanupFailureEvent);
}
}
private emitSafely(eventName: string, event: unknown): void {
try {
this.emit(eventName, event);
} catch (err) {
debugLogger.error(`${eventName} handler threw: ${getErrorMessage(err)}`);
}
}
private async runCleanupSteps(
steps: CleanupStep[],
cleanupGeneration: number,
): Promise<void> {
for (const step of steps) {
if (cleanupGeneration !== this.cleanupGeneration) {
return;
}
this.executeStep(step);
// Keep a promise boundary between steps so escalated cleanups can queue
// behind the active cleanup instead of interleaving in the same stack.
await Promise.resolve();
}
}
private executeStep(step: CleanupStep): void {
switch (step) {
case 'clear_file_cache': {
this.coreConfig.getFileReadCache().clear();
debugLogger.debug('FileReadCache cleared');
break;
}
case 'evict_cold_cache': {
const evicted = this.coreConfig
.getFileReadCache()
.evictNotAccessedSince(30);
debugLogger.debug(`FileReadCache cold eviction: ${evicted} entries`);
break;
}
case 'evict_stale_cache': {
const evicted = this.coreConfig
.getFileReadCache()
.evictNotAccessedSince(60);
debugLogger.debug(`FileReadCache stale eviction: ${evicted} entries`);
break;
}
case 'trigger_gc': {
if (typeof global.gc === 'function') {
const before = process.memoryUsage().rss;
global.gc();
const after = process.memoryUsage().rss;
debugLogger.debug(`global.gc() freed ${before - after} bytes`);
} else {
debugLogger.warn(
'trigger_gc requested but global.gc is not available; ' +
'start Node.js with --expose-gc',
);
}
break;
}
default:
return assertNever(step);
}
}
// Memory metrics
private computeEffectiveMemoryLimit(): number {
const hostTotal = os.totalmem();
const cgroupV2Limit = this.readCgroupMemoryLimit(
'/sys/fs/cgroup/memory.max',
hostTotal,
);
if (cgroupV2Limit !== undefined) {
debugLogger.info(
`Using cgroup v2 memory limit: ${formatMiB(cgroupV2Limit)} MiB`,
);
return cgroupV2Limit;
}
const cgroupV1Limit = this.readCgroupMemoryLimit(
'/sys/fs/cgroup/memory/memory.limit_in_bytes',
hostTotal,
);
if (cgroupV1Limit !== undefined) {
debugLogger.info(
`Using cgroup v1 memory limit: ${formatMiB(cgroupV1Limit)} MiB`,
);
return cgroupV1Limit;
}
debugLogger.info(`Using host memory limit: ${formatMiB(hostTotal)} MiB`);
return hostTotal;
}
private readCgroupMemoryLimit(
filePath: string,
hostTotal: number,
): number | undefined {
try {
const raw = readFileSync(filePath, 'utf-8').trim();
if (raw === 'max') return undefined;
if (!/^-?\d+$/.test(raw)) {
debugLogger.warn(
`Ignoring non-numeric cgroup memory limit from ${filePath}: ${raw}`,
);
return undefined;
}
const limit = Number(raw);
if (!Number.isFinite(limit) || limit <= 0) {
debugLogger.warn(
`Ignoring out-of-range cgroup memory limit from ${filePath}: ${raw}`,
);
return undefined;
}
if (limit < MIN_CGROUP_MEMORY_LIMIT) {
debugLogger.warn(
`Ignoring unrealistically small cgroup memory limit from ` +
`${filePath}: ${raw}`,
);
return undefined;
}
// cgroup v1 represents "unlimited" with huge sentinel values.
if (!Number.isSafeInteger(limit)) {
debugLogger.debug(
`Ignoring unlimited cgroup memory limit from ${filePath}: ${raw}`,
);
return undefined;
}
if (hostTotal > 0 && limit > hostTotal) {
debugLogger.debug(
`Ignoring cgroup memory limit above host total from ${filePath}: ` +
`${raw}`,
);
return undefined;
}
return limit;
} catch (err) {
debugLogger.debug(
`Failed to read cgroup memory limit from ${filePath}: ` +
getErrorMessage(err),
);
return undefined;
}
}
}
function cleanupActionRank(action: CleanupRecommendation['action']): number {
switch (action) {
case 'aggressive':
return 3;
case 'moderate':
return 2;
case 'light':
return 1;
case 'none':
return 0;
default:
return assertNever(action);
}
}
function shouldEmitRepeatedDiagnostic(count: number): boolean {
// Emit once at the threshold, once soon after, then every 20 repeats so
// sustained pressure remains visible without flooding event listeners.
return count === 3 || count === 10 || (count > 10 && count % 20 === 0);
}
function formatMiB(bytes: number): string {
return (bytes / 1024 / 1024).toFixed(0);
}
function assertNever(value: never): never {
throw new Error(`Unhandled memory pressure monitor value: ${String(value)}`);
}

View File

@ -49,7 +49,7 @@ export async function generateSessionRecap(
const geminiClient = config.getGeminiClient();
if (!geminiClient) return null;
const fullHistory = geminiClient.getChat().getHistory();
const fullHistory = geminiClient.getHistoryShallow();
if (fullHistory.length < 2) return null;
const dialog = filterToDialog(fullHistory);

View File

@ -31,6 +31,7 @@ function makeConfig(opts: MockOptions): {
getFastModel: vi.fn(() => opts.fastModel ?? undefined),
getModel: vi.fn(() => 'qwen-plus'),
getGeminiClient: vi.fn(() => ({
getHistoryShallow: () => opts.history ?? [],
getChat: () => ({
getHistory: () => opts.history ?? [],
}),
@ -202,7 +203,10 @@ describe('tryGenerateSessionTitle', () => {
getFastModel: vi.fn(() => 'qwen-turbo'),
getModel: vi.fn(() => 'qwen-plus'),
getGeminiClient: vi.fn(() => ({
getChat: () => ({ getHistory: () => history }),
getHistoryShallow: () => history,
getChat: () => ({
getHistory: () => history,
}),
})),
getBaseLlmClient: vi.fn(() => ({ generateJson })),
} as unknown as Config;
@ -240,7 +244,10 @@ describe('tryGenerateSessionTitle', () => {
getFastModel: vi.fn(() => 'qwen-turbo'),
getModel: vi.fn(() => 'qwen-plus'),
getGeminiClient: vi.fn(() => ({
getChat: () => ({ getHistory: () => history }),
getHistoryShallow: () => history,
getChat: () => ({
getHistory: () => history,
}),
})),
getBaseLlmClient: vi.fn(() => ({ generateJson })),
} as unknown as Config;

View File

@ -113,7 +113,7 @@ export async function tryGenerateSessionTitle(
const geminiClient = config.getGeminiClient();
if (!geminiClient) return { ok: false, reason: 'no_client' };
const fullHistory = geminiClient.getChat().getHistory();
const fullHistory = geminiClient.getHistoryShallow();
if (fullHistory.length < 2) return { ok: false, reason: 'empty_history' };
const dialog = filterToDialog(fullHistory);

View File

@ -21,7 +21,6 @@ import {
type AnsiOutput,
} from '../utils/terminalSerializer.js';
import { normalizePathEnvForWindows } from '../utils/windowsPath.js';
import { getShellContextEnvVars } from '../utils/shellContextEnv.js';
import { createDebugLogger } from '../utils/debugLogger.js';
const { Terminal } = pkg;
@ -551,7 +550,6 @@ export class ShellExecutionService {
QWEN_CODE: '1',
TERM: 'xterm-256color',
PAGER: 'cat',
...getShellContextEnvVars(),
},
});
@ -1154,7 +1152,6 @@ export class ShellExecutionService {
TERM: 'xterm-256color',
PAGER: shellExecutionConfig.pager ?? 'cat',
GIT_PAGER: shellExecutionConfig.pager ?? 'cat',
...getShellContextEnvVars(),
},
handleFlowControl: true,
});

View File

@ -102,11 +102,7 @@ export async function readWorktreeSession(
return parsed;
}
/**
* Atomically writes the sidecar. Uses `atomicWriteJSON` (write-to-temp +
* rename) so a crash mid-write can never leave a half-written file that
* subsequent reads would reject as malformed.
*/
/** Writes the worktree session sidecar via `atomicWriteJSON`. */
export async function writeWorktreeSession(
filePath: string,
session: WorktreeSession,

View File

@ -53,7 +53,6 @@ import {
isShellCommandReadOnlyAST,
} from '../utils/shellAstParser.js';
import { getCurrentAgentId } from '../agents/runtime/agent-context.js';
import { getShellContextEnvVars } from '../utils/shellContextEnv.js';
const debugLogger = createDebugLogger('MONITOR');
@ -367,7 +366,6 @@ class MonitorToolInvocation extends BaseToolInvocation<
QWEN_CODE: '1',
TERM: 'dumb', // no color codes for streaming
PAGER: 'cat',
...getShellContextEnvVars(),
},
});
} catch (err) {

View File

@ -269,4 +269,160 @@ describe('atomicWriteFile', () => {
path.normalize('../otherDir/target.txt'),
);
});
it.skipIf(process.platform === 'win32')(
'should use atomic rename when ownership matches (inode changes)',
async () => {
const filePath = path.join(tmpDir, 'mine.txt');
await fs.writeFile(filePath, 'original');
const inoBefore = (await fs.stat(filePath)).ino;
await atomicWriteFile(filePath, 'updated');
const statAfter = await fs.stat(filePath);
// Atomic rename produces a new inode.
expect(statAfter.ino).not.toBe(inoBefore);
expect(await fs.readFile(filePath, 'utf-8')).toBe('updated');
},
);
it.skipIf(
process.platform === 'win32' || typeof process.geteuid !== 'function',
)(
'should fall back to in-place write when atomic rename would change ownership',
async () => {
// Simulate a file owned by a different user by replacing process.geteuid
// so it reports a uid that doesn't match the file's real uid. The code
// should detect rename would strip ownership and fall back to in-place
// writeFile, which preserves the inode — our signal that fallback ran.
const filePath = path.join(tmpDir, 'shared.txt');
await fs.writeFile(filePath, 'original');
await fs.chmod(filePath, 0o664);
const realStat = await fs.stat(filePath);
const inoBefore = realStat.ino;
const realGeteuid = process.geteuid!;
process.geteuid = () => realStat.uid + 1;
try {
await atomicWriteFile(filePath, 'updated');
} finally {
process.geteuid = realGeteuid;
}
expect(await fs.readFile(filePath, 'utf-8')).toBe('updated');
const statAfter = await fs.stat(filePath);
// In-place write preserves the inode — proves rename was skipped.
expect(statAfter.ino).toBe(inoBefore);
// Permissions preserved.
expect(statAfter.mode & 0o777).toBe(0o664);
// No leftover temp file.
expect(await fs.readdir(tmpDir)).toEqual(['shared.txt']);
},
);
it.skipIf(
process.platform === 'win32' || typeof process.geteuid !== 'function',
)(
'should skip in-place fallback for non-regular files and use atomic replace',
async () => {
// FIFO + ownership mismatch must NOT take the in-place fallback —
// open(O_WRONLY|O_TRUNC) against a FIFO would block forever
// waiting for a reader. The atomic rename path instead replaces
// the FIFO with a regular file, which is the only sane behavior
// for "write to this path" semantics on a special file.
const { execSync } = await import('node:child_process');
const fifoPath = path.join(tmpDir, 'pipe.fifo');
execSync(`mkfifo "${fifoPath}"`);
const realStat = await fs.stat(fifoPath);
expect(realStat.isFIFO()).toBe(true);
const realGeteuid = process.geteuid!;
process.geteuid = () => realStat.uid + 1;
try {
// If the in-place fallback were taken, this would hang
// indefinitely. Vitest's default timeout will catch that.
await atomicWriteFile(fifoPath, 'content');
} finally {
process.geteuid = realGeteuid;
}
// Atomic path replaced the FIFO with a regular file.
const statAfter = await fs.stat(fifoPath);
expect(statAfter.isFile()).toBe(true);
expect(await fs.readFile(fifoPath, 'utf-8')).toBe('content');
},
);
it.skipIf(
process.platform === 'win32' || typeof process.geteuid !== 'function',
)(
'should write via in-place fallback through a resolved symlink when ownership differs',
async () => {
// atomicWriteFile resolves the symlink via resolveSymlinkChain
// before stat, so the in-place write targets the real file.
// Verifies the symlink itself is preserved.
const realFile = path.join(tmpDir, 'real.txt');
const symlinkAt = path.join(tmpDir, 'attacker-symlink.txt');
await fs.writeFile(realFile, 'real-content');
await fs.symlink(realFile, symlinkAt);
const realGeteuid = process.geteuid!;
const realStat = await fs.stat(realFile);
const inoBefore = realStat.ino;
process.geteuid = () => realStat.uid + 1;
try {
await atomicWriteFile(symlinkAt, 'updated');
} finally {
process.geteuid = realGeteuid;
}
// The real file is updated; the symlink itself is preserved.
expect(await fs.readFile(realFile, 'utf-8')).toBe('updated');
expect((await fs.stat(realFile)).ino).toBe(inoBefore);
expect((await fs.lstat(symlinkAt)).isSymbolicLink()).toBe(true);
},
);
it.skipIf(
process.platform === 'win32' ||
typeof process.geteuid !== 'function' ||
// chmod 0o000 against the file's real owner still succeeds via
// POSIX rename in CI/sandbox setups where the user is effectively
// root; only assert real EACCES when we own and can be denied.
process.geteuid() === 0,
)(
'should surface EACCES when in-place fallback hits an unwritable file',
async () => {
// Atomic rename used to silently replace files the calling user
// has no write permission on (rename only needs parent-dir write).
// The in-place fallback respects the file's mode and surfaces
// EACCES — the correct behavior for "you don't own this, you
// shouldn't be replacing it" scenarios.
const filePath = path.join(tmpDir, 'readonly.txt');
await fs.writeFile(filePath, 'original');
await fs.chmod(filePath, 0o444);
const realStat = await fs.stat(filePath);
const realGeteuid = process.geteuid!;
process.geteuid = () => realStat.uid + 1;
try {
await expect(atomicWriteFile(filePath, 'updated')).rejects.toThrow(
/EACCES/,
);
} finally {
process.geteuid = realGeteuid;
// Restore mode so afterEach's rm can clean up.
await fs.chmod(filePath, 0o644);
}
// Original content untouched.
expect(await fs.readFile(filePath, 'utf-8')).toBe('original');
},
);
});

View File

@ -5,6 +5,7 @@
*/
import * as crypto from 'node:crypto';
import type { Stats } from 'node:fs';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { isNodeError } from './errors.js';
@ -94,19 +95,12 @@ async function resolveSymlinkChain(filePath: string): Promise<string> {
}
/**
* Atomically write arbitrary content (string or Buffer) to a file.
* Atomically write content to a file (write-to-temp + rename).
*
* 1. Resolve symlinks (including broken ones) so the temp file lives
* next to the real target.
* 2. Write to a temporary file with fsync (`flush: true` by default).
* 3. Preserve the original file's permissions (or apply `options.mode`).
* 4. Atomic rename (POSIX) with retry (Windows).
* 5. On EXDEV (cross-device rename), fall back to direct write.
* **Note:** the EXDEV fallback is non-atomic — a crash mid-write
* can leave a partially-written file. EXDEV only occurs when the
* resolved target path is on a different filesystem than its parent
* directory, which is rare in practice.
* 6. Always clean up the temp file on failure.
* Falls back to in-place write when the existing file's uid differs
* from the process's euid — POSIX rename would reset ownership.
* Also falls back on EXDEV (cross-device). Both fallbacks lose crash
* atomicity but preserve the existing inode's uid.
*
* The parent directory of `filePath` must already exist.
*/
@ -122,19 +116,20 @@ export async function atomicWriteFile(
const targetPath = await resolveSymlinkChain(filePath);
const tmpPath = `${targetPath}.${crypto.randomBytes(6).toString('hex')}.tmp`;
// Stat the target to preserve existing permissions (mask out file-type bits).
let existingMode: number | undefined;
// Stat the target to preserve existing permissions and detect
// ownership-changing renames (see the ownership-preservation note in
// the function doc).
let existingStat: Stats | undefined;
try {
const stat = await fs.stat(targetPath);
existingMode = stat.mode & 0o7777;
existingStat = await fs.stat(targetPath);
} catch (err) {
if (!isNodeError(err) || err.code !== 'ENOENT') {
throw err;
}
}
const existingMode =
existingStat !== undefined ? existingStat.mode & 0o7777 : undefined;
const desiredMode = existingMode ?? options?.mode;
const writeOptions: {
@ -156,6 +151,33 @@ export async function atomicWriteFile(
}
};
// Detect when atomic rename would silently change ownership. POSIX
// rename creates a new inode owned by the process's euid:egid; if the
// existing file has a different uid, fall back to in-place write which
// preserves the inode and therefore uid. Only uid is compared — gid
// is intentionally skipped because macOS inherits the parent
// directory's GID for new files, making egid !== file.gid a
// false positive on the most common dev platform.
const ownershipWouldChange = (): boolean => {
if (existingStat === undefined) return false;
if (process.platform === 'win32') return false;
const euid = process.geteuid?.();
if (euid === undefined) return false;
return existingStat.uid !== euid;
};
if (
existingStat !== undefined &&
existingStat.isFile() &&
ownershipWouldChange()
) {
await fs.writeFile(targetPath, data, writeOptions);
await tryChmod(targetPath);
return;
}
const tmpPath = `${targetPath}.${crypto.randomBytes(6).toString('hex')}.tmp`;
try {
await fs.writeFile(tmpPath, data, writeOptions);
await tryChmod(tmpPath);
@ -179,17 +201,7 @@ export async function atomicWriteFile(
}
}
/**
* Atomically write a JSON value to a file.
*
* Delegates to {@link atomicWriteFile} for the actual atomic
* write-to-temp + rename flow.
*
* Note: if `filePath` is a symlink, the write resolves the chain
* and updates the real target file — the symlink itself is preserved.
*
* The parent directory of `filePath` must already exist.
*/
/** Atomically write a JSON value to a file. Delegates to {@link atomicWriteFile}. */
export async function atomicWriteJSON(
filePath: string,
data: unknown,

View File

@ -116,4 +116,45 @@ describe('contextLengthError', () => {
expect(info.isExceeded).toBe(false);
});
it('skips accessor properties that throw while collecting error text', () => {
const error = new Error('Connection error.');
Object.defineProperty(error, 'name', {
enumerable: true,
get() {
throw new TypeError('Value of "this" must be of DOMException');
},
});
Object.defineProperty(error, 'details', {
enumerable: true,
get() {
throw new TypeError('Value of "this" must be of DOMException');
},
});
const info = getContextLengthExceededInfo(error);
expect(info.isExceeded).toBe(false);
expect(info.message).toContain('Connection error.');
});
it('skips throwing accessors on plain objects', () => {
const errorLike: Record<string, unknown> = {};
Object.defineProperty(errorLike, 'detail', {
enumerable: true,
get() {
throw new TypeError('accessor refused');
},
});
Object.defineProperty(errorLike, 'message', {
enumerable: true,
value: 'context_length_exceeded: too many tokens',
});
const info = getContextLengthExceededInfo(errorLike);
expect(info.isExceeded).toBe(true);
expect(info.message).toContain('context_length_exceeded');
});
});

View File

@ -103,6 +103,32 @@ function tryParseEmbeddedJson(text: string): unknown | undefined {
}
}
function safeReadProperty(value: object, key: string): unknown {
try {
return (value as Record<string, unknown>)[key];
} catch {
return undefined;
}
}
function enumerableValues(value: object): unknown[] {
try {
return Object.values(value);
} catch {
try {
const descriptors = Object.getOwnPropertyDescriptors(value);
return Object.values(descriptors)
.filter(
(descriptor): descriptor is PropertyDescriptor & { value: unknown } =>
'value' in descriptor && descriptor.enumerable === true,
)
.map((descriptor) => descriptor.value);
} catch {
return [];
}
}
}
function collectStrings(
value: unknown,
seen: Set<object>,
@ -135,11 +161,21 @@ function collectStrings(
const strings: string[] = [];
if (value instanceof Error) {
strings.push(value.name, value.message);
strings.push(...collectStrings(value.cause, seen, depth + 1));
const name = safeReadProperty(value, 'name');
const message = safeReadProperty(value, 'message');
if (typeof name === 'string') {
strings.push(name);
}
if (typeof message === 'string') {
strings.push(message);
}
strings.push(
...collectStrings(safeReadProperty(value, 'cause'), seen, depth + 1),
);
}
for (const [, nested] of Object.entries(value)) {
for (const nested of enumerableValues(value)) {
strings.push(...collectStrings(nested, seen, depth + 1));
}

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