* fix(core,cli): replace full-history structuredClone with shallow/tail variants to prevent OOM on resume
Several UI and service call sites clone the entire chat history via
structuredClone(getHistory()) every turn. On a resumed session with
thousands of entries, each clone allocates 150-200 MB transiently.
When multiple async side-requests overlap (suggestion generation,
auto-title, checkpointing), multiple clones coexist on the heap,
pushing V8 past its limit within 10 turns (2 GB heap cap).
Changes:
- AppContainer.tsx: use getHistoryTail(40, true) instead of
getHistory(true) + slice(-40)
- btwCommand.ts: same pattern, use getHistoryTail(40, true)
- sessionTitle.ts: use getHistoryShallow() (read-only filtering)
- sessionRecap.ts: use getHistoryShallow() (read-only filtering)
- useGeminiStream.ts: use getHistoryShallow() for checkpoint
serialization (only needs to survive JSON.stringify)
Closes#4624
* fix(test): update mocks for getHistoryShallow/getHistoryTail in sessionTitle and btwCommand tests
* fix(cli): migrate remaining getHistory() clone sites to shallow/tail variants
- AppContainer.tsx rewind path: getHistory() → getHistoryShallow()
(only used read-only by computeApiTruncationIndex)
- Session.ts ACP rewind: getHistory() → getHistoryShallow()
(only walks entries to compute truncation index)
- Session.ts stop-hook: getHistory() + filter(.model).pop() →
getLastModelMessageText() (O(1) backward scan, no clone)
* fix(core): use client-level getHistoryShallow with fallback
sessionTitle.ts and sessionRecap.ts were calling
chat.getHistoryShallow() directly, bypassing the client-level
wrapper that provides a getHistory() fallback when the chat
implementation doesn't support shallow reads. Use
geminiClient.getHistoryShallow() instead.
Update test mocks to match the new call site.
* fix(test): add getHistoryShallow and getLastModelMessageText to Session test mocks
Session.ts now calls chat.getHistoryShallow() in rewindToTurn and
chat.getLastModelMessageText() in the Stop hook. Update all mockChat
instances in Session.test.ts to provide these methods.
Detach closeSession/killSession from the session entry's owning channel instead of the current attach target, so the correct channel is decremented and killed during channel overlap (old channel dying while a fresh channel is current). Extracts findChannelInfoForEntry/detachSessionIdFromEntryChannel helpers with unit + integration coverage. Fixes#4325.
The Auto-memory / Auto-dream / Auto-skill rows initialized their state
from Config getters, which are frozen at startup and never reflect a
setValue() write. Each /memory reopen re-mounts the dialog and re-reads
that stale snapshot, so a just-flipped toggle appeared to revert. Read the
initial state from the live merged settings instead, matching the existing
write path (bareMode semantics preserved).
Also switch the test's `act` import to `react` — the previously used
@testing-library/react is declared in package.json but not installed, so
the suite could not run — and add a mount/unmount/remount regression test.
* feat(cli): add settings corruption recovery dialog
* fix(cli): address review1 comments – copy instead of rename, clean DEBUG logs & lint
* test(cli): add SettingsCorruptedDialog keyboard navigation & callback coverage
* Update packages/cli/src/config/settings.test.ts
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* Update packages/cli/src/config/settings.ts
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* fix(cli): drop corrupted-path filter, use corruptedPath as sole signal
* fix(test): add missing truncateToItem to mockUIState
* fix(cli): prevent env var stale state and unnecessary normalization writes
* Apply suggestions from code review
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* fix(cli): resolve merge conflict and fix formatting errors from PR review update
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* fix(cli): prevent validateAuthMethod from consuming corruption env vars
* test(settings): fix scope guard test to actually set env vars
* fix(cli): separate corruption warning from migrationWarnings
* fix(ui): extract CORRUPTED_SUFFIX constant to avoid magic string
* fix(ui): emit error on restore failure in onExit handler
* test(ui): strengthen up/down arrow test to assert selection on target line
* test(settings): strengthen double-corruption and scope guard assertions
* test(ui): assert selection moves in onContinue test before pressing Enter
* fix(ui): include corruption dialog in dialogsVisible to suppress global keypress
* fix(ui): resolve type incompatibility in dialogsVisible and test helpers
* fix(cli): block corruption env var injection and harden error handling
Co-Authored-By: wenshao <shaojin.wensj@alibaba-inc.com>
* fix(cli): harden corruption env var guard with helper, comment, and regression test
* fix(cli): add afterSpawn callback to clear corruption env vars after spawn
Co-Authored-By: qwen3.7-max <noreply@qwen-code.ai>
* fix(cli): share mockSpawn instance between default and named exports in relaunch test
* Update packages/cli/src/utils/relaunch.ts
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
---------
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
Co-authored-by: qwen3.7-max <noreply@qwen-code.ai>
* fix(config): load home .env vars before settings ${VAR} resolution (#4466)
${VAR} placeholders in settings.json (e.g. MCP server headers) could not
reference variables defined in ~/.qwen/.env because resolveEnvVarsInObject()
ran before loadEnvironment() loaded the .env file into process.env.
Add preLoadHomeEnvVars() that loads all variables from home-level .env files
(~/.qwen/.env, ~/.env) into process.env in no-override mode before settings
env var resolution. Workspace .env files and settings.env are still handled
by the existing loadEnvironment() call after settings merge.
Fixes#4466
* test: add env var resolution from .env file test (#4466)
* fix(config): use customEnv fallback for home .env resolution (#4466)
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
Signed-off-by: kagura-agent <kagura.agent.ai@gmail.com>
* fix: align .env precedence and fix test mock
- Use ??= in getHomeEnvFallbackVars() so the more-specific file
(~/.qwen/.env) wins over ~/.env, matching dotenv first-occurrence-wins
- Fix test 'QWEN_HOME is set': use customSettingsPath matching the
runtime QWEN_HOME instead of the module-level USER_SETTINGS_PATH
constant (fixes mock mismatch that cascaded into 7 test failures)
- Remove unused homeEnvPath variable (tsc/eslint warning)
- Add debugLogger.warn in catch block for I/O errors
- Document that the dict intentionally skips
PROJECT_ENV_HARDCODED_EXCLUSIONS (substitution scope is narrower
than process.env population)
Signed-off-by: kagura-agent <kagura.agent.ai@gmail.com>
* test: add .env fallback, precedence, and error path tests
Address R2 reviewer suggestions:
- Add ~/.env fallback positive path test (no QWEN_HOME)
- Add precedence test: ~/.qwen/.env wins over ~/.env (first-write-wins)
- Add error path test: readFileSync throws, loadSettings still succeeds
- Add code comment explaining intentional path discrepancy between
getHomeEnvFallbackVars() and getUserLevelEnvPaths()
* docs: clarify customEnv precedence comment per reviewer suggestion
---------
Signed-off-by: kagura-agent <kagura.agent.ai@gmail.com>
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
* fix(cli): stabilize statusline preset ordering
* test(cli): make statusline helper contracts explicit
Add direct coverage for exported statusline preset helper behavior requested during PR review.
Constraint: Address PR #4634 review feedback for direct exported helper tests.
Rejected: Relying on existing integration coverage | Direct tests were requested for exported helper contracts.
Confidence: high
Scope-risk: narrow
Directive: Keep preset item ordering and reasoning formatting contracts directly covered when these helpers change.
Tested: cd packages/cli && npx vitest run src/ui/statusLinePresets.test.ts; cd packages/cli && npx vitest run src/ui/statusLinePresets.test.ts src/ui/components/StatusLineDialog.test.tsx src/ui/hooks/useStatusLine.test.ts; cd packages/cli && npx eslint src/ui/statusLinePresets.ts src/ui/statusLinePresets.test.ts; git diff --check
Not-tested: Full repository test suite.
Mid-turn user messages (typed during tool execution) were added to UI
history as type 'user', causing isRealUserTurn to count them. But in
the API history, they are merged into the preceding tool_result Content
(alongside functionResponse), making them invisible to isUserTextContent.
This UI/API count mismatch caused computeApiTruncationIndex to return -1,
producing a false "Cannot rewind to a compressed turn" error.
Fix: change mid-turn messages from type 'user' to type 'notification'
in both live and resume paths so isRealUserTurn no longer counts them.
Closes#4579
The auto-compaction notice hardcoded "approached the input token limit"
even when the screenshot-overflow trigger fired. In computer-use sessions
that's misleading: compaction can fire on accumulated tool screenshots
while token usage is far below the window limit (observed: the notice
claimed "approached the input token limit" at ~116K/1M tokens when it was
actually the image-count trigger).
Add ChatCompressionInfo.triggerReason ('token_limit' | 'image_overflow' |
'manual'); compress() sets it to 'image_overflow' when the screenshot
trigger is what let it through the cheap gate. Both the TUI
(useGeminiStream) and ACP (Session) notices now show an accurate clause.
* feat(computer-use): add tool name constants
* feat(computer-use): hardcode upstream tool schemas
* feat(computer-use): add enableComputerUse setting (default true)
* chore(vscode-ide-companion): sync settings schema for computerUse
* feat(computer-use): MCP stdio client for upstream binary
* feat(computer-use): ComputerUseTool wrapper + bootstrap stub
* feat(computer-use): register 9 deferred tools when enabled
* feat(computer-use): persist install approval state under ~/.qwen
* feat(computer-use): detect upstream permission errors
* feat(computer-use): bootstrap state machine (install + permissions)
* feat(computer-use): wire install approval to qwen-code confirm UX
* chore(computer-use): script to sync schemas from upstream
* fix(computer-use): consolidate package spec, surface download progress, correct version comment
* docs(computer-use): implementation plan
* fix(computer-use): forward image content parts to the model
* fix(computer-use): coerce string numbers to integers + clarify required fields
* fix(computer-use): detect missing Screen Recording + re-spawn doctor across permission transitions
* fix(computer-use): auto-reconnect on transport-closed errors
* fix(computer-use): sync schemas with upstream canonical contract
Regenerated schemas.ts from upstream open-computer-use@latest via
scripts/sync-computer-use-schemas.ts. Key contract fixes:
- element_index: type integer → string (upstream reads via optionalString)
- x/y/from_x/from_y/to_x/to_y: type integer → number (upstream uses optionalDouble)
- scroll: adds required direction enum + requires element_index (not pages)
- click: adds optional mouse_button string enum (left/right/middle)
- Descriptions updated to upstream verbatim text (no "REQUIRED:" prefix)
* fix(computer-use): bidirectional type coercion for string element_index
Rename coerceNumericStrings → coerceTypes and add Direction 2:
when schema declares type: "string" and model sends a number,
stringify it (e.g. element_index: 2 → "2"). This fixes the upstream
runtime error where optionalString returns nil for numeric element_index.
Direction 1 (string → number for integer/number fields) is preserved
unchanged for x/y coordinate fields.
Update tests: element_index coercion tests now reflect string schema
type; add new "coerces integer element_index to string" test cases.
* feat(prompts): strengthen deferred-tools guidance to prevent param guessing
* fix(computer-use): clearer wording for permission-transition onboarding message
* fix(computer-use): only probe permissions on fresh client start, not every tool call
* docs(computer-use): correct comment about permission-revocation recovery behavior
* fix(computer-use): pin upstream version exactly to prevent schema drift
* fix(computer-use): use pinned package spec in client singleton to prevent schema drift
* fix(computer-use): decouple install gate from per-action permission grant
* fix(computer-use): route registration through PermissionManager-aware registerLazy
* fix(computer-use): probe via upstream doctor instead of get_app_state on Finder
The previous probe called get_app_state on Finder, which has the side
effect of activating the target app via upstream's unhide / open -b /
AXRaise logic. Result: Finder popped to the foreground once per fresh
session even when the user's task had nothing to do with it.
The doctor CLI reads TCC + runtime preflight and prints a summary to
stdout, exiting silently when permissions are granted. When any
permission is missing, doctor launches the onboarding window via
LaunchServices (which dedups so repeated invocations focus the
existing window). We parse the stdout summary and rely on doctor's
own window-launching for the UX trigger — no separate spawnDoctor
call needed.
Side effect for steady-state sessions (permissions already granted):
ZERO Finder activation. The probe spawns npx -y doctor once per fresh
client start (~200-500ms), and that's it.
Also bumped pollIntervalMs default from 2s to 5s to amortize the
npx-spawn overhead during the rare permission-grant flow.
* fix(cli): prevent file paths from being treated as slash commands (#1804)
When users input file paths starting with '/' (e.g. '/api/apiFunction/...',
'/Users/name/path'), they were incorrectly parsed as slash commands, resulting
in "Unknown command" errors. The input was discarded instead of being sent to
the model for processing.
Root cause: isSlashCommand() only checked for a '/' prefix without validating
whether the first token actually looks like a command name. Any '/' prefix
triggered the slash command flow, and when no matching command was found, the
error was shown with no fallback.
Fix: Add looksLikeCommandName() that validates command names contain only
[a-zA-Z0-9:_-]. Both isSlashCommand() and handleSlashCommand() now check the
first token — if it contains path separators, dots, or non-ASCII characters,
the input falls through to normal model processing instead of the command
dispatcher.
Closes#1804
* fix(cli): allow dots in command names and fix prettier formatting
Address review feedback:
- Allow '.' in looksLikeCommandName() regex to support extension-qualified
commands like gcp.deploy (CommandService renames conflicts as ext.cmd)
- Add regression tests for dot-named commands in both commandUtils and
slashCommandProcessor
- Fix prettier formatting in slashCommandProcessor test file
* fix(cli): handle slash command review edge cases
* docs(cli): align slash command validation comment
* fix(cli): preserve slash prompt ordering
* fix(cli): reject shell-metacharacter slash tokens
* test(cli): align slash command action mocks
* fix(cli): track model-sent user turns
* fix(cli): narrow slash path handling scope
* fix(cli): split slash routing follow-up
* fix(cli): tighten slash routing follow-up scope
* fix(cli): address slash routing review gaps
* fix(cli): keep slash history follow-up focused
* fix(cli): align resume history item typing
* fix(cli): address slash history review suggestions
* test(cli): harden slash command history item ids
* chore(cli): use HistoryItemWithoutId in useEditorSettings.test
* refactor(cli): keep setSessionName optional in useSlashCommandProcessor
main currently exposes setSessionName as an optional trailing parameter.
The earlier addition of updateItem pushed it before updateItem and
forced every caller — including AppContainer and all tests — to pass an
explicit undefined. Reorder so updateItem stays required and
setSessionName remains optional, preserving the prior ergonomic.
* test(cli): fix slash command processor hook args
* fix(cli): harden slash command history metadata
* feat(channels): add Feishu (Lark) channel adapter
* fix(channels/feishu): fix webhook stop button, memory leak, spin-wait timeout, and reaction cleanup
* fix(channels/feishu): fix security, stability and build issues from PR review
* fix(channels/feishu): fix card lifecycle, streaming limits, and download safety from CR round 2
* fix(channels/feishu): harden webhook, card lifecycle, and disconnect cleanup from CR round 3
* fix(feishu): clarify stoppedMessages JSDoc to match actual cleanup behavior
* fix(channels/feishu): handle post messages without language key wrapper in quote context
* fix(channels/feishu): fix webhook signature bypass, stop-button double-send, and blockStreaming duplicates from CR round 4
* fix(channels/feishu): harden card lifecycle, markdown splitting, and defensive guards from CR round 5
* fix(channels/feishu): harden card lifecycle, markdown splitting, and defensive guards from CR round 5
- Set cardCreationFailed on onPromptStart failure to prevent retry spiral
- Skip throttle updates when card creation permanently failed
- Handle code fences in hard-split and table-stripping fallbacks
- Use parity-based fence detection in splitByTables (align with splitChunks)
- Add cs.stopped and else branch in onPromptEnd to prevent timer race and state leak
- Mark cardState.stopped after busy-wait timeout to abandon orphaned in-flight creation
- Apply MAX_CARD_CHARS truncation with fence parity in onResponseComplete
- Sanitize senderId before <at> tag interpolation
- Use replaceAll + callback form for mention replacement
- Floor token expiry to prevent thundering herd on expire:0
- Add log for stop-button auth rejection
- Fix stoppedMessages JSDoc to match actual cleanup lifecycle
- Fix test fixture to match "still creating" scenario
- Fix typecheck errors in test file (TS2571, TS4111)
- Add stop-button auth negative path tests (operator mismatch, missing operator, missing sender)
- Replace spanning regex in table-stripping with line-by-line stripTables() to resolve CodeQL ReDoS warning
* fix(channels/feishu): fix HMAC bypass, prompt injection, SSRF, and card lifecycle from CR round 5-6
Security:
- Fix webhook HMAC bypass: use defineProperty(non-enumerable) for headers instead of prototype shadowing
- Fix cross-user prompt injection: mark quoted content as untrusted with explicit marker
- Fix SSRF: validate all Feishu IDs with FEISHU_ID_RE before URL interpolation in 6 endpoints
- Fix safeSenderId regex: add hyphen to character class so ou_abc-def-123 is not rejected
Card lifecycle:
- Set cardCreationFailed on onPromptStart failure to prevent retry spiral
- Skip throttle updates when card creation permanently failed
- Fallback to plain message delivery when cardCreationFailed with accumulated text
- Track creationTimer in CardSessionState so cleanupCard/disconnect can cancel orphaned card creation
- Add cs.stopped and else branch in onPromptEnd to prevent timer race and state leak
- Mark cardState.stopped after busy-wait timeout to abandon orphaned in-flight creation
- Apply MAX_CARD_CHARS truncation with fence parity in onResponseComplete
- Preserve atPrefix in streaming truncation to prevent @mention visual snap
- Account for suffix and fence reserve in truncation maxBody calculation
- Clean up auxiliary maps after handleInbound when gate rejects the message
- Clean up blockStreaming mode Map entries in onPromptEnd
- Skip bare @mention without question text
Markdown:
- Handle code fences in hard-split and table-stripping fallbacks
- Use parity-based fence detection in splitByTables (align with splitChunks)
- Replace spanning regex in table-stripping with line-by-line stripTables() to resolve CodeQL ReDoS warning
Defensive guards:
- Sanitize senderId before <at> tag interpolation
- Use replaceAll + callback form for mention replacement
- Floor token expiry to prevent thundering herd on expire:0
- Add log for stop-button auth rejection
Tests:
- Fix stoppedMessages JSDoc to match actual cleanup lifecycle
- Fix test fixture to match "still creating" scenario
- Fix typecheck errors in test file (TS2571, TS4111)
- Add stop-button auth negative path tests (operator mismatch, missing operator, missing sender)
- Assert cancelSession called in stop-button happy-path test
* fix(channels/feishu): add request timeouts, token dedup, and harden file/quote sanitization
* fix(channels/feishu): harden card lifecycle, webhook auth, and resource cleanup from CR round 7
* fix(channels/feishu): harden card lifecycle, mention handling, and error recovery
* fix(cli): surface startup warnings on stderr before TUI render (#4448)
When settings.json has invalid JSON, the file is renamed to
.corrupted.<timestamp> and a warning is added to startupWarnings.
Previously these warnings were only rendered inside the TUI's
Notifications component, which can be obscured by the onboarding
flow ('Connect a provider') — leaving users unaware their settings
were silently reset.
Now all startup warnings are written to stderr before the TUI takes
over. This ensures the message appears in the terminal scrollback
regardless of what the TUI shows. In non-interactive mode (--prompt,
piped stdin) this is the *only* output channel for these warnings,
closing a gap where they were collected but never emitted.
* fix(cli): emit settings warnings before relaunch to ensure parent surfaces them
Move getSettingsWarnings() stderr emission to right after loadSettings(),
before the sandbox/relaunch block. This ensures the parent process prints
corruption warnings before relaunchAppInChildProcess() spawns the child
and exits.
Add regression test verifying getSettingsWarnings returns non-empty,
human-readable warnings containing 'invalid JSON' when settings.json
has broken content.
Addresses review feedback from @wenshao on #4461.
Fixes#4448
Signed-off-by: kagura-agent <kagura@openclaw.dev>
---------
Signed-off-by: kagura-agent <kagura@openclaw.dev>
* feat(cli): default auto-dream/auto-skill to on and add /memory toggle
Bring the managed memory pipeline closer to its intended out-of-the-box
experience: auto-dream and auto-skill now default to enabled (matching
the existing auto-memory default), so users get summarized memories and
reusable project skills without having to opt in.
The /memory dialog previously only exposed Auto-memory and Auto-dream
toggles. With auto-skill now on by default, users need an equally
discoverable way to opt out, so this adds an Auto-skill row alongside
the existing two with the same focus/Enter toggle semantics and
workspace-scoped persistence (memory.enableAutoSkill).
Default-value updates are kept consistent across all three sources of
truth (settings schema, CLI loader, core Config), and the generated
vscode settings.schema.json is regenerated to match.
* test(cli): add getAutoSkillEnabled to MemoryDialog test mock
The new Auto-skill toggle row reads config.getAutoSkillEnabled() at
render time; without it on the mocked config the component throws and
the existing list-navigation tests assert against an empty frame.
* fix(cli): guard managed auto-dream in bare mode, sync tests and docs
- enableManagedAutoDream in loadCliConfig was missing the bareMode guard
that its two siblings already had; once the default flipped to true,
this caused a raw-field inconsistency in bare-mode sessions (the
getter still returned false via its own !getBareMode() guard, but the
Config.enableManagedAutoDream field itself was now true).
- docs/users/configuration/settings.md still listed
enableManagedAutoDream's default as false, and was missing the new
enableAutoSkill row entirely. Both fixed.
- MemoryDialog.test.tsx now covers the autoSkill row render, the new
focus chain (list ↑ autoSkill ↑ autoDream and back down), and the
Enter-toggle path that writes memory.enableAutoSkill to workspace
settings.
- config.test.ts gains a non-bare default test asserting all three
getManaged*Enabled() / getAutoSkillEnabled() return true, and the
bare-mode test now asserts auto-dream/auto-skill also resolve to
false in bare mode.
* fix(permissions): make command substitution ask, not deny (#4093)
`resolveDefaultPermission` hard-denied any shell command containing
$(), backticks, <(), or >(). Two problems:
1. The deny couldn't be overridden by YOLO mode — YOLO sees the
result only as `'ask'` or `'default'`, never `'deny'`.
2. It fired inconsistently: only when `hasRelevantRules()` happened
to be true. A compound command like
`echo hello && python3 -c "print($(echo hello))"` was hard-denied
because `echo hello` matched an unrelated allow rule and made
`hasRelevantRules()` true, while the same `python3` sub-command
in isolation kept its L3 `'ask'` (PM skipped) and was approvable.
Same substitution, opposite verdict — purely a function of which
unrelated rules were loaded.
This is the surviving half of a two-step migration. `fb7e30ad3
"fix(shell): remove command substitution deny check from
getDefaultPermission"` removed the equivalent L3 deny but missed
the L4 mirror — this commit completes that cleanup.
What changes:
- `resolveDefaultPermission` no longer special-cases substitution; the
AST read-only check already marks substitution-bearing commands as
non-read-only, so they fall through to `'ask'` with everything else.
- Return type narrowed from `'allow' | 'ask' | 'deny'` to `'allow' | 'ask'`.
- `ToolExecuteConfirmationDetails` gains an optional `warnings?: string[]`
field. `ShellToolInvocation.getConfirmationDetails` populates it with a
"Contains command substitution …" line when substitution is detected
on either the original or stripped command. The CLI confirmation
dialog renders these as ⚠-prefixed lines in the warning color,
mirroring Claude Code's UX (see issue thread for reference).
Out of scope: `checkCommandPermissions` in shell-utils.ts still hard-
denies substitution. That path is exercised by user-authored `!{...}`
shell injections in slash commands (shellProcessor.ts) and is a
prompt-injection defense, not the agent-tool path #4093 describes.
Regression coverage:
- permission-manager.test.ts: new `command substitution (issue #4093)`
describe with 5 cases — standalone $(), the exact compound from the
issue, backticks, <(), and deny-rule precedence.
- shell.test.ts: new `command substitution warning (issue #4093)`
describe with 4 cases — $()/backticks/<() each surface a warning,
plain commands do not.
- ToolConfirmationMessage.test.tsx: 2 new render tests.
Fixes#4093
* fix(cli): reserve warnings height in exec confirmation layout (#4386 review)
Addresses two round-1 findings from Copilot on PR #4386:
1. ToolConfirmationMessage: the warnings block was rendered as a sibling
*below* the MaxSizedBox-capped command body (with marginTop=1), but
the height budget computed by availableBodyContentHeight() — and the
compactMode cap of COMPACT_BODY_MAX_LINES — didn't account for the
extra lines. On small terminals + compactMode this could push the
options list off-screen. Reserve the warnings footprint
(`warningsCount + 1` for marginTop) up-front so the overall exec
block respects availableTerminalHeight / COMPACT_BODY_MAX_LINES.
Added a regression test (`keeps options visible alongside the
warning on a tight compactMode layout`) that renders a substitution
command with `availableTerminalHeight=10` + `compactMode=true` and
asserts both the warning text and all three compactMode option
labels remain on-screen.
2. permission-manager.test.ts: the new `command substitution (issue
#4093)` describe had a misleading inline comment that conflated the
issue's original scenario (`echo hello && python3 ...` + `Bash(echo *)`)
with the test fixture (`git status && python3 ...` + `Bash(git *)`).
Rewrote it to describe what the test actually does (`git status`
matches `Bash(git *)`, making hasRelevantRules() true; the python3
sub-command then resolves via resolveDefaultPermission).
* fix(permissions): align monitor + propagate warnings to ACP/non-interactive (#4386 review)
Addresses round-2 review findings from wenshao on PR #4386. Four
related findings, all about sibling drift from the original #4093 fix:
either the same hard-deny-on-substitution pattern in a sibling tool, or
downstream consumers that don't propagate the new warnings field.
1. monitor.ts: `MonitorToolInvocation.getDefaultPermission()` had the
identical `detectCommandSubstitution → 'deny'` pattern that the
original PR removed from `PermissionManager.resolveDefaultPermission`
— sibling drift the original audit missed. Same UX problems apply
(YOLO unbypassable, opaque deny). Removed the deny branch, added
the substitution warning in `getConfirmationDetails` (mirroring
ShellToolInvocation), updated the 5 existing tests that asserted
the old 'deny' to assert 'ask', and added a confirmation-warning
test for the issue #4093 mirror case. Monitor still maintains its
separate permission boundary (Monitor(...) rules don't share with
Bash(...) — documented in the unchanged comment at the top of
getConfirmationDetails); only the substitution-deny half is removed.
2. ACP `buildPermissionRequestContent` (permissionUtils.ts): had no
`exec` branch, so the new `warnings` field never reached ACP
clients (IDE integrations etc.). Added an `exec` branch that emits
one `⚠ <warning>` text content per warning, alongside the existing
`edit` (diff) and `plan` (text) branches. Two regression tests
added: warning present → ⚠ content entry; no warnings → empty.
3. Non-interactive `permissionController.buildPermissionSuggestions`:
the `case 'exec'` description string didn't read `warnings`, so
daemon/API consumers that delegate the approval decision back to
a user lost the substitution context. Appended warnings as a
parenthesized `⚠ ...` suffix to the description string. (No test
file exists for this controller — change is small and verifiable
by inspection; adding test scaffolding is out of scope for this
round.)
4. Test coverage: the `command substitution (issue #4093)` describe
blocks in `shell.test.ts` and `permission-manager.test.ts` covered
`$()`, backticks, and `<()` but not `>()` — even though
`detectCommandSubstitution` and the warning text both list it.
Added a `>()` case to each block to close the regression gap.
* fix(cli): wrap-aware warnings reservation + load-bearing regression test (#4386 self-review)
Two related self-review findings from my pre-push review on PR #4386:
1. SR-1: the round-1 layout regression test
(`keeps options visible alongside the warning on a tight compactMode
layout`) used a single-line command at `contentWidth=80`. `MaxSizedBox`
clamps to `min(content_lines, maxHeight)`, so a 1-line command
renders as 1 line regardless of whether `bodyContentHeight -=
warningsHeight` is applied — the test would still pass if that line
were silently removed. Replaced with a 4-line command and an
assertion on the `... N lines hidden ...` truncation footer that
MaxSizedBox emits *only* when its cap is actually active. Confirmed
RED → fix → GREEN: the new test fails when the warnings
subtraction is removed and passes when restored.
2. SR-2: the warnings-height reservation reserved `warningsCount + 1`
lines (one per warning + one marginTop separator). On narrow
terminals the warning text wraps across multiple visual rows, so
the reservation under-counts. Replace the per-warning `+1` with
`ceil((warning.length + 2) / max(contentWidth, 1))` to account for
each warning's actual rendered row count. The `+ 2` accounts for
the `⚠ ` prefix; the `max(...,1)` keeps the math defined for
pathological inputs. Independently flagged by Codex during
self-review as `[P3] Account for wrapped warning lines`.
* fix(core): log substitution audit trail on YOLO/auto bypass (#4386 review)
Round-3 review caught a real observability gap: when `needsConfirmation`
returns false (YOLO mode at line 1791, or auto-approve at line 1740),
the scheduler skips `getConfirmationDetails()` entirely and the
substitution warning generated there never reaches the user. Pre-#4093
this didn't matter because substitution hard-denied before reaching
the bypass; post-#4093 it executes silently with no audit trail.
YOLO/auto by design execute arbitrary LLM-emitted commands without
warnings — bypassing the substitution warning isn't a new
vulnerability vs. e.g. an unwarned `rm -rf /tmp/x`. But operators
troubleshooting a prompt-injection incident need an audit trail.
Adds a module-level `maybeLogSubstitutionBypass()` helper that emits a
`debugLogger.warn` only when (a) the canonical tool name is in the
shell-like audit set (RUN_SHELL_COMMAND / MONITOR) AND (b) the command
arg contains substitution. Called from both bypass branches with a
`yolo` / `auto-approve` discriminator so the audit log identifies
which path bypassed.
DEBUG-only — silent at default verbosity, no noise for typical YOLO
users; forensic signal lives in `DEBUG=*` traces. No separate test
added: `debugLogger` is module-private (created at the top of
coreToolScheduler.ts), and mocking the createDebugLogger module is
disproportionate complexity for a DEBUG-only audit signal whose
logic is a 7-line guard chain.
* refactor(core): extract substitution warning constant + helper, plus permissionController test (#4386 review)
Round-3 review cleanup, bundling 4 small related findings:
1. **Extract `COMMAND_SUBSTITUTION_WARNING` constant** (`shell-utils.ts`).
The user-facing warning string was hardcoded identically in two
source files (`shell.ts`, `monitor.ts`); tests assert via regex so
the constant doesn't break them. Co-located with
`detectCommandSubstitution` since they share the same domain.
2. **Extract `buildShellExecWarnings()` helper** (`shell-utils.ts`).
The 6-line warnings-building pattern was duplicated between
`ShellToolInvocation.getConfirmationDetails` and
`MonitorToolInvocation.getConfirmationDetails` — same two-input
substitution check (stripped + raw command), same literal push,
same undefined-on-empty contract. Both call sites collapse to a
one-liner. This is a mechanism lift, not a boilerplate lift —
the helper captures non-trivial behavior. The
`checkCommandPermissions` path in `shell-utils.ts` intentionally
keeps its own deny-reason string (different code path, different
threat model — prompt-injection defense for `!{…}` slash commands).
3. **Drop unnecessary non-null assertion** in
`ToolConfirmationMessage.tsx`. Line 268 already defines
`const warnings = executionProps.warnings ?? []`; the JSX block was
using `executionProps.warnings!.map(...)` which (a) reaches past
the null-safe local and (b) misleads readers about whether the
field is actually guaranteed-defined.
4. **Add `permissionController.test.ts`** covering the
`buildPermissionSuggestions` exec branch added in commit 7bb420562.
Seven cases: warning-present (single + multiple), non-string
filtering, warning-absent (missing key + empty array + malformed
non-array), and the null-payload return for invalid input. No test
file existed for this controller before; the new file establishes
the pattern for the four sibling controllers, but stays scoped to
only the method under review.
* fix(core): close AST substitution gaps and log AST parser failures (#4386 R4)
Round-4 critical findings from wenshao:
1. **AST substitution blind spots in non-`command` node types** —
`evaluateStatementReadOnly` (shellAstParser.ts) only checked
`containsCommandSubstitutionAST` inside the `command` node branch.
Substitution living in OTHER node types slipped through as
read-only, causing `resolveDefaultPermission` to return `'allow'`
and `coreToolScheduler` to auto-approve silently. Verified blind
spots (tests added):
- `variable_assignment` / `variable_assignments`:
`FOO=$(curl evil)` and `FOO=$(cat /etc/shadow) ls` were read-only
- Backtick form: `FOO=\`cat /etc/shadow\`` was read-only
The pre-PR #4386 regex check in `resolveDefaultPermission` was a
safety net masking these AST gaps; removing it without patching
the AST was a real security regression.
Fix: hoist the `containsCommandSubstitutionAST` guard to the top
of `evaluateStatementReadOnly` so every node type inherits the
check in one place. Net behavior: substitution anywhere in the
statement subtree marks the whole statement as non-read-only,
matching the contract the function's docstring (and the comment
in `resolveDefaultPermission`) already claimed.
Tests follow Step 7.1 RED → fix → GREEN ordering: confirmed each
of the 3 affected shapes was misclassified as read-only before
the AST hoist, and all 4 cases pass after.
2. **Silent catch in `resolveDefaultPermission`** — the `try/catch`
around `isShellCommandReadOnlyAST` swallowed parser exceptions
without logging. With the regex safety net gone, the AST check is
now the sole gatekeeper, so a parser regression would silently
route every command to 'ask' with no trace. Added the same
`debugLogger.warn` already used by the equivalent catches in
`shell.ts` (line 1394) and `monitor.ts` (line 192).
3. **Misleading comment** in `resolveDefaultPermission` already
asserted "the AST walker marks any node with a substitution
expansion as non-read-only" — true post-fix, but false pre-fix.
Updated to reference the load-bearing top-level guard in
`shellAstParser.ts` so the claim is verifiable from one place.
Closes wenshao R4 findings: AST blind spots (`permission-manager.ts:417`
+ `shellAstParser.ts:884`), silent catch (`permission-manager.ts:415`).
* fix(core): extend substitution audit log + dual-check stripped form (#4386 R4)
Round-4 audit-log consistency fixes from wenshao:
1. **Dual-check stripped form in audit predicate** — round 3's
`maybeLogSubstitutionBypass` only ran `detectCommandSubstitution`
on the raw command, but `buildShellExecWarnings` (the
confirmation-dialog warning helper extracted in round 3) checks
BOTH the raw and the `stripShellWrapper`-stripped forms. For
wrappers like `bash -c 'echo $(cat secret)'` the `$(` sits inside
the outer single quotes, so raw-check returns false but the inner
shell still expands the substitution. Result: dialog showed the
warning, audit log silently dropped it — exactly the wrapper
pattern an exfiltration attack would use. Refactored the helper
to extract a pure predicate `shouldAuditSubstitutionBypass` that
does the dual-check, exported for unit testing.
2. **JSDoc correction** — round 3's JSDoc claimed "DEBUG-level log
here so the signal exists when `DEBUG=*` is set". Both clauses
were wrong: the call uses `debugLogger.warn` (WARN level), and
`debugLogger` is controlled by `QWEN_DEBUG_LOG_FILE` (active by
default) rather than the `DEBUG=*` convention of the `debug` npm
package. Rewrote the doc to match the real semantics.
3. **Audit log on three more auto-approve bypass paths** — round 3
only covered the YOLO and auto-mode-`approved` bypasses, missing
three other paths that auto-approve without invoking
`getConfirmationDetails()`:
- PM `'allow'` fast path (coreToolScheduler.ts:1664) — fires
when an allow rule matches a substitution-bearing command
(e.g. `allow Bash(python3 *)` + `python3 -c "$(...)"`).
- permission-request hook `shouldAllow` (line ~1896) — fires
when an external hook grants permission directly.
- `autoApproveCompatiblePendingTools` sibling-tool ProceedAlways
(line ~3300) — fires when one tool's user-issued ProceedAlways
outcome rolls up to a sister tool. Uses `canonicalToolName`
to normalise the legacy name in the audit log.
New `SubstitutionBypassReason` discriminator union surfaces the
bypass path in the log so operators can distinguish them.
4. **Unit test coverage** — added a `shouldAuditSubstitutionBypass`
describe block to `coreToolScheduler.test.ts` covering all 8
branches: non-shell tool, missing args, non-string command,
absent substitution, direct substitution (shell + monitor), the
load-bearing wrapper case (proves the dual-check works), backtick
substitution, and env-prefix substitution.
Out of scope: reviewer also suggested forcing `'ask'` whenever
substitution is detected with a matching allow rule. Declined —
would partially re-introduce #4093 (substitution can't be allowed
via rules even with explicit user intent), and overrides the
allow-rule "trust this pattern" semantics. The audit-log extension
above gives operators the visibility they asked for without
overriding user-configured permission policy.
Closes wenshao R4 findings: dual-check (cids 3293074365, 3293075616),
JSDoc level/envvar (cids 3293074371, 3293075619), audit on PM-allow
(cid 3293078740 — partial), audit on hook + sibling-auto (rid 4351040390
non-diff), and test coverage for the predicate (cid 3293078758 — partial).
* test(core): cover env-prefix substitution + buildShellExecWarnings dual-check (#4386 R4)
Round-4 test-coverage findings from wenshao:
1. **env-prefix integration test in `shell.test.ts`** (cid 3293075622) —
the `command substitution warning (issue #4093)` describe block in
`shell.test.ts` covered `$()`, backticks, `<()`, `>()`, and the
no-warning case, but had no test for the shape where
`stripShellWrapper` strips the env-prefix + `bash -c` wrapper to
yield a substitution-free inner command (`echo ok`) while the raw
command has substitution in the env assignment
(`FOO=$(cat secret.txt) bash -c 'echo ok'`). This is the exact
shape that exercises the `|| detectCommandSubstitution(rawCommand)`
branch of `buildShellExecWarnings` via integration through
`getConfirmationDetails`. Without this test, removing the `||`
clause wouldn't regress any case here.
2. **`buildShellExecWarnings` unit tests in `shell-utils.test.ts`**
(cid 3293078758 second half) — round 3 extracted
`buildShellExecWarnings` as an exported helper but added no direct
unit test. Added a 5-case describe block covering: no substitution,
stripped-form substitution, the env-prefix dual-check case (with
a sanity-check that the stripped form actually lacks `$(` to make
the dual-check load-bearing), backticks, and process substitution.
These complement the integration tests in shell.test.ts /
monitor.test.ts which exercise the helper through the tool
confirmation paths.
Closes wenshao R4 findings: env-prefix integration test
(cid 3293075622), `buildShellExecWarnings` direct unit coverage
(cid 3293078758 — second half).
* fix(test): drop duplicate ToolNames import in coreToolScheduler.test (#4386 R4 CI)
Round-4 commit a24485029 added `import { ToolNames }` without checking
the file already had `import { ToolNames, ToolNamesMigration }` at line
35. Vitest's esbuild was permissive about the duplicate (silently used
the latter) so the test file passed locally and `npx tsc --noEmit` on
the package didn't complain either — but CI's `tsc --build` is strict
and errored with TS2300 "Duplicate identifier 'ToolNames'", taking down
Lint + all three test platforms + Coverage in one go (run 26382523711).
Removed the duplicate import. Verified locally via `rm -rf
packages/core/dist && npx tsc --build` (clean) + `npx vitest run`
(171/171 pass).
* fix(core): close env-prefix wrapper substitution bypass at L3 (#4386 R6)
Round-6 review caught a real Critical security regression my R0 +
R4 audits both missed.
**The bug.** `ShellToolInvocation.getDefaultPermission()` calls
`stripShellWrapper(this.params.command)` BEFORE the AST check. For
`FOO=$(curl evil) bash -c 'echo ok'`, `stripShellWrapper` discards the
env-prefix AND unwraps the `bash -c` wrapper, yielding `echo ok` — a
substitution-free residual that the AST classifies as read-only.
Result: L3 returns `'allow'` → coreToolScheduler fast-allow at
line 1664 auto-approves silently with no confirmation dialog and no
user-visible warning.
The R4 top-level AST guard (`evaluateStatementReadOnly` ↳
`containsCommandSubstitutionAST`) only catches substitution that
survives `stripShellWrapper` to enter the parsed tree. The env-prefix
+ wrapper shape gets stripped to nothing visible, so the AST guard is
asked to inspect a clean tree and returns true. The pre-#4386 regex
`detectCommandSubstitution` in `resolveDefaultPermission` was a safety
net masking exactly this gap — R0 removed it without recognising the
strip-before-check pattern.
Probe (vitest harness, real `isShellCommandReadOnlyAST`):
```
{
raw: "FOO=`whoami` bash -c 'ls'",
stripped: "ls",
ast_on_stripped: true, // ← classifies as read-only
ast_on_raw: false // ← R4 guard works on raw
}
```
**The fix — `hasShellSubstitution` single source of truth.**
Extracted dual-check predicate (`detectCommandSubstitution(raw) ||
detectCommandSubstitution(stripShellWrapper(raw))`) into
`shell-utils.ts hasShellSubstitution(rawCommand)`. The raw arm catches
the env-prefix-wrapper shape; the stripped arm catches the inside-
single-quoted-wrapper-body shape that R3 already documented. Single
predicate keeps detection semantics in lockstep across all surfaces.
Gates added at:
- `ShellToolInvocation.getDefaultPermission` (shell.ts:1384) — primary
fix for the cited bug
- `shellReadOnlyChecker.ts evaluateShellSegment` (line 298) — regex
fallback path has the same strip-before-check pattern; only hit when
WASM parser fails, but same root cause
- `MonitorToolInvocation.getDefaultPermission` (monitor.ts:174) —
belt-and-suspenders; `normalizeMonitorShellCommand`'s `safetyCommand`
preserves env-prefix tokens so the AST already sees substitution
there, but the gate parallels shell.ts in case
`normalizeMonitorShellCommand`'s env-preservation ever regresses
- `PermissionManager.resolveDefaultPermission` (permission-manager.ts:413)
— belt-and-suspenders; the raw command reaches the AST already, but
the reviewer-requested gate makes the intent grep-discoverable
Refactor (Finding C, cid 3298521063): `buildShellExecWarnings` and
`shouldAuditSubstitutionBypass` both now delegate to
`hasShellSubstitution`, addressing the reviewer's concern that the
audit-log path and the UI-warning path were maintaining parallel
dual-check implementations that could silently diverge.
**Test-first per skill Step 7.1.** Two new tests in `shell.test.ts`
under `getDefaultPermission and getConfirmationDetails`:
- `asks (not allow) for env-prefix substitution inside a bash wrapper`
- `asks for backtick env-prefix substitution inside a bash wrapper`
Both confirmed RED pre-fix (`expected "ask" got "allow"`); GREEN
post-fix. Wider sweep (1262 tests across 19 files in permissions,
tools, utils, core, cli) all green; tsc --build clean (matching CI's
strict build).
Out of scope for this commit (deferred to follow-up #4509):
- R6 Finding B (dead catch blocks in resolveDefaultPermission / shell /
monitor) — appended to #4509
- R6 Finding D (Record<string, unknown> cast in permissionController
exec branch — could use discriminated-union narrow) — appended to #4509
- R6 Finding E (O(N×D) DFS in evaluateStatementReadOnly — could be
hoisted to isShellCommandReadOnlyAST as O(N) root-level check) —
appended to #4509
Closes wenshao R6 findings: env-prefix wrapper bypass (cid 3298521039 —
Critical, fixed) + dual-check DRY (cid 3298521063 — fixed as side
effect of A's refactor).
* revert: remove substitution audit-log infrastructure (#4386 cleanup)
Reverts:
- fd2cf080d "fix(core): log substitution audit trail on YOLO/auto bypass"
- a24485029 "fix(core): extend substitution audit log + dual-check stripped form"
The audit-log infrastructure was originally added in R3 as a self-Codex
suggestion (forensic visibility when YOLO bypasses the substitution
warning) and extended in R4 to PM-allow / hook / sibling-auto paths.
None of this is what issue #4093 asked for — #4093 is purely about
making substitution `'ask'` instead of `'deny'` so YOLO can override
and the behavior is consistent across rule configurations. The audit
log is debug-only forensic polish on a UX warning, not part of the
permission-decision fix.
Each subsequent review round (R4/R5/R6/R7) then surfaced sibling-drift
findings on this infrastructure — PM-allow audit, hook audit, ACP
audit-log parity, callId enrichment, dual-check asymmetry, integration
tests — all of which were tracking the same out-of-scope addition.
Removing the infrastructure removes the surface entirely.
`hasShellSubstitution` (added in 5a5cfb4fc) is kept — it's still used
by `shell.ts` L3 substitution gate and `buildShellExecWarnings`, both
of which ARE in scope for #4093.
* cleanup: remove out-of-scope additions from R2/R3/R6 review (#4386)
Surgical reverts that complement a5d9f087e (audit-log infrastructure
revert). These changes were accepted in earlier review rounds but were
out of scope for issue #4093 — a bug-fix PR whose stated goal is to
make command substitution `'ask'` instead of `'deny'` so YOLO can
override and the behavior is consistent across rule configurations.
Anything beyond that fix is unrelated to the bug and not this PR's
responsibility.
Removed:
1. **ACP `permissionUtils.ts`: `exec` branch in
`buildPermissionRequestContent`** (R2, commit 7bb420562). The new
`warnings` field propagation to ACP clients (VS Code extension,
daemon) was UX polish on a different surface. Not what #4093 asked
for. Plus the two regression tests in `permissionUtils.test.ts`.
2. **Non-interactive `permissionController.ts`: `case 'exec'`
warning-suffix on the suggestion description** (R2, commit 7bb420562).
Same pattern as above — warning propagation to daemon/API consumers
on a non-primary surface. Plus the entire
`buildPermissionSuggestions — exec warnings` describe block I added
to `permissionController.test.ts` (R3, commit baa1e9f78). Main's
#4491 timeout tests (which merged in via 6342d2810) are preserved.
3. **`monitor.ts` belt-and-suspenders `hasShellSubstitution` gate**
(R6, commit 5a5cfb4fc). I added this with an explicit "if
normalizeMonitorShellCommand's env-preservation ever regresses"
justification — i.e. defense-in-depth on a non-existent bug. Not
what #4093 asked for.
4. **`permission-manager.ts` belt-and-suspenders `hasShellSubstitution`
gate at `resolveDefaultPermission`** (R6, commit 5a5cfb4fc). Same
pattern — reviewer-requested gate on top of a code path the R4 AST
guard already covered. Not what #4093 asked for.
What's kept (in scope for #4093):
- L4 `deny → ask` in `resolveDefaultPermission` (the actual fix)
- `warnings?: string[]` field on `ToolExecuteConfirmationDetails` +
CLI rendering — #4093 explicitly asks for a user-visible reason
- `ShellToolInvocation.getDefaultPermission` env-prefix wrapper gate
(R6, 5a5cfb4fc) — closes a real `'allow'` regression on substitution
- `shellReadOnlyChecker.ts` regex-fallback raw-check (R6, 5a5cfb4fc)
— same root-cause bug on the WASM-fallback path
- AST top-level substitution guard in `evaluateStatementReadOnly`
(R4, 42debd13d) — closes real AST blind spots
- `hasShellSubstitution`, `buildShellExecWarnings`,
`COMMAND_SUBSTITUTION_WARNING` helpers — still used by the above
- Monitor tool's `'deny' → 'ask'` alignment for substitution (R2,
7bb420562) — same root-cause as the main fix
* feat(worktree): Phase D — startup --worktree flag + symlinkDirectories + PR refs
Three cross-cutting capabilities on top of the Phase A-C worktree
foundation (PRs #4073, #4174).
D-1: --worktree [name] CLI flag creates a worktree (or re-attaches to
one that already exists) before any model turn runs. Supports bare,
plain-slug, `=`, and PR-reference forms; --worktree + --acp rejected
with a clear error; --worktree + --resume overrides the resumed
session's saved sidecar and emits a stderr line.
D-2: worktree.symlinkDirectories: string[] settings key opts into
symlinking main-repo directories (e.g. node_modules) into every
newly-created general-purpose worktree. Applies to all three creation
paths: --worktree flag, EnterWorktreeTool, AgentTool isolation. Path
traversal, absolute paths, and existing destinations all guarded;
missing source dirs and EEXIST silently skipped (fail-open).
D-3: --worktree=#<N> / --worktree <github-url> resolves a PR number,
runs `git fetch origin pull/<N>/head` (30s timeout, no `gh` CLI
dependency, LANG=C for stable error-taxonomy matching), and creates
the worktree off FETCH_HEAD. URL regex tolerates /files, /commits,
/checks sub-paths so users can paste any GitHub PR URL.
Phase 6 verification fixes also included:
- Re-attach to an existing worktree instead of failing with "Worktree
already exists" — the common `qwen --resume <sid> --worktree foo`
workflow now succeeds. The session ownership marker is preserved on
re-attach so cross-session exit_worktree action="remove" still fails
for non-owners.
- Normalize path-taking argv fields (mcpConfig, jsonSchema @<path>,
openaiLoggingDir, jsonFile, inputFile, telemetryOutfile,
includeDirectories) to absolute paths against the launch cwd BEFORE
the worktree chdir. Otherwise downstream fs.existsSync('./mcp.json')
resolves into the worktree, where the file doesn't exist.
Phase 7 code-review fixes:
- buildStartupWorktreeNotice differentiates "Active worktree" (fresh
create) from "Re-attached to worktree" (re-attach path).
- Notice survives sidecar persist failure: set before the try block,
refreshed inside with override addendum if persist succeeded.
- getRegisteredWorktreeBranch verifies the candidate path's git
common-dir matches the source repo's — rejects sibling `git init`
directories that happen to be on a worktree-<slug> branch.
Three-mode parity for the startup notice: TUI consumes via
AppContainer effect, headless prepends a <system-reminder> + emits a
worktree_started JSON event. ACP path is mutually exclusive with
--worktree (ACP hosts supply per-session cwd separately).
Tests (66 + 15 new):
- 15 cli/src/startup/worktreeStartup.test.ts (slug forms, PR fetch
against local fake remote, re-attach happy + wrong-branch guard)
- 8 core/src/services/gitWorktreeService.test.ts (parsePRReference:
#N, URLs, malformed, traversal, leading zeros, non-string)
- 10 core/src/services/gitWorktreeService.symlinks.integ.test.ts
(symlink loop + fetchPullRequestRef error taxonomy)
Known limitations (documented in docs/users/features/worktree.md):
- Cross-slug --resume <sid> --worktree <different-new-slug> is
unsupported by design (sessions are bound to projectHash(cwd));
future Config refactor anchoring storage at repo root would lift this.
- Mid-session enter_worktree still does NOT switch cwd/targetDir
(Phase A's simplification); only the startup --worktree flag does.
- yargs ambiguity: `qwen --worktree "say hi"` consumes the prompt as
the slug. Quick Start shows the `=` form and reordering workarounds.
Docs:
- docs/users/features/worktree.md (new): Quick Start with --worktree
flag, CLI Reference table for all four input forms + error codes,
settings table, Limitations.
- docs/design/worktree.md: Phase D section expanded into D-1/D-2/D-3
with open questions resolved; capability table updated.
- docs/e2e-tests/worktree-phase-d.md (new): full E2E plan with Phase 4
dry-run baseline + Phase 6 post-impl reproduction tables.
Refs #4056
* refactor(worktree): apply self-review feedback on Phase D
Self-review pass over the Phase D commit (2636f59273) catching one real
typecheck regression plus a batch of small quality + efficiency
improvements. No user-visible behavior change beyond fixing the build.
Build fix:
- worktreeStartup.ts imports — pre-commit prettier had reorganized
`writeWorktreeSession` and `readWorktreeSession` under an
`import type { ... }` block, erasing them at compile time
(verbatimModuleSyntax). `tsc --noEmit` was failing with TS1361.
Bundle path still worked (esbuild is lenient) so this only surfaced
when running typecheck.
Startup-path efficiency (~10-25 ms saved per --worktree invocation on
macOS; more on Windows):
- Drop redundant `isGitRepository()` probe — `getRepoTopLevel()`
returns null on non-git paths and covers both gates in one
subprocess.
- Run `getCurrentBranch()` + `getCurrentCommitHash()` in parallel via
Promise.all (independent calls).
- Combine the two `git rev-parse` probes inside
`getRegisteredWorktreeBranch` into a single multi-arg call, and run
it in parallel with the source-repo common-dir lookup. Saves one
fork+exec on the re-attach path.
Quality:
- Extract `withReminder()` local helper in nonInteractiveCli.ts so the
startup-notice and resume-restore branches share the system-reminder
wrapping.
- Log `readWorktreeSession` failures in `persistStartupWorktreeSidecar`
with the sidecar path so operators can recover the previous slug
from a backup. Silent swallow was making "where did my worktree
binding go?" undebuggable.
- Drop the dead `Config.getWorktreeSettings()` accessor (only
`getWorktreeSymlinkDirectories()` has callers); keep the underlying
`WorktreeSettings` interface for future fields.
- Document the `pendingStartupWorktreeNotice` invariant: at most one
consumer per process; ACP path is gated out earlier so only TUI XOR
headless reads it.
- Add a maintainer note in the gemini.tsx path-normalization block:
the argv path-field allowlist is hand-maintained, register new
path-bearing flags there or `--worktree` silently breaks for them.
- Drop `Phase 6 fix (G1)/(G2)` parenthetical labels from inline
comments — internal review-cycle identifiers that decay to noise
post-merge. Substantive prose retained.
Tests: cli 15/15 (unchanged) + core 66/66 (unchanged); bundle smoke
verified fresh / re-attach / invalid slug / non-git cases.
Findings deliberately left for follow-up:
- Larger refactor extracting a shared `provisionUserWorktree` helper
for the EnterWorktreeTool / startup overlap (~80% duplicate).
- Splitting the re-attach branch out of `setupStartupWorktree` into
its own function.
- `isPathWithinRoot` / `isInsideManagedWorktree` shared utils.
- `symlinkConfiguredDirectories` loop concurrency (saves 5-15 ms on a
cold path that runs only when symlinkDirectories is configured).
* docs(worktree): refresh stale docstring in worktreeStartup
Top-of-file docstring still said `{adj}-{noun}-{4hex}` (actual format
is 6 hex chars) and described the PR form as "detected and rejected
with a clear 'coming in D-3' message" — but D-3 shipped in the same
PR. Tighten to reflect what the code actually does.
* fix(worktree): address findings from dual-reviewer self-check
Two real bugs surfaced by an independent dual-reviewer pass (Claude +
Codex) on the Phase D commits. Both correctness-affecting; both
escaped the earlier internal reviews.
P0 — re-attach captured the wrong baseline for the exit dialog
(Codex):
setupStartupWorktree captured `originalHeadCommit` from the launch
cwd (main checkout) before any chdir. On the re-attach path the
WorktreeExitDialog later runs `git rev-list <originalHeadCommit>..HEAD`
inside the worktree to count "new commits this session". With the
main-checkout baseline this counted every commit ever made in the
kept worktree as new work from the current session — misleading the
keep/remove prompt. Re-capture HEAD from inside the worktree after
chdir so the count means what the dialog text says it means.
P0 — getRegisteredWorktreeBranch mis-identified plain directories as
registered worktrees (Claude):
A plain directory at `<repo>/.qwen/worktrees/<slug>/` (e.g. a stale
artifact from a previous tool) had no `.git` file of its own, so
`git rev-parse --git-common-dir` walked up to the outer repo and
returned the outer common-dir — matching the source repo's
common-dir check and impersonating a registered worktree. If the
outer repo happened to be on `worktree-<slug>`, setupStartupWorktree
would silently chdir into the plain directory and treat it as
attached; subsequent `exit_worktree action="remove"` would then
delete a directory that was never registered.
Fix: also probe `--show-toplevel` and require it to equal the
candidate path (canonicalised via `realpath` so macOS /var → /private/var
doesn't break the equality check). A plain dir under the main repo
gets the outer repo's toplevel and is correctly rejected.
Smaller polish from the same review:
- Normalize the literal string `'HEAD'` returned by `getCurrentBranch`
on detached HEAD to `undefined`, so the `baseRef` handed to
`git worktree add -b … HEAD` does not implicitly anchor against
the loose commit when the launch cwd is detached.
- `symlinkConfiguredDirectories`: blocklist `.git` (any nested
ancestor) and `.qwen/worktrees` (any nested ancestor). Linking
`.git` would silently break commits inside the worktree; linking
`.qwen/worktrees` would create a worktrees-inside-worktrees loop
that confuses the startup sweep.
- `WorktreeSettings.symlinkDirectories` typed `readonly string[]` to
match the `createUserWorktree(options.symlinkDirectories)` contract
and the immutable-config convention elsewhere. `Config.getWorktreeSymlinkDirectories()`
return type updated to match.
Docs:
- design/worktree.md precedence table rewritten. The previous
`--worktree` 赢 row was unreachable in practice (sessions are bound
to `projectHash(cwd)`, and the chdir happens before session lookup).
New table reflects what actually happens for each combination of
`--resume` × `--worktree`, including the documented
cross-projectHash limitation. The `persistStartupWorktreeSidecar`
override branch is now annotated as dead-on-the-current-architecture
but kept so a future Config refactor (anchor storage at repo root)
picks it up for free.
Tests: cli 15/15 + core 66/66 unchanged. Bundle smoke confirms both
P0 fixes end-to-end (re-attach captures worktree HEAD = run-1 tip,
plain-dir attempt errors out without clobbering existing content).
* refactor(worktree): consolidate probe + name detached-HEAD sentinel
Second /simplify pass on the dual-reviewer fixes. Three convergent
findings; net effect is one fewer subprocess on the re-attach path
and clearer intent on string handling / blocklist guards.
Efficiency + quality:
- Fold the worktree HEAD SHA into `getRegisteredWorktreeBranch`'s
combined rev-parse. The probe already requests common-dir,
toplevel, and abbrev-ref HEAD in a single subprocess; adding a
leading `HEAD` positional (which must come BEFORE `--abbrev-ref` so
the flag doesn't apply to it) returns the SHA on its own line.
Return type widened to `{ branch, headCommit } | null`. Removes
the second `GitWorktreeService` instantiation and `getCurrentCommitHash`
call that `setupStartupWorktree`'s re-attach branch used to do.
Quality:
- Hoist `'HEAD'` to a module-level `DETACHED_HEAD` constant in
`worktreeStartup.ts`. Three uses, two meanings (input filter when
normalizing `getCurrentBranch` output, fallback metadata for the
sidecar's `originalBranch` field on detached state). Naming the
sentinel makes intent self-documenting and pre-empts the "why is
the value we just stripped re-appearing as a fallback?" reader stall
flagged by the round-3 quality review.
Reuse + quality:
- `symlinkConfiguredDirectories`: replace two hand-rolled containment
checks (`startsWith(prefix + sep)` for `.qwen/worktrees`; `path.relative(...).split(sep)[0]`
for `.git`) with `isWithinRoot` from `utils/fileUtils.ts`, which is
already imported in this file. Replace the hardcoded
`path.join(repoRootAbs, '.qwen', 'worktrees')` with `this.getUserWorktreesDir()`
so the layout lives in one place (the exported `WORKTREES_DIR`
constant). Split the misleading `sourceAbs === repoRootAbs` clause
out of the `.git` branch into its own dedicated "empty / repo-root
path" rejection with a clearer warn message.
Tests: cli 15/15 + core 66/66 unchanged. Bundle smoke verified the
folded probe still captures the worktree's HEAD on re-attach (not
the launch-cwd HEAD).
Skipped from this review pass:
- Moving `'HEAD'` normalization into `GitWorktreeService.getCurrentBranch()`
itself — would ripple through `enter-worktree.ts` and `agent.ts`
callers that hand the result verbatim to `git worktree add -b ...`.
Out of scope for a polish pass; the local const is enough.
* fix(worktree): broaden symlink blocklist from .qwen/worktrees to all of .qwen
Caught by a second pr-tracker dual-reviewer pass (Codex). The previous
guard at `symlinkConfiguredDirectories` only refused paths inside
`<repoRoot>/.qwen/worktrees/` — `.qwen` itself (the parent) sailed
through because `isWithinRoot` is a strict descendant check. A user
setting `symlinkDirectories: ['.qwen']` would therefore symlink the
entire CLI metadata tree into the new worktree, recursively pulling
in `.qwen/worktrees` and recreating the loop the guard was meant to
prevent. Other `.qwen/*` subtrees (`projects`, `tmp`, …) are CLI
state with no legitimate cross-worktree sharing use case either.
Fix: broaden the guard to reject the whole `<repoRoot>/.qwen` tree.
Both `.qwen` itself and any descendant fail closed.
Also synced the user-facing settings schema description (the in-IDE
help text and the published JSON schema) so it mentions the `.git`
and `.qwen` rejection rules. The `WorktreeSettings` interface JSDoc
already mentioned them; the schema description had not been updated.
Tests: cli 15/15 + core 66/66 unchanged. Smoke confirms `--worktree foo`
with `symlinkDirectories: ['.qwen']` configured leaves the worktree
free of any `.qwen` symlink (only the legitimate per-worktree
`.qwen-session` marker file appears).
* fix(worktree): guard fetchPullRequestRef against CodeQL command-injection alert
CodeQL flagged a "Second order command injection" finding (rule 235) on
the `git fetch origin pull/<N>/head` call in `fetchPullRequestRef`. The
taint analyzer doesn't see the type-narrowing at the function entry
(`Number.isSafeInteger(prNumber) && prNumber > 0 && prNumber <= 1e9`),
so it considers `prNumber` library input that could in principle reach
a `--upload-pack=…`-shaped flag and thereby execute an arbitrary
program. In practice the entry guard already prevents that, but the
alert blocks the CodeQL CI check.
Add `--end-of-options` between `origin` and the refspec — git's
canonical "stop parsing flags" marker (git ≥ 2.24). Tells git
definitively that every subsequent argv element is a positional, not
a flag, which (a) satisfies the analyzer, (b) adds defense-in-depth
against a future regression that might relax the entry guard, and
(c) has zero behavior change for any well-formed PR number.
Verified locally: `git fetch --end-of-options origin pull/<N>/head`
against a local bare-remote with a seeded `refs/pull/42/head` still
fetches the ref correctly; the `--worktree=#42` smoke test reads back
the PR content from the materialized worktree.
Tests: cli 15/15 + core 66/66 unchanged.
* fix(worktree): lexical sanitizer for CodeQL + missing test mock entry
Two fixes from the third CI round on PR #4381:
1. CodeQL re-fires (round 2 of the same finding).
`--end-of-options` is a git-runtime defense, not a lexical sanitizer
that CodeQL's `js/second-order-command-line-injection` taint tracker
recognises. The alert re-fired against the same call after the
previous fix.
Switch to a CodeQL-recognised sanitizer: validate the numeric
component against `/^[1-9][0-9]*$/` immediately at the sink. The
regex digit-only check is one of the documented sanitizer patterns
the rule looks for, and proves at the analyzer level that the
resulting argv element cannot resemble a flag (`--foo`). The entry
guard at the top of the function still establishes the same fact
at runtime; this layer makes the proof visible to static analysis.
Keep `--end-of-options` as a runtime fallback against any future
regression that loosens the entry guard.
2. `nonInteractiveCli.test.ts` mock was missing the new
`consumePendingStartupWorktreeNotice` Config method.
Phase D-1 added the method on `Config` and `nonInteractiveCli`
calls it on every prompt to pick up the one-shot startup-worktree
notice. The test file's `mockConfig` literal was not updated, so
all 19 `runNonInteractive` tests threw
`TypeError: config.consumePendingStartupWorktreeNotice is not a
function` on Ubuntu / macOS CI.
Add a stub returning `null` so the helper short-circuits, matching
the equivalent Phase C stub for `getResumedSessionData`.
Local: cli (worktreeStartup + nonInteractiveCli) 60 passed + 1
skipped; core (gitWorktreeService + symlinks + hooks +
enter-worktree) 66 passed.
* test(worktree): mock getWorktreeSymlinkDirectories in three more test files
Round 4 of the same Phase D-2 mock-drift class. CI surfaced 9 test
failures across three files whose `Config` mocks construct
`EnterWorktreeTool` for setup but lack the new
`getWorktreeSymlinkDirectories` method `createUserWorktree` now
calls:
- enter-worktree.session.integ.test.ts (2 tests)
- exit-worktree.session.integ.test.ts (3 tests) — provisions
worktrees via EnterWorktreeTool before exercising exit paths
- exit-worktree.test.ts (4 tests) — same provisioning pattern via
`provisionWorktree()` and the `makeMockConfig` helper
Add a `getWorktreeSymlinkDirectories: () => []` stub to each so
the symlink loop is a no-op in tests.
`enter-worktree.test.ts` and `agent/agent.test.ts` intentionally
skipped — they mock `GitWorktreeService.createUserWorktree` outright,
so the method call never fires in their code paths. Adding the stub
there would be defensive speculation. If a future test exercises
the real path, it'll surface there too and we'll add it then.
Local: core tools tests now 123 passed (was 9 failed / 114 passed
on CI run 26213122427 against commit 000c9f63).
* fix(worktree): normalize repoRoot path separators + disable autocrlf in tests
Round 5 of CI: Windows-only test failures on the latest HEAD. Two
unrelated Windows-specific bugs, both in / around worktreeStartup.
1. `setupStartupWorktree` stored the raw `getRepoTopLevel()` output
in `context.repoRoot`. git always emits POSIX paths via
`--show-toplevel` (`C:/Users/...`), so on Windows the value was
forward-slash where `fs.realpath` and `path.join` produce
backslash. The sidecar's `originalCwd` field got the
inconsistent format and a downstream `expect(...).toBe(tempRepo)`
in the round-trip test compared `C:/Users/.../tmp/...` against
`C:\Users\.../tmp/...`.
Wrap the value in `path.resolve()` to normalize to the
platform-native separator before storing. Downstream consumers
(`path.join(session.originalCwd, '.qwen', 'worktrees')` in
`restoreWorktreeContext`, `new GitWorktreeService(originalCwd)`
in `AppContainer`) already handle either format, so no migration
concern for older sidecars.
2. `makeTempRepo` in worktreeStartup.test.ts didn't configure
`core.autocrlf=false`. On Windows runners the default is `true`,
so files committed and pushed to the test's fake-remote `pull/<N>/head`
ref get CRLF-converted on the worktree's checkout. The PR-content
assertion `expect(prFile).toBe('from PR 42\n')` then failed with
`'from PR 42\r\n'`.
Add `core.autocrlf=false` + `core.eol=lf` to the temp-repo setup
so test files round-trip byte-for-byte regardless of host platform.
Local mac: cli worktreeStartup 15/15 still pass. Windows verification
deferred to CI.
* fix(worktree): reject '..' segments + use junction on Windows
Two Copilot findings on symlinkConfiguredDirectories (PR #4381 round 3):
1. The settingsSchema description, docs/users/features/worktree.md, and
WorktreeSettings JSDoc all promise that entries containing `..` are
rejected — but the post-resolve isWithinRoot check accepted
`foo/../bar` (resolves to `bar`, inside the repo). Add a literal `..`
segment check before path.resolve so the code matches the contract.
2. On Windows, fs.symlink(..., 'dir') requires
SeCreateSymbolicLinkPrivilege (admin / Developer Mode) and EPERMs on
default consumer installs. Use 'junction' for directory entries on
win32 — junctions are reparse points that achieve the same semantics
without elevation. Keep 'dir' on POSIX and 'file' for non-directory
sources (no junction-equivalent for files; rare path).
Adds an integration test exercising `foo/../bar` to lock in the
syntactic guard; existing absolute-path and traversal tests already
covered the other rejection forms.
* fix(worktree): PR-worktree HEAD-SHA capture + symlink guard tests
Three findings from wenshao round 4 (PR #4381):
1. For --worktree=#42 (PR worktrees), originalHeadCommit was captured
from the parent repo's HEAD via getCurrentCommitHash() — but the
worktree branches off FETCH_HEAD (the PR tip), not main. Downstream,
WorktreeExitDialog's `rev-list <originalHeadCommit>..HEAD` would
count every commit in the fetched PR as "new work this session"
alongside the user's actual commits.
Same root cause covers the FETCH_HEAD TOCTOU window: between
`git fetch origin pull/<N>/head` and `git worktree add ... FETCH_HEAD`,
a concurrent `git fetch` from any other process sharing this repo
could overwrite .git/FETCH_HEAD, causing the worktree to branch off
an unrelated commit.
Fix: add GitWorktreeService.resolveRef(ref) that returns a 40-char
SHA (or null). In setupStartupWorktree, immediately after
fetchPullRequestRef succeeds, resolve FETCH_HEAD to an immutable
SHA; pass that SHA both as the baseRef to createUserWorktree (closes
the TOCTOU) AND as originalHeadCommit in the returned context
(closes the exit-dialog miscount). Fail-close on null resolve.
2. Orphaned JSDoc block at gitWorktreeService.ts:1035-1048 — originally
wrote validateUserWorktreeSlug's docs, stranded above parsePRReference
after that function was inserted between them. Move the block down to
sit immediately above validateUserWorktreeSlug at its current line.
3. `.git` / `.qwen` symlink rejection guards (~20 lines of security-
critical code at gitWorktreeService.ts:1640-1655) had no regression
tests — only absolute paths, `..` traversal, isWithinRoot escapes,
and missing sources were covered. Add two integ tests in
gitWorktreeService.symlinks.integ.test.ts: one asserts `.git/hooks`
is refused, one asserts `.qwen/projects` is refused.
Also extends the existing PR-worktree integration test in
worktreeStartup.test.ts to assert originalHeadCommit equals the
resolved FETCH_HEAD SHA AND does NOT equal the parent repo's main HEAD
— the assertion would fail loudly if the new SHA-capture path were
reverted.
* fix(worktree): realpath check on symlinkDirectories source + dest paths
Security fix from PR #4381 round 7 (wenshao/qwen3.7-max). The lexical
isWithinRoot + .git/.qwen blocklist checks in symlinkConfiguredDirectories
all operated on path.resolve(repoRoot, raw) — a STRING operation that
doesn't follow symlinks. A committed (or out-of-band) symlink at
<repo>/node_modules pointing into .git would pass every gate:
1. path.resolve gives `<repo>/node_modules` (lexical, passes
isWithinRoot against repo root).
2. The .git/.qwen blocklists also see the lexical path — they don't
detect that the realpath chains into .git.
3. fs.stat() follows the symlink and succeeds against .git/.
4. fs.symlink writes `<worktree>/node_modules → <repo>/node_modules`,
which OS-side resolves through to <repo>/.git. Any tool inside the
worktree that writes to node_modules/hooks/post-merge then has RCE
on the next hook-firing git operation.
Fix: after fs.stat succeeds, fs.realpath the source and RE-RUN the three
containment checks against the realpath. Refuse on any escape. Use the
realpath (not the lexical sourceAbs) as the symlink target so the new
link is one-hop canonical rather than preserving the chain.
Also closes the dest-side variant of the same root cause — flagged in
round 4 thread #5 (declined then as overthinking) but now in scope per
the skill's iteration rule (two consecutive rounds raising the same
root-cause class). path.join(worktreePath, raw) is also lexical: if
git worktree add materialized a committed worktree-level symlink (e.g.
HEAD ships tools → /etc), then fs.mkdir / fs.symlink for a nested entry
like "tools/cache" writes OUTSIDE the worktree. Realpath the dest
parent before mkdir and refuse if it escapes the worktree.
New integ test covers both source-side variants (escape-to-git via
out-of-band symlink + escape-to-outside-dir) in one block. Was RED
against the pre-fix code: <wt>/escape-to-git was created as a symlink
that chained into the source repo's .git. GREEN after the fix.
* fix(worktree): canonicalise repo root before symlinkDirectories checks
Round-7's source-side realpath fix introduced a canonical-vs-lexical
mismatch: `repoRootAbs = path.resolve(this.sourceRepoPath)` is purely
lexical, while `realSource = await fs.realpath(sourceAbs)` is canonical.
On macOS where `/tmp → /private/tmp` and `/var → /private/var` are
ubiquitous, and on any Linux/Windows setup where the user's checkout
sits behind a symlink, the prefixes diverge at the symlink boundary and
`isWithinRoot(realSource, repoRootAbs)` silently rejects every
configured entry.
Production callers (worktreeStartup.ts, EnterWorktreeTool,
agent isolation) all pass the lexical path returned by
`git rev-parse --show-toplevel`. The integ tests masked the bug because
the shared `beforeEach` did `repoRoot = await fs.realpath(dir)` upfront.
Round 8 fix:
- Hoist `repoRootAbs`, `gitDirAbs`, `qwenDirAbs`, and `realWorktreePath`
outside the for-loop — they're loop invariants and were being
recomputed once per entry.
- `await fs.realpath(this.sourceRepoPath)` for `repoRootAbs` so every
containment check below is canonical-vs-canonical. The derived
`gitDirAbs` / `qwenDirAbs` blocklist paths inherit the canonical
prefix automatically. `sourceAbs = path.resolve(repoRootAbs, raw)`
inherits it too, so the early lexical reject paths (absolute, `..`,
repo-root equality, isWithinRoot) stay self-consistent.
- Fail-close: if the repo root itself doesn't realpath (deleted /
inaccessible), bail out of the entire symlink loop rather than
continuing with comparisons we can't trust. Non-destructive — the
worktree was created earlier by `git worktree add`.
New integ test provisions the production shape: a symlink path used
as `sourceRepoPath`, distinct from its canonical realpath. RED on the
pre-fix code (assertion fired with "symlinkDirectories entry was
silently rejected — canonical vs lexical isWithinRoot mismatch"),
GREEN after.
* fix(cli): auto-prepend @ when pasting or dropping multiple file paths
When pasting or drag-and-dropping a single file path, Qwen Code
automatically prepends @ to convert it into an @file reference. However,
pasting or dragging multiple file paths (separated by newlines or
whitespace) did not receive the same treatment, requiring users to
manually add @ to each path.
This change extends the paste detection logic in text-buffer.ts to
detect and prepend @ to multiple file paths, matching the behavior
of single-file paste/drag. The fix also strips surrounding quotes
(common in drag-and-drop input) before path validation.
Before:
- Drag & drop 1 file → @file ✅
- Drag & drop 3 files → 'file1' 'file2' 'file3' ❌
- Paste 1 file → @file ✅
- Paste 3 files → file1 file2 file3 ❌
After:
- Drag & drop 1 file → @file ✅ (unchanged)
- Drag & drop 3 files → @file1 @file2 @file3 ✅ (fixed)
- Paste 1 file → @file ✅ (unchanged)
- Paste 3 files → @file1 @file2 @file3 ✅ (fixed)
* fix(cli): simplify path extraction and escape spaces for @-paths
Refactor multi-file paste @-path detection:
- Extract tryExtractFilePaths() and extractPathsFromSegment() helpers
to eliminate ~100 lines of duplicated path-extraction logic
- Add shellModeActive guard to newline paste branch for consistency
- Remove redundant isPaste variable
- Escape spaces in paths with backslash so downstream parseAllAtCommands
parser correctly handles filenames with spaces (e.g. @/path/to/my\ file.txt)
* fix(cli): address wenshao's code review for multi-file paste
Address 3 critical and 4 suggestion issues from wenshao's review:
Critical fixes:
- Prevent silent data loss: only transform paste when all tokens are
valid paths. If any non-path token exists, preserve original content
(hadNonPathToken tracking)
- Fix O(n²) synchronous fs calls: pre-filter tokens with looksLikePath()
to skip non-path tokens before expensive fs.existsSync calls
- Add tests for paths with spaces and escapePath integration (6 new tests)
Suggestion fixes:
- Fix quoted path regex: require path-like prefix to avoid false matches
on English contractions (don't → /'([~/.][^']*)'/g)
- Flatten if/else in newline paste branch
- Add CRLF, shell mode, and null-return tests
- Escape commas in paths for parseAllAtCommands compatibility
* fix(cli): use escapePath to avoid CodeQL warning
Use escapePath() for whitespace escaping instead of manual regex to
avoid CodeQL's incomplete-string-escaping warning, then additionally
escape commas.
* fix(cli): add comma to SHELL_SPECIAL_CHARS to fix CodeQL warning
- Add comma to SHELL_SPECIAL_CHARS in core so escapePath handles it
- Simplify escapePathAndCommas to just call escapePath(path)
- This avoids CodeQL's incomplete-string-escaping warning
* fix(cli): address wenshao's remaining code review findings
- looksLikePath: add support for relative paths (./, ../, ~/) and dotfiles
- Greedy matching: reverse to longest-match-first for paths with spaces
- Add tests for relative paths, longest-match-first, and invalid paths
* fix(cli): address wenshao's remaining review suggestions
- Fix stale JSDoc: change 'shortest' to 'longest' match-first
- Remove overly broad includes('/') from looksLikePath
- Sync SHELL_SPECIAL_CHARS in vscode-ide-companion (add comma)
- Add tests for shell metacharacters (parentheses, brackets, semicolons)
- Add short-circuit when hadNonPathToken is set
- Inline escapePathAndCommas (now redundant with comma in SHELL_SPECIAL_CHARS)
* fix(cli): address wenshao's latest review suggestions
- Fix quotedPathRegex to support Windows drive-letter paths
- Fix looksLikePath to handle quoted Windows paths split by whitespace
- Allow bare filenames for single-token segments
- Add tests for Windows drive-letter and quoted Windows paths
- Add comma to paths.test.ts escapePath test
* fix(cli): address wenshao's latest JSDoc and test suggestions
- Fix looksLikePath JSDoc to include ../ and ..
- Fix tryExtractFilePaths JSDoc to reflect all shell-special chars
- Add test for bare filename (README.md) single-token segment
* feat(cli): dense inline panel for parallel agent fan-out
When a tool group is composed entirely of multiple `task_execution`
agent invocations (the shape produced by `/review`'s 9-agent fan-out),
`CompactToolGroupDisplay` collapses the whole group into one line —
`Agent × 9 / <last agent's name>` — even though the agents may run
for minutes each. Status, current activity, elapsed, and tokens are
all hidden, so the most informative span of a multi-agent run is
also the most opaque.
Route those groups to a new `InlineParallelAgentsDisplay` that
surfaces every agent on its own row:
╭─ Parallel agents · 9 · 3/9 done ───────────────────────╮
│ ○ Agent 1: Correctness ReadFile server.ts 3m 38s · 7.0k tok
│ ✔ Agent 2: Security 12s · 8.1k tok
│ ○ Agent 3: Code Quality ReadFile index.ts 3m 38s · 9.0k tok
│ ...
╰────────────────────────────────────────────────────────╯
Each row pulls activity / elapsed live from `BackgroundTaskRegistry`
on a 1s tick (same pattern LiveAgentPanel uses). When the registry
unregisters a finished foreground subagent, the row falls back to
`AgentResultDisplay.executionSummary` for elapsed + tokens so the
column doesn't blank out the moment an agent completes.
A new `InlineAgentClaimContext` lets the inline display claim the
agentIds it's rendering; `LiveAgentPanel` filters those out so the
same agent never appears in both surfaces. Claims are refcounted so
React's commit/cleanup interleave doesn't transiently drop a claim
while the same id is being re-claimed by a remount.
Routing conditions in `ToolGroupMessage`:
- Live phase only (`isPending`). Once the group commits to
`<Static>`, the expanded path with `SubagentScrollbackSummary`
owns the permanent record.
- Group has ≥2 calls and ONLY agent calls — mixed groups keep
the legacy renderer so sibling tools stay visible.
- No pending confirmation — those go through the normal renderer
so the keyboard-focus surface for approval stays intact.
Verified visually in tmux with `/review <pr-url> --comment` against
qwen-code PR 4472: all 9 agents render with live status / activity /
elapsed / tokens, transition glyphs ○→✔ in place, and the footer
LiveAgentPanel correctly suppresses the duplicate rows.
11 new tests + all 57 prior tests on touched files pass.
* refactor: address PR review feedback
- Split InlineAgentClaimContext into read + write contexts so
claimers (InlineParallelAgentsDisplay) don't re-render every
time some unrelated inline display claims its own ids. The
write API now has a stable identity for the lifetime of the
provider; only readers (LiveAgentPanel) react to claim-set
changes. Add a test that locks in the stability invariant so a
future memo on `[version]` is caught before it ships.
- Extract `isPureParallelAgentGroup` predicate in ToolGroupMessage
alongside the existing `isSubagentToolEntry` / `isTerminalSubagentTool`
helpers so the routing intent reads at the call site instead of
being spelled out inline.
- Document that `recentActivities` is mutated in place by the
registry; the rows useMemo's `now`-keyed re-read is what
surfaces the latest entry, so `activityLabel` must treat the
value as a tick-snapshot rather than closing over the live
array.
- Document the exhaustiveness of the `hasLiveAgent` status check
(`running | background`) against the upstream
`AgentResultDisplay.status` union so a future status addition
is caught.
- Document why `NAME_COL_WIDTH = 26` (fits /review's longest
agent label at full length on typical 100-col widths) instead
of leaving it as a magic number.
- Add an inline comment in gemini.tsx explaining why
InlineAgentClaimProvider sits inside BackgroundTaskViewProvider
(visible to both surfaces, no provider-boundary crossing).
* refactor: dense panel committed-only, live phase defers to LiveAgentPanel
- Dense panel renders only in committed phase, replacing verbose
per-agent ToolMessage expansion with one compact row per agent.
- Live phase: pure parallel agent groups return null so LiveAgentPanel
below the input is the sole live surface (fixes terminal agents
rendering as verbose ToolMessages above input during live phase).
- Remove InlineAgentClaimContext (no longer needed without live-phase
inline panel).
* refactor: dense panel both phases, LiveAgentPanel maxRows 12
- Show InlineParallelAgentsDisplay in both live and committed phases
with all agents (running + completed). LiveAgentPanel below the
composer also shows running agents during live phase (brief overlap
that resolves as agents complete and expire from the panel).
- Increase LiveAgentPanel DEFAULT_MAX_ROWS from 5 to 12 so all 9
/review agents are visible without truncation.
- Add totalAgentCount prop to InlineParallelAgentsDisplay for correct
header when rendering a subset of agents.
* feat(cli): keyboard navigation for LiveAgentPanel
- Add "main" as first entry in LiveAgentPanel, followed by running agents
- ↓ from Composer focuses LiveAgentPanel (selects "main")
- ↓/↑ navigates between entries with ▸ selection indicator
- Enter on agent opens BackgroundTasksDialog directly in detail mode
- Esc or ↑-at-top returns focus to Composer
- Printable chars auto-unfocus and type through to Composer
- Simplify header from "Active agents (N/N)" to "Active agents (N)"
- Add livePanelFocused + livePanelSelectedIndex state to
BackgroundTaskViewContext, keyboard handling stays in InputPrompt
* refactor: remove redundant Active agents header, keep only main
* fix: eslint warnings — missing deps in useCallback/useEffect
Add livePanelFocused, livePanelSelectedIndex, enterBgDetailFromPanel,
setBgSelectedIndex, bgEntries.length to InputPrompt handleInput deps.
Add isDetailMode to BackgroundTasksDialog effect deps. Remove unused
setBgPillFocused import.
* fix: address Critical review feedback
- Use bgAgentCount (agent-only) instead of bgEntries.length for
keyboard navigation bounds (was counting shells/monitors/dreams).
- Auto-clear livePanelFocused when no agent entries remain (prevents
stuck focus state when LiveAgentPanel returns null).
* fix: update AgentTabBar test for setLivePanelFocused change
* fix(core): consolidate AbortController handling to stop listener leaks in long sessions
Users hit `MaxListenersExceededWarning: 1509 abort listeners added to
[AbortSignal]` in long interactive sessions. The agent runtime nests
parent→child controllers (masterAbortController → per-message round →
per-API-call round → tool execution) and each layer registered its own
`addEventListener('abort', ...)` on the parent without `{once:true}` or
reverse cleanup, so listeners accumulated on long-lived parents across
hundreds of model turns.
Add `utils/abortController.ts` with three helpers:
- `createAbortController(maxListeners = 50)` — factory that pre-caps the
signal so the warning never fires on per-request signals.
- `createChildAbortController(parent)` — WeakRef-based parent→child
propagation with `{once:true}` on the parent listener AND a reverse-cleanup
listener on the child that detaches the parent listener when the child
aborts. This is the key mechanism — short-lived children stop accumulating
dead listeners on long-lived parents.
- `combineAbortSignals(signals, {timeoutMs})` — N-way combiner that replaces
the existing one-input `combinedAbortSignal.ts` (kept as a `@deprecated`
shim so `httpHookRunner.ts` doesn't churn).
Migrate every production `new AbortController()` in `packages/core/src` (24
sites) to the helper. Wrap `_runReasoningLoopInner` per-iteration body and
`AgentHeadless.execute` in `try/finally` so the round controller is aborted
(triggering reverse cleanup) even when the model stream or tool execution
throws. Add `{once:true}` to the manual abort listeners in `hookRunner`,
`functionHookRunner`, and `message-bus` that were missing it. Remove the
`raiseAbortListenerCap` band-aid from `openaiContentGenerator/pipeline.ts` —
no longer needed now that the per-round signal carries `maxListeners=50`.
Add `cli/utils/warningHandler.ts` as a belt-and-suspenders: hides
`MaxListenersExceededWarning.*AbortSignal` from end users in production
(any shape Node ≥20 emits), keeps it visible under `DEBUG`/`QWEN_DEBUG`/
`NODE_ENV=development`. Uses `process.on('warning', ...)` without
`removeAllListeners` so third-party warning subscribers stay intact.
Direct reproducer in `docs/verification/abort-controller-refactor/` proves
the old pattern accumulates 2000 listeners over 2000 rounds while the new
pattern stays at 0.
* fix(core): address PR #4366 review feedback
Four issues from the Copilot review:
1. combineAbortSignals — add a per-iteration `aborted` check inside the
for-loop so we short-circuit if an input signal flips aborted between
the initial scan and listener registration. In single-threaded JS this
can't actually interleave, but the defensive check makes correctness
obvious and protects against signals whose `aborted` getter has side
effects. New test exercises the path via a Proxy that flips after the
initial scan.
2. warningHandler docstring — was stale: said "AbortSignal / EventTarget"
while the regex was tightened to AbortSignal-only in the previous review.
3. README.md — replace personal absolute path with `$WT` placeholder so
the verification recipe is shareable.
4. README.md — replace the markdown table with per-scenario headed
sections. Prettier had interpreted an inline `ps -ef | grep sleep`
pipe character as a column separator, breaking the table rendering on
GitHub. Per-section format is also easier to scan and edit.
* test(core): fix abortController race-defense test to actually hit the loop check
The previous version set the Proxy's `aborted` to true before calling
combineAbortSignals, so the initial `find` scan caught it and we took the
fast path — not the per-iteration check the test was meant to validate.
Switch to an access counter so `aborted` is false on the first read (during
`find`) and true on subsequent reads (inside the loop). This forces the
loop to enter, then catches the flip via the defensive per-iteration check
before any listener is attached to the next input.
Verified the test fails if the per-iteration check is removed.
* fix(lint): include docs/**/*.mjs in the script ESLint block so the AbortController repro passes lint
CI Lint flagged 11 no-undef errors in
docs/verification/abort-controller-refactor/listener-accumulation-repro.mjs
(AbortController, console, process) because the project's flat config
only declared Node globals for ./scripts/**/*.mjs.
The reviewer's suggestion (`/* eslint-env node */`) doesn't work under
ESLint 9 flat config — env directives are deprecated there. The proper
fix is to extend the existing script-globals block to also cover the
verification repro script under docs/.
* fix(core,cli): address PR #4366 critical review findings
Two real bugs the reviewer caught and I confirmed locally:
1. warningHandler.ts didn't actually suppress anything. Adding a
`process.on('warning')` listener does NOT prevent Node's default
onWarning printer from writing to stderr — the default is just an
ordinary listener registered in `lib/internal/process/warning.js`.
My previous code therefore:
- failed to suppress targeted AbortSignal warnings (they still hit
stderr via the default printer)
- produced a SECOND copy of every non-suppressed warning (default
printer + my handler's own stderr.write)
The unit tests missed it because they synthesised a fake warning and
called `process.listeners('warning')` directly rather than going
through `process.emitWarning`.
Fix: snapshot the existing `'warning'` listeners (which include the
default printer and any third-party telemetry hooks) BEFORE replacing
them. Install ours as the sole listener. For non-suppressed warnings
fan out to the captured set so the default printer + telemetry still
fire; for suppressed warnings stop here. Tests now use
`process.emit('warning', ...)` to drive the real listener chain, plus
a spawned-child integration test that asserts the real stderr from
`process.emitWarning` is empty for AbortSignal warnings and still
contains DeprecationWarning text.
2. abortController.createChildAbortController kept a WeakRef to the
child controller. A natural usage pattern — pass `child.signal` into
an async API and drop the controller object — could let the
controller be GC'd while the signal is still in use, after which
`parent.abort()` would no longer propagate. Reproduced with
`node --expose-gc`.
Fix: hold the child strongly via the parent's listener closure. The
reverse-cleanup listener still removes the closure when child aborts
(closure releases child → GC-eligible), and the parent's `{once:true}`
listener self-removes when parent fires (same effect). Net listener
accounting on long-lived parents is unchanged; the only difference is
the controller now stays alive long enough for propagation to reach
downstream consumers that hold only the signal. Tests updated: drop
the old `--expose-gc`-dependent assertion that abandoned children
GC immediately (that was a property of the OLD contract); add a
signal-only-retention test that verifies propagation under the new
contract without needing GC at all.
Verified: 32 helper/warning tests pass (incl. spawned-child stderr
integration); 363 affected caller tests pass; typecheck + prettier +
eslint clean for the touched files.
* fix(core,cli): address PR #4366 review — fix combineAbortSignals orphan listeners + runtime DEBUG toggle
Two real bugs the reviewer caught:
1. combineAbortSignals registered its cleanup listener on
controller.signal AFTER the for-loop. Node does NOT fire 'abort'
listeners added to an already-aborted signal, so when the
per-iteration defensive check aborted the controller mid-loop, the
cleanup never ran — orphaning every input-signal listener registered
before the break, and leaving the (also-registered-after-the-break)
setTimeout uncleared.
Fix: skip timeout scheduling when controller.signal.aborted is
already true post-loop, and when it's true call cleanup()
synchronously instead of registering a doomed listener. Existing
test for the mid-iteration path now also asserts that the
pre-break input signal (a) has zero abort listeners — that's the
assertion that catches the orphan bug. New test for the
already-aborted-input + timeoutMs combination confirms the timer
isn't scheduled (would otherwise overwrite the abort reason).
2. warningHandler captured isDebugMode() in a closure at init time, so
toggling DEBUG / QWEN_DEBUG at runtime (e.g. via a /debug slash
command) didn't update suppression behavior. Moved the check inside
the handler — warnings are rare so the per-emit env-lookup cost is
negligible. New test asserts a mid-stream DEBUG=1 flip starts
forwarding suppressed warnings to the prior-listener chain.
* test(core): strengthen the timeout-guard test in combineAbortSignals to actually exercise the new !aborted check
Reviewer correctly pointed out that the previous version of this test
took the pre-loop fast path (since `a.abort('pre')` ran before
`combineAbortSignals`), so it never reached the in-loop guard at
abortController.ts:138.
Switched to the Proxy `aborted`-getter pattern from the sibling
mid-iteration test (so the loop genuinely re-checks `aborted` and
short-circuits inside the for-loop), and added a `setTimeout` spy that
asserts the timer was never scheduled — this is the only observable
difference from "scheduled then immediately cleared by synchronous
cleanup()", which is what the timer-advance assertion alone couldn't
distinguish.
Verified by mutation testing: removing the guard makes the new test
fail; restoring it makes it pass. Refs PR #4366.
* test(core): cover timeout-triggered cleanup of input-signal listeners in combineAbortSignals
Reviewer noted the timeout path only had an empty-input test, leaving
the leak-sensitive case uncovered: when timeoutMs fires with a
long-lived source signal in the input list, do the input-side
listeners get released? They do (the timeout callback aborts the
combined controller, which fires the auto-cleanup listener registered
on its signal, which calls the per-input removeEventListener), but
that path wasn't tested.
Adds a test that snapshots the source listener count before, asserts
it increased by 1 after combineAbortSignals returns, advances fake
timers past timeoutMs, and asserts the count returns to baseline.
Refs PR #4366.
* fix(test): use pathToFileURL for the warning-handler e2e import on Windows
CI failure on windows-latest:
AssertionError: expected '\r\nnode:internal/modules/run_main:12…'
to match /DeprecationWarning.*Plain deprecation/
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme in:
file, data, and node are supported by the default ESM loader. On
Windows, absolute paths must be valid file:// URLs. Received protocol 'd:'
The e2e test wrote a child script with an `import "<helperPath>"` where
helperPath was a raw Windows absolute path (`D:\a\qwen-code\...`). Node's
ESM loader parses that as a URL on Windows and rejects the `D:` "scheme".
Converted the helper path to a `file://` URL via `pathToFileURL`. macOS
test still passes; the Windows-specific schemes-must-be-URL behavior is
now honored. Refs PR #4366.
* fix(core,cli): address PR #4366 review batch — onAbort leak, migrate missed sites, tighten tests
Adopted 6 of the 7 review threads (skipping the debug-logging suggestion).
1. processFunctionCalls onAbort leak (CRITICAL): the new
`finally { roundAbortController.abort(); }` in _runReasoningLoopInner
would fire the `onAbort` handler in `processFunctionCalls` if
scheduler.schedule or batchDone threw (the explicit
removeEventListener at the old happy-path exit would be skipped),
emitting spurious "Tool call cancelled by user abort." TOOL_RESULT
events for every un-emitted callId — corrupting the transcript and
misleading the model on the next round. Fixed by wrapping schedule
+ batchDone in their own try/finally so removeEventListener always
runs before the outer finally's abort.
2. Migrate 3 new-from-main `new AbortController()` sites that this
PR's audit missed (they came in via the merge from main):
- goals/goalHook.ts (2 sites: judgeController, fallback signal) —
consistency
- hooks/promptHookRunner.ts (1 site: internalAbortController) —
real leak (manual addEventListener without {once:true} or
cleanup, exactly the pattern this PR exists to fix). Switched to
createChildAbortController + finally `internalAbortController.abort()`
for reverse cleanup on the success path.
3. Repro script (`listener-accumulation-repro.mjs`): inlined helper
diverged from production — used WeakRef on child, while production
was changed to strong-ref earlier in this PR. Updated the inlined
copy to match production exactly, with a comment noting the
intentional WeakRef-on-parent-only pattern.
4. warningHandler.ts: documented the snapshot-and-replace trade-offs
in the JSDoc (late-added listeners bypass our filter; late
`removeListener` calls have no effect on our fan-out). Tried the
re-snapshot-per-warning approach the reviewer suggested but it
doesn't work — `removeAllListeners('warning')` permanently removes
the snapshot from Node's tracking, so a `process.listeners('warning')`
filter at fan-out time always returns empty for prior listeners.
The current design is the right trade-off; documentation is the
correct fix.
5. abortController.test.ts: added three coverage gaps the reviewer
identified —
- createChildAbortController forwards custom maxListeners
- manual cleanup() before scheduled timeout fires cancels it
- timeoutMs <= 0 is treated as "no timeout"
6. Migrated `httpHookRunner.ts:202` (the lone caller of the deprecated
`createCombinedAbortSignal`) to `combineAbortSignals` directly,
then deleted `combinedAbortSignal.ts` + its test. All semantics
covered by `combineAbortSignals` tests in abortController.test.ts.
Refreshed `migration-completeness.txt` (now empty — clean grep).
Tests: 194 pass across abortController/warningHandler/agent-runtime/
followup/hooks/goal/promptHook suites. Typecheck + prettier clean.
* docs(verification): commit the headless-scenario scripts referenced by the PR body
The PR body's "End-to-end scenarios I drove locally" section points at
docs/verification/abort-controller-refactor/scripts/02-lite.sh and 06-headless-sigint.sh.
These are the actual reproducible commands behind the EXIT codes /
warning counts reported there — checking them in so anyone can replay
without copy-pasting from the PR description.
Refs PR #4366.
* docs(verification): sync automated-results with current state
Two doc fixes the reviewer flagged:
- migration-completeness.txt was a 0-byte file with a confusing
cross-reference. Populated with the actual grep command + its
"(no output)" result so the empty-output state is explicit.
- automated-results.md still referenced combinedAbortSignal.test.ts (8
tests, @deprecated shim) — both files were deleted in 94e8c5812 when
httpHookRunner.ts migrated to combineAbortSignals directly. Replaced
the line with a reference to httpHookRunner.test.ts. Also updated
the test counts to reflect current state (26 abortController, 13
warningHandler — both grew with the review cycle) and removed the
stale combinedAbortSignal.ts entry from the prettier-check command.
Refs PR #4366.
* test(core): pin two abort-cascade behaviors PR #4366 introduced
Adopting 2 of 3 new review threads (the third — automated-results.md
drift — was already fixed in 5aa7110e4).
1. packages/core/src/agents/arena/ArenaManager.test.ts: pin the
master→agent abort cascade introduced by switching per-agent
controllers to `createChildAbortController(this.masterAbortController)`.
New test spawns ≥2 agents, calls `manager.cancel()`, and asserts every
`agentState.abortController.signal.aborted === true`. Existing cancel
test only checked backend + status; if a future refactor re-introduced
independent controllers, the cascade would silently regress.
2. packages/core/src/followup/speculation.test.ts: cover the
`startSpeculation` abort wiring introduced when the manual
addEventListener + .finally removeEventListener pattern got replaced
by createChildAbortController + .finally abort(). Three tests:
- parent abort propagates to state.abortController (lifetime contract)
- parent-already-aborted fast path returns aborted state
- parent-signal listener count returns to baseline after the fire-and-
forget loop settles (reverse-cleanup proof)
Mocked `runWithForkedChatModel` and `OverlayFs` so the background
loop is a no-op — these tests only assert the synchronous wiring,
not the loop's content.
* fix(test): speculation.test.ts TS errors + sync verification doc counts
Two real CI blockers in the just-added speculation tests (TS2554 and
TS2339) plus stale doc counts the reviewer flagged.
1. saveCacheSafeParams takes 3 positional args (generationConfig,
history, model), not a single object. Compile error on every
platform. Fixed by switching to the correct shape; also moved
getEventListeners to a static `import` at the top of the file
(dynamic `await import('node:events')` exposes EventEmitter's
static method via the namespace type rather than as a direct
property, so destructuring fails type-check).
2. docs/verification/abort-controller-refactor/README.md still claimed
"18 + 1 GC" tests for abortController and "9" for warningHandler;
actual current counts are 26 and 13. Also dropped the stale
combinedAbortSignal reference and added a note about the new
ArenaManager cascade + startSpeculation wiring pin tests.
Refreshed smoke-boot.log against current built bin (still 0.15.11,
which is what package.json reports on this branch).
Refs PR #4366.
* refactor(core): narrow PR #4366 scope per yiliang's review — revert independent-controller migrations
Adopting @yiliang114's review feedback (#4366 review comment, 2026-05-22):
keep only the migrations that fix the real leak path (the agent-runtime
parent→child chain that accumulates listeners on a long-lived parent
signal in long sessions) and revert the consistency-only migrations on
independent short-lived controllers.
Issue #4423 confirms the user-visible bug is the nested-chain
accumulation — the reverted sites do not contribute to that bug.
Migrations KEPT:
- agents/runtime/agent-interactive.ts (master + per-message round)
- agents/runtime/agent-core.ts (per-iteration + wait + processFunctionCalls)
- agents/runtime/agent-headless.ts (external → execution)
- hooks/promptHookRunner.ts (real cleanup leak: addEventListener without
{once:true}, never removed)
- hooks/httpHookRunner.ts → combineAbortSignals direct (shim deleted)
- hookRunner.ts / functionHookRunner.ts / message-bus.ts: {once:true} only
- openaiContentGenerator/pipeline.ts band-aid removal (per-request signals
are children of the per-round controller, which carries maxListeners=50)
- warningHandler.ts belt-and-suspenders
Migrations REVERTED (independent short-lived controllers; restored to
`new AbortController()` + their original cleanup patterns):
- agents/arena/ArenaManager.ts (master + per-agent)
- agents/background-agent-resume.ts (3 sites)
- core/client.ts (recall — restored manual addEventListener + finally
removeEventListener pattern from main)
- followup/speculation.ts (restored parentAbortHandler + finally
removeEventListener)
- goals/goalHook.ts (judgeController + fallback signal)
- memory/manager.ts (dream controller)
- services/chatCompressionService.ts (fallback signal)
- services/chatRecordingService.ts (autoTitle controller)
- tools/agent/agent.ts (fg + bg subagent controllers — restored manual
onParentAbort + finally removeEventListener)
- tools/monitor.ts (entryAc)
- tools/shell.ts (promote + 3 entryAc)
- utils/fetch.ts (fetchWithTimeout)
Tests removed alongside the reverts:
- ArenaManager.test.ts "cancels cascades..." — the cascade itself was an
intentional behavioral improvement that's now reverted, so the
pin-test belongs with it
- speculation.test.ts "startSpeculation — abort-controller wiring" block
(3 tests) — they tested helper-wired behavior we reverted
Verification docs updated to reflect the narrower scope.
Net change: 19 raw `new AbortController()` remain (intentional, per
migration-completeness.txt rationale); previously was 0.
Refs PR #4366, issue #4423.
/context counted every registered deferred tool — MCP tools plus
low-frequency built-ins like web_fetch, monitor, cron_*, exit_plan_mode,
enter/exit_worktree, send_message, task_stop — even when ToolSearch had
never loaded them. The real API request (client.ts:506) only sends
revealed tools, so the displayed totals diverged from what's actually
in the prompt.
The previous `getFunctionDeclarations({ includeDeferred: true })` was
added alongside ToolSearch (#3589) to keep `displayBuiltinTools = total
- mcp` non-negative, but it aligned both sides to the "registry"
dimension instead of the "prompt" dimension. This change aligns both
sides to "prompt" (matching client.ts): the function-declaration call
drops the override, and the per-tool loop skips deferred-but-not-revealed
tools too — keeping the math consistent without overcounting.
On a default session that has just sent a single message, this reclaims
~8.2k tokens of false overhead (MCP 4.9k + deferred built-ins 3.3k) and
reattributes them to the messages category, where they actually live.
Closes#4508
Co-authored-by: Qwen-Coder <noreply@alibaba-inc.com>
* fix(cli): require whitespace before @ to trigger file completion
Input like `cici@192.168.0.160` was incorrectly triggering @ file
completion mode, causing the session to become unresponsive because
Enter was consumed by the suggestion handler instead of submitting.
Add a check that @ must be at position 0 or preceded by a space,
matching the existing `isAtCommand()` semantics used at submit time.
* test(cli): add regression tests for @ completion whitespace check
Add two test cases to prevent regression:
- cici@192.168.0.160 should not trigger AT completion
- user@example.com should not trigger AT completion
* fix(cli): use \s regex for @ whitespace check to match isAtCommand
Use /\s/.test() instead of === ' ' so the completion trigger matches
isAtCommand's /\s@/ pattern, covering tabs and other whitespace.
* feat(cli): headless runaway-protection guardrails (#4103)
Adds two opt-in run-level budgets and a startup safety warning for
non-interactive / CI / SDK runs. All defaults preserve existing
behavior; the budgets only fire when the user explicitly sets a limit.
Phase 1 — surface unsafe configs and fix doc drift
- New `--yolo`-without-sandbox stderr warning at startup of every
non-interactive run, emitted by `getHeadlessYoloSafetyWarning` in
`packages/cli/src/utils/headlessSafetyWarnings.ts`. Suppressible
via `QWEN_CODE_SUPPRESS_YOLO_WARNING=1` (strict `1`/`true` match so
`=0` / `=false` don't silence it). Strict env match also applied to
the `SANDBOX` check so values like `SANDBOX=0` don't accidentally
bypass the warning.
- Gated on `!config.isInteractive()` at the gemini.tsx call site so
TUI users aren't nagged.
- `docs/users/configuration/settings.md`: corrected
`model.skipLoopDetection` default (`true`, not `false`) and reworded
the `--yolo`/sandbox section — `--yolo` does NOT auto-enable a
sandbox; sandboxing must still be opted into explicitly.
Phase 2 — run-level budgets with distinct exit code
- `--max-wall-time` / `model.maxWallTimeSeconds`: wall-clock duration
for the whole run. Flag accepts `90` (s), `30s`, `5m`, `1h`,
`500ms`. Settings is plain seconds.
- `--max-tool-calls` / `model.maxToolCalls`: cumulative tool
executions (success + failure). Ticked BEFORE each `executeToolCall`
so a budget of N caps the run at exactly N executions.
- New `FatalBudgetExceededError` (exit code 55), distinct from
`FatalTurnLimitedError` (53) and `FatalCancellationError` (130) so
CI scripts can branch on the reason. JSON output mirrors the
`handleMaxTurnsExceededError` / `handleCancellationError` envelope
convention.
- Enforced via `RunBudgetEnforcer` in
`packages/cli/src/utils/runBudget.ts`, wired to the same
`AbortController` as SIGINT so existing cancellation plumbing
carries the abort. A `routeAbort` helper distinguishes budget vs.
SIGINT at the abort-check sites and at the outer catch.
Critical correctness fixes (informed by the #4105 review pass)
- Drain-loop fall-through: the inner drain-item `for await` previously
exited via `finalizeAssistantMessage(); return;`, swallowing a
budget abort that fires during the last drain item and surfacing
exit code 0. Now routes through `routeAbort` so exit 55 is
preserved.
- Settings symmetry: `maxWallTimeSeconds: 0` in settings.json is now
rejected (same as `--max-wall-time 0`); the enforcer treats `<=0`
as "no timer" so silent disable would be a foot-gun.
`validateMaxWallTimeSetting` also rejects `Infinity` / `NaN`.
- `setTimeout` overflow: both parser paths reject durations above
`Math.floor((2^31 - 1) / 1000)s` (~24.8 days). Node clamps
oversized delays to 1ms and fires the timer almost immediately;
fail loud at startup instead.
- First-fence-wins + SIGINT race: `markExceeded` no-ops if the
controller was already aborted by a third party, so a budget tick
arriving after user SIGINT doesn't misattribute the abort to exit
code 55.
- Outer catch re-routes mid-stream `AbortError`s through the budget
handler so users see "Run aborted: …" instead of raw "AbortError".
Tests
- `runBudget.test.ts` (32 tests): parser happy / reject paths,
setting validator, post-increment off-by-one, `maxToolCalls=0`
meaning "disallowed", `-1` meaning unlimited, wall-clock under
fake timers, `stop()` cancels pending timer, idempotent `start()`,
first-fence-wins, SIGINT-race protection.
- `headlessSafetyWarnings.test.ts` (7 tests): YOLO + sandbox / env
matrix; strict-truthy `SANDBOX` check; suppression env.
- Pre-existing suites: `nonInteractiveCli.test.ts` (46),
`gemini.test.tsx` (23), `config/config.test.ts` (220),
`core/utils/errors.test.ts` (12), `core/config/config.test.ts`
(172) all green after picking up the new config getters / CliArgs
fields.
Backward compatibility
- All budgets default to `-1` (unlimited); existing CLI invocations
behave identically.
- New stderr warning only fires in the narrow YOLO-no-sandbox case,
with an explicit suppress env.
- New exit code 55 is purely additive; no existing exit codes change
meaning.
* fix(cli): address audit findings for headless guardrails (#4103, #4502)
Round-1 audit (3 angles × line-by-line + removed-behavior + cross-file)
plus an open-ended design pass surfaced eight correctness issues. This
commit lands all of them; the larger ACP / serve-mode structural items
are documented for follow-up.
Correctness fixes
- headlessSafetyWarnings: `SANDBOX` env check reverted to plain truthy.
The sandbox transport sets `SANDBOX` to `sandbox-exec` (macOS
seatbelt) or the container name (`qwen-code-sandbox`), neither of
which matches `isTruthyEnv`. The PR's strict-`1`/`true` check was
emitting the "no sandbox" warning INSIDE real sandboxes. Match the
rest of the codebase (sandboxConfig.ts, gemini.tsx, Footer.tsx,
prompts.ts, …) which all treat any non-empty value as "sandboxed".
- nonInteractiveCli main-loop abort: add `finalizeAssistantMessage()`
before `routeAbort()`. The drain-item loop already had it (PR #4502
Critical bug #1); the main loop was asymmetric — stream-json
consumers would see an unterminated `message_start` when a budget /
SIGINT abort landed mid-stream.
- nonInteractiveCli drain-loop `routeAbort`: also flush
`flushQueuedNotificationsToSdk(localQueue)` and
`finalizeOneShotMonitors()` before exiting. The old `return`-and-
fall-through path went through the outer holdback loop, which did
this flushing; switching to `routeAbort()` skipped it, so
`task_started` envelopes lost their paired `task_notification`.
- nonInteractiveCli catch handler: emit `adapter.emitResult({...})`
BEFORE `handleBudgetExceededError`, with the budget message as
`errorMessage` when budget tripped. Previously the budget handler
`process.exit(55)`ed before the adapter could emit a terminal
`result` envelope, so STREAM_JSON consumers never saw a stream
terminator on budget exits and hung waiting for one.
- runBudget: new `validateMaxToolCalls` mirrors
`validateMaxWallTimeSetting`. yargs coerces non-numeric flag values
(`--max-tool-calls abc`) to `NaN`, and the enforcer's `>= 0` gate
treats `NaN` and negatives as "no limit", silently disabling the
budget. Reject `NaN`, `Infinity`, fractional, and negative-other-
than-`-1` values at both flag and settings layers. `0` remains
legal (`first tick aborts`), unlike wall-time where 0 is fatal.
- runBudget: new `MIN_WALL_TIME_SECONDS = 1` floor. Previously
`--max-wall-time 500ms` parsed cleanly and aborted on the next
event-loop tick before any model round-trip — almost certainly a
typo (`5m`?) and not a useful guardrail at any rate.
- nonInteractiveCli `tickToolCall`: exempt `ToolNames.STRUCTURED_OUTPUT`.
Under `--json-schema` this is the terminal "I'm done" contract tool,
not real work. Without the exemption a budget-edge completion is
aborted as a false positive (model used N tools then emitted
structured_output as call N+1 → exit 55 instead of success).
- commands/serve.ts: emit the YOLO-no-sandbox warning at daemon
startup when settings.json statically configures
`tools.approvalMode: 'yolo'` with no `tools.sandbox` /
`SANDBOX` env. The daemon can't use `getHeadlessYoloSafetyWarning`
(no Config yet — sessions get their own) so we re-derive the
predicate from settings. Per-session ACP override is documented as
out of scope.
Documentation
- `docs/users/features/headless.md`: new "Scope" subsection under
Run-level budgets explaining (a) `--max-tool-calls` counts top-level
dispatches only — subagent / `agent` tool inner calls are not
counted, (b) `structured_output` is exempt, (c) stream-json input
mode resets budgets per user message, (d) `qwen serve` / ACP
sessions do not currently consult budgets from settings.json.
Tests
- `runBudget.test.ts` grows from 32 → 41 tests: `validateMaxToolCalls`
(NaN / Infinity / negatives / fractional), `parseDurationSeconds`
sub-second rejection, `validateMaxWallTimeSetting` sub-second
rejection.
- `headlessSafetyWarnings.test.ts`: replaced the "still warns when
SANDBOX is 0/false/no" case (which encoded the strict-check bug) with
positive coverage for the real sandbox-set values
(`sandbox-exec`, `qwen-code-sandbox`).
All previously-green suites still green: cli/nonInteractiveCli (46),
cli/gemini.test (23), cli/config/config.test (220), core/utils/errors
(12), core/config/config.test (172). 337 tests across the touched suites.
Won't-fix (out of scope, documented or pre-existing)
- Unpaired `tool_use` in stream-json when a tool is aborted mid-execution
— pre-existing structural gap (SIGINT mid-tool has the same outcome);
PR amplifies it but doesn't introduce it.
- Narrow SIGINT-vs-budget-timer race — already mitigated by
`markExceeded`'s `signal.aborted` check.
- `tickToolCall` increments past abort (cosmetic; only affects the
`observed` value in the error envelope for a pathological caller).
* fix(cli): round-2 audit fixes for headless guardrails (#4103, #4502)
Round-2 audit (after round-1 commit 40ae6dd0f) surfaced two NEW
correctness issues introduced by the round-1 catch-handler restructure,
plus a handful of polish items from a parallel design pass.
Correctness fixes (new bugs from R1)
- nonInteractiveCli catch handler: wrap `adapter.emitResult` in
try/catch. R1 moved the emit BEFORE `handleBudgetExceededError` so
STREAM_JSON consumers see a terminal envelope first. But emitResult
eventually hits `stdout.write`, which throws on EPIPE /
ERR_STREAM_WRITE_AFTER_END when a piped consumer closes early
(`qwen -p ... | head -n 1` is the common CI case). Letting that
throw bubble out skipped both `handleBudgetExceededError` and
`handleError`, dropping the documented exit-code-55 contract
precisely when stdout was in trouble. Best-effort emit and continue
to the exit handler.
- nonInteractiveCli `structured_output` exemption: also require
`config.getJsonSchema?.() !== undefined`. Without that guard, an
MCP server registering an unrelated tool literally named
`structured_output` would silently bypass `--max-tool-calls`. Also
documents (in `headless.md` "Scope") the related caveat that failed
Ajv-validation retries skip the tick too, so a malformed-output
retry loop is NOT bounded by `--max-tool-calls` — combine with
`--max-session-turns` or `--max-wall-time`.
Polish
- runBudget `validateMaxToolCalls` upper bound: cap at 1_000_000.
`1e10` (typo for `1e1`) would otherwise parse cleanly, pass the
`>= 0` gate forever, and silently disable the budget — the exact
foot-gun `MAX_WALL_TIME_SECONDS` was built to prevent. Symmetry.
- runBudget `parseDurationSeconds` sub-second hint: only append the
"did you mean Ns?" suggestion when the input actually contained
`ms`. Bare `0.5` would otherwise produce a useless "did you mean
0.5s?" suggestion.
- nonInteractiveCli `routeAbort`: the `throw 'unreachable'` is only
hit if `handleBudgetExceededError` / `handleCancellationError` ever
becomes resumable (e.g. mocked `process.exit` in a test). Carry
the original exceeded.message into the thrown Error so the outer
catch's `errorMessage` field stays actionable instead of degrading
to a literal "unreachable" string.
- commands/serve.ts: compare `approvalMode` against `ApprovalMode.YOLO`
enum instead of the string literal `'yolo'`. If the enum value is
ever renamed, the startup warning stays in sync with the helper at
`headlessSafetyWarnings.ts` instead of silently going dead.
Documentation
- `headless.md` "Scope": clarify the `structured_output` exemption is
unconditional (including failed validations); add explicit note
that `--max-session-turns` does NOT exempt `structured_output`, so
size to `N+1` for `N` real-work turns under `--json-schema`.
- `headless.md` flag table: add `1.5h` to the accepted-forms hint for
`--max-wall-time` (the parser already accepts fractional units).
Tests
- `runBudget.test.ts`: new coverage for the `validateMaxToolCalls`
ceiling. Total 42 tests across `runBudget.test.ts` (was 41), all
green. cli/nonInteractiveCli, gemini.test, config/config all
unchanged and still green.
Won't-fix (documented above or out of scope)
- ACP per-session approval-mode escalation (mid-session flip to YOLO)
doesn't print the warning — daemon-level wiring; out of scope for
this PR.
- 1s wall-time floor vs higher (5–10s) — debatable, keeping 1s with
loud sub-second rejection; can raise later without semver impact.
- Integration test for the full budget-trip → catch → emitResult →
exit 55 path — requires a process-exit-mocking harness; tracked as
follow-up.
* docs: align headless guardrails examples with R1 sub-second floor
Round-3 audit caught two stale doc surfaces that R1's 1-second wall-time
floor (and R2's `1.5h` fractional-unit addition) didn't update:
- `docs/users/features/headless.md` budget table: replace stale `500ms`
example with `1.5h`, add explicit "minimum 1s — sub-second values are
rejected as typos" note.
- `docs/users/configuration/settings.md` `model.maxWallTimeSeconds` row:
same fix. Also extend `model.maxToolCalls` row with the structured_output
exemption note, the `0` semantic, and the 1,000,000 ceiling that R2
added.
A user copying the documented `--max-wall-time 500ms` example from either
surface would hit a startup error after R1.
Known follow-up (not addressed in this commit)
- No test exercises the R2 `isStructuredOutputExempt` predicate end-to-end.
Adding one needs the same process-exit-mocking harness called out in the
R2 commit as a separate follow-up.
* docs: align JSDoc / schema / CLI help with R1+R2 validation rules
Round-4 final-pass audit caught four schema/help-text/JSDoc surfaces
that drifted from the validators introduced in R1 (1s wall-time floor,
24-day ceiling) and R2 (1M tool-call ceiling, structured_output
exemption, `0` sentinel).
- `runBudget.ts` `parseDurationSeconds` JSDoc: replace stale claim
that `500ms` is accepted and "sub-second precision is preserved"
with the actual contract — `[MIN_WALL_TIME_SECONDS, MAX_WALL_TIME_SECONDS]`,
ms suffix only legal when value resolves to >= 1s. Adds `1.5h` to
the accepted-forms list.
- `settingsSchema.ts` `model.maxWallTimeSeconds` description: now
documents the 1s minimum and ~24-day ceiling.
- `settingsSchema.ts` `model.maxToolCalls` description: documents the
structured_output exemption, the `0` sentinel ("no tool calls
allowed"), and the 1,000,000 ceiling.
- `vscode-ide-companion/schemas/settings.schema.json`: mirrors both
schema descriptions above so the VS Code settings UI auto-completion
matches.
- `config.ts` yargs `--max-wall-time` description: documents the 1s
floor and the ~24-day max.
- `config.ts` yargs `--max-tool-calls` description: documents the
structured_output exemption, the `0` sentinel, and the 1M ceiling.
`qwen --help` is the most-read surface for these flags; matches the
prose docs in headless.md and settings.md.
No code changes — pure doc/help-text alignment.
---------
Co-authored-by: 克竟 <dingbingzhi.dbz@alibaba-inc.com>
* feat(telemetry): propagate W3C traceparent on outbound LLM requests
Part 1 of #4384 (sub-issue of #3731 P3 deeper observability).
Today qwen-code's only OTel instrumentation is `HttpInstrumentation`,
which only patches Node's `http`/`https` modules. The `openai` and
`@google/genai` SDKs use `globalThis.fetch` (undici), so outbound LLM
requests carry no `traceparent` header and trace context dies at the
qwen-code process boundary.
Adds `@opentelemetry/instrumentation-undici@0.14.0` (peer-compatible
with the installed `@opentelemetry/instrumentation@0.203.0`) and wires
it into `initializeTelemetry()` next to the existing
`HttpInstrumentation`. Default propagator (W3C tracecontext + baggage)
remains unchanged — no explicit `textMapPropagator` needed.
`ignoreRequestHook` skips OTLP exporter endpoints to avoid the
classic feedback loop (OTel SDK uses fetch to upload OTLP data; without
the hook each upload would create a span that gets uploaded, infinitely).
Configured `otlpEndpoint` / per-signal endpoints are stripped of trailing
slash and query string for robust prefix matching against undici's
`request.origin + request.path`.
Outbound LLM calls now also produce a client-side HTTP span (separating
network TTFB / transfer time from the existing `api.generateContent`
total-duration span).
Design doc: docs/design/telemetry-outbound-propagation-design.md
(Part A — traceparent; Part B — session id header — lands in a
follow-up PR per the design's split rationale.)
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): harden OTLP feedback-loop guard + slim lockfile diff
Review feedback on #4390:
1. CI was failing on npm ci because the lockfile was generated with npm 11
locally (it sprinkles `peer: true` annotations npm 10 reads differently
and rejects). Regenerated with npm 10 (matching CI's Node 22.x default),
so the diff vs main is now 18 lines (the actual instrumentation-undici
entry) instead of 105 lines of npm-version drift noise.
2. (Copilot inline at sdk.ts:330) `otlpUrlPrefixes` was derived from raw
Config strings, so a settings.json `"otlpEndpoint": "\"http://...\""`
(quoted) or trailing `#fragment` would silently miss the prefix match
and reintroduce the feedback loop the hook exists to prevent. Replaced
the regex-based suffix trim with a WHATWG URL parser:
- strips ?query, #fragment, trailing slash
- trims symmetric ASCII quotes a user may have placed in settings.json
- falls back to safe suffix trimming if URL parsing fails (misconfigured
endpoint still gets SOME protection)
3. (CodeQL inline) Replaced the `/\?.*$/` regex in ignoreRequestHook with
`indexOf('?')`/`indexOf('#')` slicing for ReDoS hygiene. The regex was
linear in practice but flagged as polynomial — using indexOf removes
the ambiguity and is arguably simpler.
Added 3 tests in sdk.test.ts covering the new normalizations (#fragment
on incoming path, quoted endpoint, #fragment on configured endpoint).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(telemetry): propagate X-Qwen-Code-Session-Id on outbound LLM requests
Part 2 of #4384. Stacks on top of PR #4390 (traceparent via undici).
Adds a product-namespaced HTTP header X-Qwen-Code-Session-Id to every
outbound LLM request when telemetry is enabled, so server-side ingestion
can correlate observed requests with qwen-code session metric/log records.
Pattern matched from claude-code (X-Claude-Code-Session-Id, verified at
src/services/api/client.ts:108 in their open-source repo).
Critical design decision (design doc section 4.3): the OpenAI / Anthropic
providers use a per-request fetch wrapper rather than the SDK defaultHeaders
option, because content-generator SDK clients are constructed once and NOT
recreated on /clear-triggered session resets (Config.resetSession updates
this.sessionId but the contentGenerator keeps using the stale header value).
Reading config.getSessionId() from inside the wrapper at request time gives
the live value.
Gemini provider uses static httpOptions.headers — @google/genai HttpOptions
interface does not expose a fetch hook (only headers, baseUrl, apiVersion,
timeout, extraParams). This is a known limitation: after session reset,
Gemini X-Qwen-Code-Session-Id stays stale until the contentGenerator is
recreated. Documented in telemetry.md and the design doc section 8.6;
spans/logs continue to carry the live session id for trace/log correlation.
Lazy-invalidate fix is a follow-up sub-issue.
Header is omitted when telemetry is disabled OR when getSessionId returns
an empty string (some HTTP middleware rejects empty header values).
Integration sites:
- packages/core/src/core/openaiContentGenerator/provider/default.ts
(base class — automatically covered by deepseek/minimax/mistral/
modelscope/openrouter subclasses; openrouter calls super.buildHeaders)
- packages/core/src/core/openaiContentGenerator/provider/dashscope.ts
(overrides buildClient — must be touched separately; QwenContentGenerator
inherits via this provider)
- packages/core/src/core/anthropicContentGenerator/anthropicContentGenerator.ts
- packages/core/src/core/geminiContentGenerator/index.ts (factory function,
not the GeminiContentGenerator class — no signature change)
End-to-end verification (local HTTP server in tmux):
PASS: traceparent + X-Qwen-Code-Session-Id on every LLM request
PASS: session id refreshes after simulated /clear (staleness regression
guarded by llm-correlation-fetch.test.ts)
PASS: OTLP upload traffic not traced (no feedback loop — PR A
ignoreRequestHook working)
Robot generated with Qwen Code https://github.com/QwenLM/qwen-code
* fix(telemetry): R2 review fixes — critical correctness + tsc + boundary safety
Adopts 7 review findings from wenshao on #4390 (+ duplicates from now-closed
#4393). Critical bugs first, polish second.
CRITICAL:
1. tsc TS2322 — wrapper return type incompatible with Anthropic SDK Fetch.
`typeof fetch` (Node WHATWG, 2 overloads) is not structurally assignable
to Anthropic's narrower `Fetch = (input: RequestInfo, init?) => ...`,
even though they're call-compatible at runtime. Make wrapper generic
`<TFetch extends FetchLikeLoose>` so callers preserve their exact fetch
signature; cast the Anthropic call site through `unknown` with a comment
explaining why.
2. tsc TS2352 / TS2493 — `baseFetch.mock.calls[0]![1] as RequestInit` was
out-of-bounds when wrapped was called with no init arg. Replaced with a
`makeFetchMock()` helper returning typed accessors.
3. normalizeOtlpPrefix catch fallback was DANGEROUS — a config of `"http"`
produced prefix `"http"` which `startsWith`-matched every outbound HTTP
request → silently disabled ALL instrumentation (no client spans, no
correlation header — defeats the entire feature). Fixed: catch returns
undefined + diag.warn. Misconfigured endpoint loses its feedback-loop
guard (acceptable) instead of disabling all guards (catastrophic).
4. `url.startsWith(prefix)` matching was NOT boundary-safe — port collision
(`:4318` matches `:43180`), hostname suffix collision (`otlp.example.com`
matches `otlp.example.com.evil.net`), path-segment collision (`/v1`
matches `/v1foo/x`). Replaced with origin-equality + path-prefix +
boundary-char check (next char must be `/`, `?`, `#`, or end-of-string).
5. HttpInstrumentation also lacked the OTLP feedback-loop guard. The OTLP
HTTP exporter (`@opentelemetry/exporter-trace-otlp-http`) uses node:http
(patched by HttpInstrumentation, NOT undici). Without this, every OTLP
upload batch creates a parasitic client span → feedback loop. Added
`ignoreOutgoingRequestHook` that reuses the same `matchesOtlpPrefix` /
`stripPathSuffix` helpers as the undici instrumentation.
SAFETY:
6. Request input + undefined init dropped the Request's own headers
(Authorization etc.) because `new Headers(undefined)` → `{...init, headers}`
replaced them with just our session header. Fix: when input is a Request
and init.headers is unset, seed from input.headers before adding ours.
7. Wrapped fetch had no try/catch — a throwing Config getter or Headers
constructor would propagate as TypeError and break the LLM request path.
Wrapped header construction in try/catch; on failure, fall through to
baseFetch with original init (no header) + diag.warn. Telemetry must
never break the model call.
COVERAGE:
- 3 new sdk.test.ts boundary tests (port/host/path)
- 1 new sdk.test.ts normalizeOtlpPrefix catch-branch coverage
- 1 new sdk.test.ts HttpInstrumentation OTLP guard test
- 1 new sdk.test.ts proxy-mode wrapped-fetch test (default.test.ts)
- 1 new anthropic test asserting wrapped fetch installed on Anthropic SDK
- 2 new llm-correlation-fetch.test.ts (Request-headers preservation + try/catch fall-through)
All 668 tests pass (1 pre-existing Anthropic User-Agent failure on main is
unrelated). tsc clean.
Declined: #10 DRY-refactor of baseFetch extraction across 3 sites — the
duplication was pre-existing (default/dashscope buildClient was already
near-identical), refactoring is a separate cleanup PR not gated by this
feature. Will reply on the thread.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* chore(deps): allow patch updates for @opentelemetry/instrumentation-undici
Switch from exact pin `0.14.0` to `^0.14.0` for consistency with the rest
of the `@opentelemetry/*` deps in this block (all carated).
For 0.x semver, npm treats `^0.14.0` as `>=0.14.0 <0.15.0`, so patch
updates within the 0.14.x line — which are tied to the same
`@opentelemetry/instrumentation@0.203.x` peer — flow in via `npm update`
without requiring a manual package.json edit. A bump across the 0.x
minor (e.g. 0.15.x) would shift the instrumentation peer compatibility
and still requires explicit attention, which the caret correctly blocks.
Per review feedback on #4390 (wenshao).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(telemetry): stub getTelemetryEnabled + getSessionId in Gemini factory tests
The X-Qwen-Code-Session-Id commit added a `staticCorrelationHeaders(gcConfig)`
call inside the Gemini content generator factory. That helper reads
`gcConfig.getTelemetryEnabled()` and `gcConfig.getSessionId()` per request.
Both pre-existing Gemini tests in `contentGenerator.test.ts` build a minimal
partial Config stub via `as unknown as Config` and only stub the methods the
factory used to need. The new call path now hits the unstubbed methods at
runtime, surfacing as `TypeError: config.getTelemetryEnabled is not a function`
on all three CI platforms.
Add the two missing stubs to both test cases. The Gemini factory continues
to ignore the values when telemetry is off — these stubs only have to exist,
not return anything in particular.
Local check ran the full test suite for the four directories `/loop` covers
plus `src/core/contentGenerator.test.ts` itself; all green. Also re-ran the
other test files that build partial Config mocks via the same idiom
(`client.test.ts`, `config.test.ts`, `nextSpeakerChecker.test.ts`,
`content-generator-config.test.ts`) — none exercise the new code path.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): R3 review fixes — port + protocol + quote + safety
Four issues found by wenshao reviewing the R2 boundary-safety pass on PR
#4390. All four close gaps where the OTLP feedback-loop guard or the
correlation-header path could fail silently.
1. **Port normalization mismatch** (sdk.ts ignoreOutgoingRequestHook):
`normalizeOtlpPrefix` builds prefixes via `URL.origin`, which strips
default ports (`:80` for http, `:443` for https). The hook reconstructed
request origin manually as `${proto}://${host}${portPart}`, keeping the
port. Result: prefix `http://collector` (no explicit port) didn't match
a request to `http://collector:80/v1/traces` because their `.origin`
differed → guard bypassed → feedback loop. Now the reconstructed origin
is also routed through `URL` so both sides apply the same default-port
stripping.
2. **HTTPS proto silent fallback** (sdk.ts ignoreOutgoingRequestHook):
The `(req.protocol && ...) || 'http'` fallback would silently mis-bucket
HTTPS requests as HTTP when `req.protocol` was unset, so HTTPS OTLP
endpoints couldn't match their prefix. Changed to fail open: when proto
can't be determined, return false (request gets instrumented). Worst
case is a parasitic client span — observable, recoverable — versus the
previous unbounded silent feedback loop. Picked fail-open over the bot's
port-based heuristic because non-standard HTTPS ports break the
heuristic but not fail-open.
3. **Quote-stripping divergence** (sdk.ts normalizeOtlpPrefix):
`parseOtlpEndpoint` (line 109) uses `/^["']|["']$/g` which strips
asymmetric leading/trailing quotes; `normalizeOtlpPrefix` previously
only stripped symmetric pairs. A settings.json typo like `"value'` would
let the exporter connect (parseOtlpEndpoint trims) but leave the guard
returning `undefined` (normalizeOtlpPrefix rejected) → parasitic loop.
Aligned `normalizeOtlpPrefix` to the same lenient regex.
4. **`staticCorrelationHeaders` missing try/catch** (llm-correlation-fetch.ts):
`wrapFetchWithCorrelation` already catches all internal exceptions and
falls through to baseFetch — same "telemetry must never break LLM path"
contract was missing on the static-headers helper. A throw here would
propagate up to the Gemini content-generator factory and crash
content-generator init for the whole session. Wrapped the body in
try/catch with `diag.warn` fall-through to `{}`.
Tests: added 4 regression tests covering each scenario:
- default-port HTTP request matched against portless prefix (1)
- hook returns false when req.protocol missing on https endpoint (2)
- asymmetric-quoted endpoint normalizes for guard parity (3)
- staticCorrelationHeaders returns {} when config getter throws (4)
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(telemetry): fix misleading "BOTH" wording in wrapFetchWithCorrelation
The comment described the header-seeding logic as merging "BOTH the
init.headers AND the Request's own headers", but the two branches are
mutually exclusive — `new Headers(init?.headers)` runs unconditionally
(empty Headers when init.headers is undefined), and the Request-headers
copy only runs when init.headers is undefined. So in practice it's
either-or, not BOTH.
Reworded to match the actual logic per #4390 review feedback (wenshao).
Behavior unchanged.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): strip port from req.host fallback + document undici scope
Two issues found by wenshao reviewing the R3 boundary-safety fixes on PR
#4390.
1. **`req.host` may already include `:port`** (sdk.ts ignoreOutgoingRequestHook):
When `req.hostname` is absent and `req.host` is the fallback, the value
may already be `"collector:4318"`. Naively appending `:${req.port}`
produced `"http://collector:4318:4318"` → `new URL()` rejects → catch
returns false → silent guard bypass for that request. Currently
unreachable because `@opentelemetry/otlp-exporter-base` always sets
`hostname` from WHATWG URL parsing, but the fallback exists in the
code and must be correct — a future OTLP transport that emits `host`
without `hostname` would silently trigger the feedback loop. Strip the
port when falling back; bracketed IPv6 literals like `"[::1]:443"`
keep their bracketed host intact.
2. **Undici scope honesty** (telemetry.md):
Previous docs framed the propagation as "outbound LLM requests", but
`UndiciInstrumentation` actually patches `globalThis.fetch` for the
whole process — `WebFetch`, MCP clients, IDE extension calls all get
spans + `traceparent` injection too. Added a "Scope: all fetch() calls,
not just LLM" subsection covering: (a) trace ID leakage to third-party
URLs (the user-supplied destinations of `WebFetch` see our trace ID;
not secret per W3C but worth knowing); (b) non-LLM span volume
inflating OTLP batches with a workaround tip. Per-destination scoping
toggle deferred as a follow-up — out of scope for this PR.
Added regression test for the host:port-fallback path. Test exercises
the previously broken combination (hostname absent, host carries port)
through the existing test harness.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(telemetry): scope X-Qwen-Code-Session-Id to first-party hosts by default
Address LaZzyMan's REQUEST_CHANGES review of PR #4390.
The original design injected `X-Qwen-Code-Session-Id` on every outbound
LLM request gated only by `telemetry.enabled`. Review caught that this
broadcasts a stable cross-request client identifier to every configured
third-party provider (OpenAI, Anthropic, OpenRouter, MiniMax, ModelScope,
Mistral, vanilla Gemini, ...), which the claude-code precedent does NOT
justify — claude-code is a first-party Anthropic→Anthropic flow; qwen-code
is an open-source CLI connecting to many providers.
Fix: add a host allowlist with a deliberately narrow default. The header
is now only attached to destinations whose hostname matches:
dashscope.aliyuncs.com
dashscope-intl.aliyuncs.com
*.dashscope.aliyuncs.com
*.dashscope-intl.aliyuncs.com
*.alibaba-inc.com
*.aliyun-inc.com
This is exactly the set where the LLM provider, the upstream telemetry
backend (ARMS Tracing), and qwen-code itself are the same legal entity —
mirroring the first-party claude-code pattern and preserving the real
product value (server-side trace stitching against DashScope) without
exposing the session id to third parties.
Operators with broader correlation requirements override via:
"telemetry": {
"sessionIdHeaderHosts": ["*"] // restore broadcast
"sessionIdHeaderHosts": [] // fully disable
"sessionIdHeaderHosts": ["api.example.com", "*.foo"] // custom allowlist
}
Implementation:
- NEW `telemetry/trusted-llm-hosts.ts`: `DEFAULT_SESSION_ID_HEADER_HOSTS`
+ `matchesTrustedHost(hostname, patterns)` + `extractRequestHost(input)`.
Pattern syntax is intentionally tiny (bare hostname OR `*.suffix`,
dot-anchored to reject `evil-alibaba-inc.com` style attacks). Unit-tested
in dedicated test file including TLD/sub-domain attack vectors.
- `wrapFetchWithCorrelation` (openai + anthropic providers): resolves the
allowlist at wrap time (Config snapshot), inspects each request's
destination URL inside `correlationFetch`, falls through to baseFetch
for non-trusted destinations. Wildcard escape hatch via `["*"]`.
- `staticCorrelationHeaders` (Gemini factory): now takes an optional
`destinationUrl` and applies the same host gate. The Gemini SDK default
endpoint `generativelanguage.googleapis.com` is NOT on the default
allowlist, so vanilla Gemini calls receive no header — matching the
"first-party only" scope. Operators who put the Gemini SDK on a
DashScope-compatible endpoint via `baseUrl` get the header naturally.
- `Config.getTelemetrySessionIdHeaderHosts()` getter +
`TelemetrySettings.sessionIdHeaderHosts` interface field + JSON schema
entry in `settingsSchema.ts`. Wired through `resolveTelemetrySettings`.
- Defensive optional-chaining + try/catch on the Config getter call at
wrap time so partial test mocks (or pre-getter Config implementations)
fall back to the default allowlist rather than crashing buildClient.
Tests: 12 new cases covering host match/skip on default allowlist,
sub-domain handling, TLD-suffix attack rejection, `["*"]` broadcast
override, `[]` full-disable, custom operator allowlist, unparseable
destination (fail closed), and the three Gemini factory paths
(googleapis.com default → omit; DashScope `baseUrl` → inject; custom
allowlist → inject).
Docs updated in `docs/developers/development/telemetry.md` Session
correlation header section, including override examples and the new
Gemini host-gate semantics.
Closes the LaZzyMan REQUEST_CHANGES blocker. The cross-vendor
fingerprint-broadcast failure mode is now opt-in rather than default,
restoring the first-party-only semantics that make the claude-code
precedent applicable.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): R5 review fixups — Vertex destination + ["*"] trim + docs
Self-review pass on commit 1c8528a56 (host-scoped session-id header):
1. **Vertex AI destination guessing**
(geminiContentGenerator/index.ts)
`@google/genai` routes to `{region}-aiplatform.googleapis.com` (not
`generativelanguage.googleapis.com`) when `vertexai: true` and no
`baseUrl`. The previous "guess generativelanguage" default would have
mis-bucketed Vertex traffic under any operator-supplied allowlist that
covered the public Gemini endpoint but not the Vertex one. Today
invisible (both off the default allowlist), but a latent gotcha for
operators tuning `telemetry.sessionIdHeaderHosts`.
Fix: pass `undefined` when `config.baseUrl` is unset (fail-closed —
no header). Operators who want correlation against Google endpoints
must set `baseUrl` explicitly, which is also the SDK's input for
destination resolution.
2. **`["*"]` broadcast escape hatch tolerates whitespace**
(llm-correlation-fetch.ts)
`[" * "]` (a settings.json hand-edit with a stray space) previously
silently fell back to "no host matches" — the opposite of operator
intent. Now `.trim()` before comparing, so common whitespace mistakes
still trigger broadcast.
3. **Doc note on wrap-time allowlist snapshot**
(llm-correlation-fetch.ts JSDoc)
The session id is read live per-request, but `trustedHosts` is
snapshotted once at `wrapFetchWithCorrelation` call time. Spell this
out in the JSDoc so a future maintainer doesn't read the live
`getSessionId()` and assume the allowlist is the same shape.
4. **Defensive test coverage**
(trusted-llm-hosts.test.ts, llm-correlation-fetch.test.ts)
Added: extractRequestHost with explicit port / userinfo / query /
fragment / IPv6 bracket form. Whitespace `[" * "]` broadcast test.
IPv6 case documents the "bracketed → never matches" behavior is
intentional fail-closed for the named-host allowlist scope.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* chore: regenerate settings.schema.json for sessionIdHeaderHosts
Lint check `Check settings schema is up-to-date` failed because the
checked-in `packages/vscode-ide-companion/schemas/settings.schema.json`
wasn't regenerated after adding `telemetry.sessionIdHeaderHosts` to
`settingsSchema.ts` in commit 1c8528a56. Regenerated via
`npm run generate:settings-schema`.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(design): update telemetry-outbound-propagation design for R3 host-allowlist scoping
Adds a "修订历史" header table at the top and a new §11 "R3 修订 —
Host-Allowlist Scoping for X-Qwen-Code-Session-Id" capturing what changed
after LaZzyMan's REQUEST_CHANGES review, why, and how. Inline pointers
added at §3.1, §3.2, §4.3, §4.4, §9 (claude-code comparison table) to
point readers at §11 — original prose preserved as a record of the
decision path rather than rewritten in place.
Concretely §11 covers:
- The three-step LazzyMan critique and why R1's "broadcast to all
providers" was structurally wrong for an open-source multi-provider CLI
- The default allowlist (`DEFAULT_SESSION_ID_HEADER_HOSTS`) and its
semantic alignment with the DashScope provider detector
- Pattern grammar (bare hostname / `*.suffix` dot-anchored), the
TLD-suffix attack vectors it rejects, why no regex / port-aware globbing
- `wrapFetchWithCorrelation` host gate, wrap-time vs request-time
semantics, `[" * "]` whitespace tolerance
- `staticCorrelationHeaders` `destinationUrl` parameter, Gemini factory's
fail-closed treatment of unset `baseUrl` (avoids the Vertex
vs `generativelanguage.googleapis.com` ambiguity)
- All R3 file changes mapped to the original §5 file-change list
- Mapping of LazzyMan's three concerns to R3's responses
- §10 future-work additions: `traceparent` per-destination toggle,
`X-Qwen-Code-Request-Id`, IPv6 allowlist syntax
No code changes; documentation only.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): defensive allowlist normalization + positive proxy test
Three issues found by wenshao reviewing the R3 host-allowlist scoping.
1. **[Critical] `broadcastAll` outside safety try/catch**
(llm-correlation-fetch.ts wrapFetchWithCorrelation)
The try/catch only fires when `getTelemetrySessionIdHeaderHosts()`
throws. If it returns a malformed value — a bare string (settings.json
typo `"sessionIdHeaderHosts": "host"` instead of `["host"]`), an array
containing `null`/`undefined`/number entries, or whitespace-padded
entries — `.some((p) => p.trim() === '*')` throws TypeError at
buildClient time, bricking the LLM session before the first prompt.
`staticCorrelationHeaders` already handled this via its end-to-end
try/catch but the sister helper diverged. Settings loader does no
runtime schema validation so this is reachable via a single typo.
Fix: normalize the allowlist at wrap time:
1. catch a throwing getter (existing)
2. reject non-array → default allowlist (NEW — bare string typo)
3. filter out non-string elements (NEW — [null, ...] typo)
4. trim every surviving entry uniformly (NEW — see #2 below)
Then `trustedHosts.includes('*')` instead of `.some((p) => p.trim() === '*')`,
since patterns are already pre-trimmed.
2. **Trim asymmetry between `*` detection and host-pattern match**
(llm-correlation-fetch.ts)
`[" * "]` was tolerated (trimmed before `===` compare) but
`[" dashscope.aliyuncs.com "]` silently never matched. The
normalization above fixes this by trimming uniformly upstream.
3. **Proxy fetch test: only negative assertions**
(openaiContentGenerator/provider/default.test.ts)
The test asserted `callArg.fetch !== proxyFetch` and `!== globalThis.fetch`
but both passed for ANY wrapper, including a buggy one that
accidentally wraps globalThis.fetch instead of proxyFetch. Added a
positive assertion: call the wrapped fetch and verify proxyFetch was
the delegation target.
Tests: 4 new cases — whitespace-padded host pattern, bare-string
malformed config (both wrapper and static), null/number-containing
array malformed config (both wrapper and static), positive proxy fetch
delegation. All pass; pre-existing Anthropic User-Agent failure
unrelated.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor(telemetry): split outbound correlation out of telemetry scope (R4)
Address LaZzyMan round-8 follow-up review on PR #4390: even though R3's
host allowlist made the default behavior safe, the meta-architectural
concern remains: telemetry's namespace and consent flow shouldn't quietly
extend to wire-level behavior aimed at third-party LLM provider request
streams. The recipient sets differ; the consent decisions differ; they
deserve separate namespaces, separate threat models, separate PRs.
This commit (called R4 in the design doc) collapses the PR scope so it
lands ONLY telemetry observability work:
REMOVED from this PR:
- packages/core/src/telemetry/llm-correlation-fetch.ts(.test.ts)
- packages/core/src/telemetry/trusted-llm-hosts.ts(.test.ts)
- telemetry.sessionIdHeaderHosts setting + Config getter +
resolveTelemetrySettings wiring + settingsSchema entry
- wrapFetchWithCorrelation usage from four provider construction
points (default.ts, dashscope.ts, anthropicContentGenerator.ts,
geminiContentGenerator/index.ts)
- All session-id provider tests across the four providers + the
contentGenerator.test.ts mock stub
- "Session correlation header" section in telemetry.md
ADDED:
- OutboundCorrelationSettings interface in packages/core/src/config/config.ts,
standalone top-level namespace separate from TelemetrySettings —
SECURITY-RELEVANT label, all defaults off
- Config.getOutboundCorrelationPropagateTraceContext() getter
- outboundCorrelation top-level entry in settingsSchema.ts with
propagateTraceContext: { default: false } and explicit
SECURITY-RELEVANT framing in the description
- CLI config-load pipeline passes settings.outboundCorrelation into
ConfigParameters
- NOOP_PROPAGATOR (TextMapPropagator no-op) in sdk.ts, conditionally
installed on NodeSDK when propagateTraceContext is false (default).
When true, omits textMapPropagator from NodeSDK options so the SDK
keeps its default W3C composite propagator
- 2 new sdk.test.ts cases covering the propagator gate behavior
UNCHANGED:
- UndiciInstrumentation registration + OTLP feedback-loop guard +
HttpInstrumentation OTLP guard from R2/R3 stay intact — they are
pure telemetry (client HTTP spans into the operator's own OTLP
collector), no wire-level data egress
- Documentation rewrites telemetry.md to split "client-side HTTP
span on outbound fetch" (telemetry) from a new "Outbound
correlation (SECURITY-RELEVANT)" top-level section
- design doc gets R4 revision row + new §12 "R4 Scope Conflation
Split" capturing the rationale and follow-up PR outline
The session-id apparatus (R3 code) lives in git history at commits
1c8528a56 / cb162e716 / 7a1b4f8d0 / 40e1efc1f / 106598ca2; the
follow-up PR can cherry-pick or restore those files under the new
outboundCorrelation.* namespace as LazzyMan suggested.
Vscode-ide-companion settings.schema.json regenerated.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(telemetry): disclose telemetry.enabled dependency on propagateTraceContext
Self-review pass on R4 commit 9bdd3bd6f flagged one footgun: both
`docs/developers/development/telemetry.md` and the settingsSchema.ts
description for `outboundCorrelation.propagateTraceContext` describe
the toggle's behavior without noting that the flag is a silent no-op
when `telemetry.enabled` is false. An operator who sets only
`outboundCorrelation.propagateTraceContext: true` and forgets the
telemetry switch gets zero behavior change — no error, no warning, no
traceparent.
Fix: add the dependency disclosure to both surfaces, plus a JSON
example showing both flags wired together for the ARMS+DashScope
cross-process trace continuation use case.
Also fix a minor comment accuracy nit at `sdk.test.ts:683`: said the
SDK installs `W3CTraceContextPropagator` instance when opt-in is true,
but the actual default is `CompositePropagator(W3CTraceContextPropagator
+ W3CBaggagePropagator)` per `@opentelemetry/sdk-node` source.
Vscode-ide-companion settings.schema.json regenerated to reflect the
expanded description string.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(config): cover getOutboundCorrelationPropagateTraceContext defaults
R4 (commit 9bdd3bd6f) added the getter but the test file didn't grow a
corresponding describe block — sibling telemetry getters all have unit
tests but this new one was missed.
Add 4 cases covering the security-relevant default-to-false invariant
and explicit-set behavior:
- omitted outboundCorrelation → false
- empty outboundCorrelation: {} → false (the `?? false` collapse on the
getter, complementing the same on the constructor)
- explicit true → true
- explicit false → false
PR #4390 review (wenshao).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(design): reflect post-R4 polish commits in §12
R4 (commit 9bdd3bd6f) was followed by two polish commits that the
design doc §12 didn't track:
- 0be0df270 (docs): telemetry.enabled dependency disclosure on
propagateTraceContext — added to telemetry.md + settingsSchema
description because a self-review pass identified the silent-no-op
footgun (operator sets propagateTraceContext: true but forgets
telemetry.enabled: true, sees zero behavior change with no error).
- c0352fd5b (test): 4 config.test.ts cases covering the
getOutboundCorrelationPropagateTraceContext default-false invariant
(omitted / {} / explicit true / explicit false) — wenshao review
flagged the test gap.
Updates §12.4 with a new "Hidden dependency: telemetry.enabled" sub-
section explaining the gating relationship and pointing forward at the
follow-up PR (future outboundCorrelation.* settings inherit the same
dependency). Updates §12.5 implementation table to add the
config.test.ts row and clarify the telemetry.md / vscode-schema rows
were touched again in the polish pass.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor: simplify post-R4 polish per /simplify review
/simplify review pass on commits 0be0df270 + c0352fd5b + 62cf6b4ee
flagged 4 concerns. Fix all 4:
1. **settingsSchema.ts description**: footgun warning ("Depends on
telemetry.enabled: true") was at char 600+ of a 650-char description.
VS Code settings UI truncates to ~300 chars inline → the most
important warning was hidden in the most-glanced view. Hoist to first
sentence ("Requires telemetry.enabled: true.").
2. **config.test.ts**: drop the task-narration comment
("PR #4390 R4: keep wire-level toggle out of telemetry namespace.")
that just restated the change context. The remaining 2-line comment
explaining WHY default-to-false is security-relevant survives.
3. **config.test.ts**: collapse 4 separate `it()` blocks into a single
`it.each([...])` covering the same 4 precondition × expectation
combinations. Removes boilerplate (`new Config({...baseParams, ...})`
repeated 4×) without losing assertion power; case-3 ("explicit false")
was a weak duplicate of case-2 ("empty object") since both hit the
same `?? false` branch, but keeping all 4 in the parametric table
documents intent more clearly than dropping case-3.
4. **design doc §12.4 + §12.5**: strip specific commit SHAs
(`0be0df270`, `c0352fd5b`) — design docs should be evergreen, not
doubled-up commit logs (those live in `git log`). Keep the design
intent ("two panels both document the dependency" / "test block
added") without naming the specific commits.
Regenerated vscode-ide-companion/schemas/settings.schema.json to
reflect the hoisted description sentence.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(core)!: redesign auto-compaction thresholds with three-tier ladder
Replaces the single 70% proportional threshold with a three-tier ladder
(warn/auto/hard) that combines proportional fallback with absolute
reservation. Large-window models (>=128K) now reserve ~33K instead of
30% of the window, freeing tens of thousands of context tokens that the
old formula wasted.
Other improvements bundled in the same redesign:
- Compression sideQuery now disables thinking and caps maxOutputTokens
at 20K, matching claude-code so the buffer math is predictable across
providers (Anthropic/OpenAI/Gemini handle thinking budgets
inconsistently)
- Failure handling upgraded from one-shot permanent lock to a 3-strike
circuit breaker; reactive overflow still latches immediately
- New estimatePromptTokens helper closes the lag-by-one-turn and
first-send-is-0 gaps in lastPromptTokenCount
- Hard-tier rescue pulls reactive overflow recovery forward to before
the API call, saving an oversized round-trip
- /context command displays the three-tier ladder + current tier
- tipRegistry's context-* tips track the new thresholds instead of
fixed 50/80/95 percentages
BREAKING CHANGE: chatCompression.contextPercentageThreshold setting is
removed. Settings files containing the field log a one-line deprecation
warning at startup and the value is ignored; behaviour is now controlled
by built-in thresholds via the new computeThresholds() function.
Design: docs/design/auto-compaction-threshold-redesign.md
Plan: docs/plans/2026-05-14-auto-compaction-threshold-redesign.md
* test(core): fix leftover hasFailedCompressionAttempt option in compress test
A pre-existing test case at chatCompressionService.test.ts:678 still
passed `hasFailedCompressionAttempt: false` in the CompressOptions
shape; rebasing onto current main surfaced this as a typecheck error
because the field was renamed to `consecutiveFailures` (Task 7 of the
three-tier ladder migration). Update to `consecutiveFailures: 0` —
semantically equivalent, the test asserts the side-query is called
when `force: true`, no other behaviour change.
* fix(core): drop compaction summary when output hits maxOutputTokens cap
Adds a defensive guard in ChatCompressionService.compress() that detects
when the side-query summary hit COMPACT_MAX_OUTPUT_TOKENS (20K). In that
case the summary is likely truncated mid-content, so we drop it and
return NOOP rather than persist a half-summary. The next send re-tries;
reactive overflow still catches the catastrophic case where the API
rejects the next request as too large.
Documented in the design doc as risk #2; the bot reviewer on PR #4168
correctly pushed for it to land alongside the threshold redesign rather
than as a follow-up since the new 20K cap is what makes truncation
likely in the first place.
* fix(cli): render three-tier thresholds in /context TUI view
The Task 11 redesign updated the non-interactive text formatter
(formatContextUsageText) but left ContextUsage.tsx — the interactive
React component that real /context users see — unchanged. As a result
the TUI still showed the old single "Autocompact buffer" line and none
of the new warn/auto/hard ladder.
Adds a "Compaction thresholds" section after the per-category breakdown:
- Effective window
- Warn / Auto / Hard threshold rows with a ▶ marker on the row the
current usage has crossed
- Current tier label coloured by severity (safe→green, warn/auto→
yellow, hard→red)
The existing progress bar legend (Used / Free / Autocompact buffer)
is preserved because it's tied to the three-segment progress bar
visualisation; the new section adds the absolute numbers + tier badge
on top of that.
Caught by the tmux e2e test (PR #4168 ci-monitor follow-up). Pre-fix
the assertion 'Compaction thresholds' missed completely from the TUI;
post-fix the new section renders correctly for fresh and live sessions
on 1M / 200K / 128K windows.
* fix(core,cli): address PR #4168 review batch 4
Behavior fixes:
- MAX_TOKENS truncation guard now returns COMPRESSION_FAILED_EMPTY_SUMMARY
instead of NOOP so the consecutive-failure breaker actually trips after
repeated max-length summaries (R1.1).
- Reactive overflow failure increments consecutiveFailures by 1 instead
of latching to MAX in one shot, so a transient network blip doesn't
permanently disable auto-compaction. The hard-tier rescue resets the
counter, which remains the designated recovery path (R1.2).
- /context current-tier classification uses rawOverhead (system + tools +
memory + skills) as the tier input when API data is not yet available,
rather than 0 — large inherited contexts no longer silently show 'safe'
(R2.2).
Performance:
- sendMessageStream computes effectiveTokens ONCE and passes it through
TryCompressOptions.precomputedEffectiveTokens, so the cheap-gate inside
service.compress doesn't redo the estimation. Also fixes the
imageTokenEstimate inconsistency between the rescue and cheap-gate
paths (R1.3 + R1.4).
- Steady-state path (lastPromptTokenCount > 0) skips the costly
getHistory(true) clone — estimatePromptTokens only needs the user
message in that branch.
Code hygiene:
- BYTES_PER_TOKEN → CHARS_PER_TOKEN (inputs are char counts, not byte
counts; CJK text would mislead under the old name) (R3.1).
- Drop dead getContextUsagePercent helper + index re-export — no callers
in source after the threshold rewire (R1.5).
- Add a comment on estimatePromptTokens' first-send fallback documenting
the ~15-20K under-estimate (system prompt + tools + skills) and that
reactive overflow is the safety net (R3.3).
Tests:
- New CLI ContextUsage.test.tsx exercises the React renderer for the
three-tier section: section presence, ▶ marker placement per tier,
current-tier label coloring (R1.6).
- New chatCompressionService.test.ts case pins that a stale
contextPercentageThreshold: 0 value in user settings no longer
short-circuits compaction (R2.1).
- New tokenEstimation.test.ts case covers functionResponse (distinct
nested-parts branch from functionCall) (R3.5).
- New geminiChat.test.ts integration test exercises the real
ChatCompressionService — not a mock — for the first-send-after-
inherited-history scenario where lastPromptTokenCount=0 and only the
full-history estimate can cross the auto threshold (R3.4).
Declined: R3.2 (change `>=` to `>` on the MAX_TOKENS guard). The current
operator catches the at-cap case as suspicious, which is intentional —
landing exactly at the output cap is far more likely truncation than
clean stop given p99.99 ≈ 17K. With R1.1 in place, persistent truncations
trip the breaker after MAX_CONSECUTIVE_FAILURES so the worst case is
bounded.
* fix(core,cli): address PR #4168 review batch 5
- R5.1: tighten /context tier comment + TODO. The rawOverhead-based fix
doesn't cover `--continue` restores with many history messages (since
rawOverhead excludes messagesTokens). UI may still show 'safe' for one
render until the first send. Documented inline and added a TODO to plumb
chat history into collectContextData for same-source-of-truth as the
cheap-gate.
- R5.2a: add TODO(finish_reason) at the truncation guard. The `>= cap`
heuristic false-positives on legitimate at-cap summaries; the proper
signal is finish_reason which runSideQuery doesn't surface today.
- R5.2b: split telemetry — new CompressionStatus.COMPRESSION_FAILED_OUTPUT_TRUNCATED
enum value. Distinct from EMPTY_SUMMARY so logs/telemetry can tell
prompt-quality failures (tune prompt / splitter) from capacity failures
(raise cap / shrink splitter input). isCompressionFailureStatus()
treats both as failures so the breaker behavior is unchanged.
- R5.3: expand consecutiveFailures JSDoc to clarify it tracks
"non-force, non-hard-rescue consecutive failures" — hard-rescue resets
the counter and force=true skips increments, so the counter is the
"regular path" health signal only; reactive overflow is the real
safety net for the force-only paths.
- R5.4: document the CompressOptions field rename
(hasFailedCompressionAttempt: boolean → consecutiveFailures: number)
as an SDK breaking change in the design doc with migration guide.
* fix(core): disambiguate hard-rescue from manual /compress orphan-strip
Self-review (dual reviewer / pr-triage round 1) caught a correctness
regression in the hard-rescue path:
`sendMessageStream` calls `tryCompress(force=true)` from inside the
pre-push window when `effectiveTokens >= hard`. The service's
orphan-strip predicate at `chatCompressionService.ts:426-429` gated on
`force` alone, which conflated two distinct call shapes:
- manual `/compress` (force=true, trigger='manual'): user-initiated
between turns; trailing model funcCall IS orphaned because no
funcResponse is coming
- hard-rescue (force=true, trigger='auto'): automatic mid-turn;
trailing model funcCall is ACTIVE because its matching funcResponse
is sitting in the pending `userContent` waiting to be pushed
The strip fired for both, so a hard-rescue triggered mid tool-use loop
would drop the active funcCall. After compression returned and
`userContent` (the funcResponse) was pushed, the next API request
carried tool_result with no matching tool_use → provider validation
error.
The in-code comment at L422-424 already documented this exact
constraint for the auto-compress case (`force=false`), but reusing
`force=true` for hard-rescue silently violated the same constraint.
Fix:
- Gate `hasOrphanedFuncCall` on `compactTrigger === 'manual'` instead
of `force`. The trigger field already disambiguates intent.
- `sendMessageStream` hard-rescue now passes `trigger: 'auto'`
explicitly (without it, `force=true` defaults to `trigger='manual'`
via the `?? (force ? 'manual' : 'auto')` resolver).
Sibling audit for "force=true non-manual callsites":
- `GeminiClient.tryCompressChat` (manual /compress): correct — manual
- `sendMessageStream` hard-rescue: fixed in this commit
- `sendMessageStream` reactive overflow catch: already passes
trigger='auto'; runs AFTER API call (userContent in history), so if
it observes a trailing funcCall it IS orphaned but findCompressSplitPoint
handles the case without needing the strip
RED-first regression test added:
`preserves trailing model+funcCall under hard-rescue (force=true + trigger=auto)`
in `chatCompressionService.test.ts`. Failed against pre-fix code (the
strip dropped the funcCall); passes against the fix.
Adjacent fixes from the same triage round:
- `docs/users/configuration/settings.md`: the
`chatCompression.contextPercentageThreshold` row still said "use 0
to disable compression entirely" — code has ignored the value since
the removal commit. Marked the row REMOVED with migration guidance
pointing at the design doc.
- `packages/core/src/config/config.ts`: the deprecation warning now
tells users how to silence it (remove the key) and where to read
current behavior, instead of just announcing the removal.
- `docs/design/auto-compaction-threshold-redesign.md`: closed Open
Question 2 (small-window hard/auto collapse) — decision is to NOT
annotate `/context`, with rationale on file.
Tests: 2395 core tests passing, typecheck clean.
* docs(core): fix tier-collapse direction in auto-compaction design doc
Self-review on the 50bac974b commit caught a direction error in the
M2a Open Question 2 closure note: said `currentTier` skips `'hard'`
and goes to `'auto'` on collapsed windows, which is backwards.
`contextCommand.ts:43-44` checks `tokens >= thresholds.hard` first
(no `hard > auto` guard — that fix lives in a separate follow-up), so
when `hard === auto` the `'hard'` branch matches first and the
`'auto'` band is the empty one. Updated the rationale to describe the
actual collapse direction and cite the source-of-truth file:line.
Conclusion of the open question (don't annotate `/context`) is
unchanged — only the explanation is corrected.
* refactor(core): extract shared in-flight funcCall fixture in compression tests
The auto-compress and hard-rescue tests for "trailing funcCall is
active, not orphaned" shared a byte-identical 4-message history and
mock setup. Pull both into setupInFlightFuncCallFixture() inside the
describe block so each test only contains the scenario name, the
compress() call shape, and its own assertions.
Net -29 LOC, no behavior change.
* fix(core,cli): address PR #4345 round-2 review feedback
- geminiChat: remove pre-call consecutiveFailures reset in hard-rescue.
force=true already bypasses the breaker check in chatCompressionService;
the pre-reset was redundant on success (post-call L614 already handles it)
and *broke* the breaker on failure paths — hard-rescue failures don't
increment via tryCompress (force=true skips that branch), only the
reactive overflow path at L992 explicitly increments. With the pre-reset
the counter oscillated 0↔1 every send and MAX_CONSECUTIVE_FAILURES=3 was
unreachable. Wrote a RED test asserting the forwarded counter is the
latched value, not zero; the test failed against the old code and passes
with the reset removed.
- geminiChat: log hard-tier-rescue triggers via debugLogger.warn including
effectiveTokens, hard, and the current consecutiveFailures so operators
debugging "compaction stopped working" have a breadcrumb.
- chatCompressionService: clamp effectiveWindow to >= 0 in computeThresholds
so the value surfaced in /context stays meaningful for tiny windows
(window < SUMMARY_RESERVE). auto/warn/hard outputs are unaffected because
each is Math.max(proportional, absolute) and the proportional branch
dominates whenever the absolute branch goes negative.
- turn.ts: rewrite COMPRESSION_FAILED_OUTPUT_TRUNCATED docstring. Drop the
misleading "compression succeeded" framing (the summary is dropped and
isCompressionFailureStatus returns true) and reference the full enum name
COMPRESSION_FAILED_EMPTY_SUMMARY instead of the abbreviation.
- contextCommand.test.ts: reword the no-API-data-session test comment.
collectContextData classifies estimated sessions against rawOverhead;
with default fixtures rawOverhead lands in `safe`, but heavy
system-prompt / skill / MCP loads can push it into warn/auto/hard.
- design doc Background: prepend a blockquote clarifying the section
describes pre-redesign behavior and that the inline file:line references
point at code before PR #4345 (which removes them).
- ui/types: replace the duplicated ContextThresholds interface with a
type alias to the core's CompactionThresholds. Field-by-field copy in
contextCommand.ts becomes a direct spread. ContextUsage.tsx keeps its
CompactionThresholds React component name — the alias avoids the
collision a direct import would have caused.
- contextCommand: interpolate the actual reserve value into the
"(window − 20K reserve)" annotation so SUMMARY_RESERVE retuning doesn't
leave the text stale.
* fix(core): address PR #4345 round-3 + round-4 review feedback
R3-1: rewrite the stale "Hard-tier rescue resets the counter" comment in
the reactive-overflow path. The R2 commit removed the pre-call reset
from hard-rescue; the only counter-reset path is now the post-call
COMPRESSED branch in tryCompress. Two contradicting comments in the
same file would mislead a future maintainer tracing the lifecycle.
R3-2: rewrite the JSDoc on CompactionThresholds.hard. The "(resets
failure counter)" phrasing was true under the pre-R2 design; after R2
the hard threshold force-triggers compaction and bypasses the breaker,
but does not reset the counter (which only happens on COMPRESSED
success via the post-call branch). The type is consumed by both
geminiChat and the CLI UI (via ContextThresholds alias), so the
authoritative description had to match the actual contract.
R3-3: add a Step 3 to the hard-rescue regression test. The test title
claims "success recovers via the post-call branch" but the original
Steps 1-2 only verified the latched counter was forwarded INTO the
call. Step 3 follows up with a below-hard send and asserts the
forwarded counter is 0 — proving geminiChat.ts:614 ran on the
COMPRESSED result.
R3-4: assert effectiveWindow === 0 on the existing extreme-small-window
test and add a separate zero-window edge case. The Math.max(0, ...)
clamp from R2 was previously unasserted; a regression that removed
the clamp would go undetected.
R4-1: forward originalTokenCount on the breaker-NOOP path in
chatCompressionService.compress() to match the adjacent
threshold-NOOP path (L368-369). Returning {originalTokenCount: 0,
newTokenCount: 0} masked "breaker tripped at N tokens" as
"empty session" in telemetry dashboards.
R4-2a: add debugLogger.warn at the two consecutiveFailures increment
sites (cheap-gate path L586 and reactive-overflow path L955) when
the counter reaches MAX_CONSECUTIVE_FAILURES. The breaker is one of
the PR's headline safety features but, prior to this round, had zero
observability when it tripped. Required importing MAX_CONSECUTIVE_FAILURES
into geminiChat.ts.
R4-3: programmatically link tokenEstimation.ts's CHARS_PER_TOKEN to
compactionInputSlimming.ts's TOKEN_TO_CHAR_RATIO. Both are 4 today
and represent the same generic char/token conversion. Exporting from
compactionInputSlimming and aliasing in tokenEstimation eliminates
the silent-drift hazard the JSDoc already warned about.
Declined (round-weighted bar at round 4):
- R3-5: debugLogger test for hard-rescue trigger — observability test
coverage is overthinking at round 3+; the log is informational.
- R4-2b: expose breaker state in /context — new feature; out of scope.
- R4-4: render test for auto-tier marker — test coverage gap on
working code, defer to follow-up PR per round-weighted bar.
- R4-5a: extract makeFakeChat/makeFakeConfig shared factory — pure
test refactor at round 4, not a fix.
- R4-5b: direct unit test for precomputedEffectiveTokens — exercised
indirectly via hard-rescue path tests in geminiChat.test.ts.
- R4-6: truncation-guard fallback test for missing candidatesTokenCount
— code already has a TODO acknowledging the heuristic is imperfect
(chatCompressionService.ts:549-553); defer.
* fix(core): address PR #4345 round-5 review feedback
R5-1: assert breaker-NOOP forwards originalTokenCount. R4-1 changed the
breaker-NOOP return from `{0, 0}` to `{originalTokenCount, originalTokenCount}`
so telemetry can distinguish "breaker tripped at N tokens" from
"empty session", but the existing test only checked compressionStatus
and newHistory. Now seeds a non-zero originalTokenCount (120K) and
asserts both fields forward it.
R5-2: forward originalTokenCount on the empty-history NOOP. This was
sibling drift on R4-1 — I fixed the cited breaker-NOOP site but missed
the empty-history NOOP. Of 5 NOOP return sites in chatCompressionService,
4 now forward originalTokenCount (breaker, threshold-gate, post-split,
min-compression-fraction) and 1 (this one) was still returning `{0, 0}`,
breaking the project-wide invariant. Now consistent.
R5-3: replace 10 stale line-number references with semantic anchors.
After the R3+R4 push, the line refs in my R2/R3 comments (`geminiChat.ts:614`,
`chatCompressionService.ts:339`, `line 992`, `L627`, `line 944`) no longer
pointed at their original targets — `geminiChat.ts:614` now points at
`setSystemInstruction`'s body, completely unrelated to compaction. The
pattern itself is fragile; semantic phrasing ("the post-call reset in
tryCompress's COMPRESSED handler") doesn't drift when lines shift.
347/347 affected core tests passing locally; typecheck clean.
* fix(core): address PR #4345 round-6 review feedback (R6 sweep)
R6-1: rewrite the stale JSDoc bullet on `consecutiveFailures` (the
"Hard-tier rescue failures" bullet). The old wording said "the counter
is reset to 0 BEFORE the rescue call" — that contradicted R5 which
explicitly removed the pre-call reset. Now the bullet matches the
actual behavior: counter is NOT pre-reset, force=true bypasses the
breaker, post-call COMPRESSED handler resets on success, reactive
overflow is the explicit-increment safety net.
My R5 stale-comment sweep only grep'd inline `//` comments; this JSDoc
on the field declaration slipped through. Re-audited "reset to 0
BEFORE" / "pre-reset" across both packages — single site remaining.
R6-7: assert `passedOpts.trigger === 'auto'` in the hard-rescue test.
This field is the orphan-strip safety wire added by the C1 fix (the
service's `compactTrigger === 'manual'` check would otherwise strip
the trailing active funcCall mid tool-loop). The test asserted force
and pendingUserMessage but not the trigger; a refactor dropping the
'auto' from `trigger: shouldForceFromHard ? 'auto' : undefined` would
silently break orphan-strip safety. Now regression-guarded with a
single-line expect.
164/164 affected core tests passing locally.
Declined per round-weighted bar (round 6 defaults Suggestion / Test
coverage / Style to overthinking):
- R6-2/3/6: test-coverage gaps on working code — defer to follow-up
- R6-4: redundant truthy guard on always-set fields — style nit
- R6-5: text-vs-UI inconsistency on /context — existing test enforces
current behavior; treat as design decision (offer follow-up if
reviewer escalates)
- R6-8 (tipRegistry small-window context-high): explicitly closed in
design doc's Open Question 2 — small windows have empty context-high
band by design; UI work is out-of-scope for this PR
- R6-9: wasted clone on rare fallback path — Suggestion-level perf
- R6-10 (CompressionMessage missing case): file not in this PR's diff;
reviewer themselves proposed it as follow-up
Replace useReducer with useRef + useState + synchronous dispatch so that
event handlers always read the latest buffer state. Previously, rapid
input via tmux send-keys could deliver characters and Enter in the same
event loop tick; the Enter handler read buffer.text from a stale render
closure (empty string) because useReducer's dispatch only enqueues
actions for the next render pass.
The fix runs the reducer synchronously at dispatch time, stores results
in a useRef for immediate reads, and calls setState to trigger
re-renders. The returned TextBuffer object exposes text, lines, and
cursor as getters reading from stateRef.current, so all consumers
(BaseTextInput, InputPrompt, vim hook) automatically get fresh values
without code changes.
* feat(cli): do not append trailing space for directory completions (#4092)
## What
在 @路径补全和 /dir add 命令的目录补全中不再追加尾部空格。这样可以允许用户在补全目录后直接按 Tab 继续深入下一级子目录,无需先删除空格。
## Examples
- Input: `@src/com` + Tab → Output: `@src/components/` (no trailing space)
- Input: `/dir add ./pac` + Tab → Output: `/dir add ./packages/` (no trailing space)
- File completions still append a space (e.g., `@src/file.txt `)
## Changes
- Added `isDirectory` flag to `Suggestion` and `CommandCompletionItem` interfaces
- Updated `handleAutocomplete` to skip trailing space when `isDirectory === true`
- Modified `getDirPathCompletions` to return `CommandCompletionItem[]` with `isDirectory: true`
- Added test case for directory completion behavior
* fix(cli): append trailing / to directory completions for deeper navigation
* fix(cli): propagate isDirectory and fix JSDoc comment
## Comment 2: Fix JSDoc in SuggestionsDisplay
Removed "(ends with /)" from isDirectory description since it was factually incorrect.
## Comment 3: Add test for isDirectory propagation
- Added test suite in useSlashCompletion.test.ts to verify directory command structure
- Real filesystem testing is done in directoryCommand.test.tsx
* fix(cli): add comprehensive isDirectory propagation tests
Added getDirPathCompletions unit tests that verify:
- Directory suggestions include isDirectory: true
- Directory values end with / for continued navigation
- Prefix filtering preserves isDirectory flag
- Comma-separated path completion works correctly
- Deeply nested directories maintain isDirectory flag
This closes the testing gap identified in review comment 3.
* fix(cli): address wenshao feedback - lint rules, real test, cross-platform
Fixes 4 new review comments from wenshao:
- [Critical] Empty catch {} blocks: guarded with if (tempTestDir) + void err
- [Critical] useSlashCompletion.no-op test: replaced with real integration test that
verifies isDirectory propagation through toSuggestion pass-through
- [Suggestion] Windows path separator: using path.sep instead of hardcoded /
in both directoryCommand.tsx and related test assertions
* fix(cli): remove unused import and fix Windows path separator in tests
- Remove unused directoryCommand import in useSlashCompletion.test.ts (TS6133)
- Replace hardcoded / regex with path.sep-aware assertions in
directoryCommand.test.tsx to fix Windows CI failures
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* Apply suggestion from @wenshao
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* Update packages/cli/src/ui/commands/directoryCommand.test.tsx
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* Update packages/cli/src/ui/commands/directoryCommand.tsx
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* Update packages/cli/src/ui/commands/directoryCommand.tsx
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* fix(cli): normalize isDirectory to explicit boolean in toSuggestion
Normalize isDirectory from three-state (true/false/undefined) to explicit
boolean (true/false) to prevent latent bugs in future code that might
distinguish between false and undefined.
Fixes review comment: isDirectory normalization is inconsistent across
completion paths.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* Update packages/cli/src/ui/hooks/useSlashCompletion.ts
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* chore: remove accidentally committed pr_body.md
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* chore: add pr_body.md to .gitignore
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(cli): remove duplicate .slice and orphaned test code from directoryCommand.tsx
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(cli): only suppress trailing space for dir completions at end-of-line
When isDirectory is true, the trailing space was suppressed unconditionally,
even when the cursor is mid-line. This caused directory completions to merge
directly with following text (e.g. '@src/components/something').
Now only suppress the space when the cursor is at end-of-line, allowing
continued Tab navigation into subdirectories.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* docs(cli): document crawler path separator dependency for isDirectory check
The isDirectory detection uses p.endsWith('/') which depends on the
crawler in @qwen-code/qwen-code-core normalizing paths with posix '/'
(fdir.withPathSeparator('/') in crawler.ts). Add a comment to make this
implicit coupling explicit.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* test(cli): add mid-line directory completion test
Verify that directory completions append a trailing space when the cursor
is mid-line, preventing the completed path from merging with following text.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* Update packages/cli/src/ui/hooks/useCommandCompletion.test.ts
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
---------
Co-authored-by: 方磊 <fanglei@192.168.1.11>
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com>
* fix(cli): gate mintty OSC 8 detection on TERM_PROGRAM_VERSION ≥ 3.3 (#4420)
mintty added OSC 8 in 3.1 and hardened it in 3.3. Older builds — still
bundled with some Git-for-Windows distros and developer environments like
Laragon — print the raw `\x1b]8;;url\x07` bytes as visible garbage instead
of silently ignoring them.
The previous unconditional `case 'mintty': return true` deviated from the
upstream `supports-hyperlinks` library (which rejects all of win32 outside
WT_SESSION) and let those old mintty users see escape bytes in their UI.
Gate on TERM_PROGRAM_VERSION (set by mintty since 2.7 in 2017 — a missing
value implies an ancient build, so we refuse rather than guess). Users on
mintty 3.1–3.2.x who know their build works can still opt in with
FORCE_HYPERLINK=1.
This fixes the OSC 8 component of #4420 (the "garbled UI on Windows + Git
Bash" report). The Ink 7 render interaction and terminalRedrawOptimizer
angles flagged in the same triage need separate Windows-environment
testing; `QWEN_CODE_LEGACY_ERASE_LINES=1` remains the documented escape
hatch for those.
* test(cli): assert FORCE_HYPERLINK=1 escape hatch works on gated mintty
Mirrors the Warp/Hyper pattern: after asserting auto-detection rejects an
older mintty build, set FORCE_HYPERLINK=1 and verify it opts back in. The
PR description for #4451 documents this contract for users on mintty
3.1–3.2 who know their build's OSC 8 implementation works; pinning it as
a test guards against a future refactor reordering the early-exit checks.
Addresses review feedback on #4451.
* fix(cli): stabilize flaky sticky-todo remeasure test (#4415)
Replace absolute mock.calls.length assertion with mockClear() +
not.toHaveBeenCalled() in the sticky todo status-only update test.
The previous assertion captured the total measureElement call count
after initial render, rerendered, and checked the count was unchanged.
This was flaky on CI (macOS runner) because React 19's Ink test
renderer can invoke useLayoutEffect a variable number of times during
mount (StrictMode double-invoke, multiple reconciliation passes),
making the absolute count unreliable across environments.
The new approach resets the mock after initial render and asserts no
new calls occur during rerender — clearly expressing the test intent
and eliminating environment-dependent flakiness.
* fix(cli): stabilize flaky sticky-todo remeasure test
Replace fragile measureElement call-count assertion with a behavioral
assertion on availableTerminalHeight stability, wrapped in act() to
flush useLayoutEffect timing.
The original test asserted that measureElement was not called after
rerender when only todo status changed (pending -> in_progress). This
was flaky because:
1. The absolute mock.calls.length count was environment-dependent
(React 19 StrictMode double-invoke, variable reconciliation passes)
2. Even with mockClear(), the useLayoutEffect fires for legitimate
reasons (buffer ref, btwItem) unrelated to sticky todo status,
especially on Windows CI runners
3. The controlsHeight state (useState(0)) races with useLayoutEffect's
first measurement — mainControlsRef.current may be null on initial
render, causing controlsHeight to settle at different times
The fix:
- Assert on availableTerminalHeight (the behavioral outcome exposed via
UIState context) rather than measureElement call count
- Wrap render + rerender in act() to ensure useLayoutEffect and
setControlsHeight fully settle before capturing the baseline
- Consolidate duplicate react imports
* test(cli): address review feedback on sticky-todo remeasure test
- Narrow the `mockConfig.initialize` stub from `beforeEach` (which flipped
`isConfigInitialized` for ~75 tests in the block) back to the single test
that needs it. Other tests now exercise the real init gate as before.
- Strengthen the behavioral assertion: switch `measureElement`'s mocked
return value between the settle phase and the status-only rerender, so
any re-measurement triggered by the status change would change
`controlsHeight` and break the equality assertion. Without this, the
production same-value short-circuit on `setControlsHeight` made the
assertion pass even when the optimization regressed.
The core layout-key contract (status-only changes return the same key) is
already directly covered by `todoSnapshot.test.ts` — this integration test
provides layered protection on top.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
---------
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(core): persist partial assistant turn when stream errors mid tool_use
Weak-network failures during an Anthropic-compatible stream (DeepSeek,
api.anthropic.com, etc.) can drop the SSE between a tool_use
`content_block_stop` and the terminal `message_stop`. The functionCall
chunk is already yielded at content_block_stop, so:
- Turn.run records a ToolCallRequest event.
- useGeminiStream's for-await exits and schedules the tool.
- handleCompletedTools eventually fires submitQuery(..., ToolResult)
and pushes a user[functionResponse] into history.
- But processStreamResponse's history.push for the model turn never
ran (the for-await threw first), so the matching tool_use is gone.
The next request body has `user → user[tool_result]` with no tool_use
in between, and the server rejects with HTTP 400:
"tool_use_id ... must have a corresponding tool_use block in the
previous message". Ctrl+Y can't recover because
stripOrphanedUserEntriesFromHistory only strips trailing user
entries — the lost tool_use is unrecoverable, and the session is
wedged.
Wrap the for-await loop in processStreamResponse with try/catch.
When the stream throws AND any functionCall chunk was already
yielded (hasToolCall=true), persist the partial assistant turn to
history before re-throwing. The eventual tool_result submission
then has a matching tool_use and the session can continue.
Plain-text partial turns (no functionCall yielded) are intentionally
NOT persisted: the Retry path pops the trailing user prompt and
re-issues it, so a stale partial-text model turn between them would
either bias the retry or surface as duplicate output.
* test(core): cover thinking+tool_use mid-stream throw in partial-history fix
Adds a third case to the partial-history persistence test suite for
reasoning-mode providers (DeepSeek thinking, Claude 4.6+ adaptive): when
the assistant turn streams a thinking block AND a tool_use before the
SSE drops, the partial push must keep the thinking part before the
functionCall so DeepSeek's `injectThinkingOnToolUseTurns` converter
pass sees an existing block on the replayed turn and does not pre-pend
a synthetic empty one (which would discard the model's original
reasoning text).
* fix(core,cli): close tool_use↔tool_result invariant at failure points
Extends the partial-history fix in fe35e3778 to cover the residual race
paths surfaced in PR #4176 review:
- Race A: Ctrl+Y while in-flight tool hasn't finished. History is
[user, model(tool_use)] — `stripOrphanedUserEntriesFromHistory` only
pops trailing user entries, so the retry payload lands as a fresh
user turn after the orphan tool_use and API rejects. Meanwhile the
scheduler's `onAllToolCallsComplete` is single-shot and gated on
`isResponding`, so the eventual tool_result is silently swallowed.
- Race B: process crash / OOM / SIGKILL between the partial-tool_use
push and the React scheduler's tool_result submission. On `--resume`
the dangling model(tool_use) wedges the first API call.
- Race C: external tooling / manual JSONL edits leaving the same
dangling shape.
The fix has three pieces working together:
1. `repairOrphanedToolUseTurns(history)` in geminiChat.ts walks history
left-to-right and synthesizes an `error`-typed functionResponse for
every functionCall whose id is not echoed back in the next user
turn. Appends to an existing user turn when present, otherwise
inserts a new one. Returns the injected (callId, name) list.
2. `GeminiClient.repairOrphanedToolUseTurnsInHistory()` wraps the helper
and is called from three points:
- `startChat()` after loading the transcript (Race B/C, --resume).
- `sendMessageStream` Retry branch after stripOrphans (Race A).
- `sendMessageStream` UserQuery/Cron branch (defensive belt-and-
suspenders for anything that slipped past 1 and 2).
3. `handleCompletedTools` in useGeminiStream.ts dedupes against
chat.history before submitting tool_results — if a synthetic
functionResponse for the same callId is already present (planted by
the repair pass), the in-flight scheduler's late result is dropped
and the call is `markToolsAsSubmitted` so the UI advances. Same
trade-off upstream Claude Code's `StreamingToolExecutor.discard()`
makes — late real results are dropped on the wire after synthesis,
the model sees the synthetic error and can retry the tool if it
still wants the result.
Together with the partial-history push from fe35e3778, every tool_use
that ever streamed to the consumer is guaranteed to have a matching
tool_result on the wire — regardless of whether the stream errored,
the user retried mid-flight, the process crashed, or the session is
later resumed. This is the qwen-code analogue of upstream Claude Code's
`yieldMissingToolResultBlocks` (query.ts:123-149), but split across
the core/cli boundary because the React tool scheduler runs out-of-band
from the stream loop (so the synthesis path can't atomically discard
in-flight tools the way upstream's StreamingToolExecutor can; the
history-dedup at handleCompletedTools fills that gap instead).
Tests:
- 8 new repair-helper tests in geminiChat.test.ts cover Race A,
Race B, partial coverage of parallel tool_use, idempotence on
already-paired history, no-op on tool-free history, caller-
supplied reason text, multiple non-adjacent dangling rounds, and
routes through the GeminiChat instance-method wrapper.
- client.test.ts mocks updated for the new GeminiChat method.
- All 88 geminiChat tests pass; 131 client tests pass; 91
useGeminiStream tests pass.
* fix(core,cli): close tool_use↔tool_result invariant at failure points
Post-review audit of 3de3241a2 surfaced two real races the earlier fix
did not actually close:
- Race A (the one yiliang114 originally flagged): handleCompletedTools
is gated on `isResponding` (useGeminiStream:1971) BEFORE the dedup
branch ran, so when the user Ctrl+Y'd mid-tool, the dedup never
fired and the in-flight tool stayed permanently stuck in
`completed-but-not-submitted` (the scheduler's
`allToolCallsCompleteHandler` is single-shot). The dedup branch was
structurally unreachable on the very race it was meant to defend
against.
- Race in the Retry path: the repair pass in
`client.sendMessageStream` Retry branch ran BEFORE the chat-internal
`push(userContent)`, so a Retry of a previous ToolResult submission
(lastPrompt is a functionResponse part array) raced its own real
`functionResponse` against the synthesized error one. The synthesis
was winning and pre-empting the real result, producing two
`functionResponse` entries with the same callId on the wire.
This commit relocates both pieces to where the contract actually holds:
1. Move the dedup branch in `handleCompletedTools` to BEFORE the
`isResponding` early-return so `markToolsAsSubmitted` always runs
for callIds already paired in history, unblocking the UI/scheduler
even when a new stream is in flight. The submission-side `geminiTools
= completedAndReadyToSubmitTools.filter(... && !inHistory ...)` then
covers the no-double-submit case in one expression.
2. Move the repair call from `client.sendMessageStream` Retry branch
into `chat.sendMessageStream` immediately AFTER the user-supplied
turn is pushed. The user's own tool_result (when the Retry payload
carries one) gets the first chance to close the pair before the
synthesizer sees it as dangling. `client.startChat()` keeps a
belt-and-suspenders pass at session-load time so any pre-send code
reading `chat.history` sees a well-formed shape.
Adds three integration tests covering the new wiring:
- geminiChat.test.ts: chat.sendMessageStream synthesizes a
functionResponse when history carries a dangling tool_use AND the
user-supplied content doesn't already close it (Race B/C plus
Race A from the chat side).
- geminiChat.test.ts: chat.sendMessageStream does NOT synthesize
when the user-supplied content IS a matching functionResponse
(the Retry-of-ToolResult race the previous wiring tripped on).
- useGeminiStream.test.tsx: handleCompletedTools dedups a late real
result whose callId already has a functionResponse in chat.history
(Race A end-to-end: markToolsAsSubmitted fires but no
submitQuery is dispatched).
Test summary: 90/90 geminiChat, 131/131 client, 92/92 useGeminiStream;
all 8186 core tests pass; tsc clean.
Known limitation logged for follow-up: a Retry of ToolResult whose
intervening stream itself partial-pushed a SECOND tool_use produces a
trailing user turn with both the stale re-pushed `fr_A` and the
synthesized `fr_B` for the second call — `fr_A` retry lands as an
orphan because `fc_A` was already paired earlier in history. Triggered
only when partial-push fires on the second stream AND user retries the
tool_result rather than the user prompt; extremely low frequency in
practice. Cleanest fix is in the retryLastPrompt layer (don't re-push
an already-paired tool_result), which is out of scope for this PR.
* fix(core,cli): close tool_use↔tool_result invariant at failure points
Review surfaced four issues on top of b2fed61cd. All addressed here:
- [P0] Synthetic functionResponse was appended to the trailing user
turn's parts; on a Ctrl+Y race the shape became `user[text, fr]` and
Anthropic-compatible backends still 400 because tool_result blocks
must come FIRST in a user message (Claude Code does the same hoist
in utils/messages.ts:hoistToolResults). Repair now slots synthetic
fr in before the first non-functionResponse part, after any
pre-existing real fr parts (which preserves real-tool-result order
on a parallel-partial-submit). Tests asserting the part order added.
- [P0] The dedup test fixture in useGeminiStream.test.tsx forced an
incompatible object through a direct cast to TrackedCompletedToolCall;
`tsc` rejected it with TS2352. Fixture restructured to match the
type's actual shape (matches the existing `Mocked` patterns at
L597-606 / L2396-2401) so the changed-file typecheck stays green.
- [P1] On stream error, `recordAssistantTurn` ran unconditionally
(gated only on parts being non-empty), so partial text-only turns
we intentionally do NOT push into in-memory history were still
written to the chat-recording JSONL — leaving --resume's
transcript-load path to re-inject a model turn the in-session run
discarded. Gate now matches the `history.push` decision: record
iff we will persist (success path OR stream-error-with-tool_use).
- [P2] Added client-level tests for the startChat repair wiring:
extraHistory ending in `model[functionCall]` triggers synthetic fr
injection on init; happy-path resume is a no-op. Defends against a
future reorder/removal of the call in startChat() regressing the
--resume recovery path.
All 91 geminiChat, 133 client, 92 useGeminiStream tests pass. Full
core suite (8186 tests) green. Changed-file tsc clean except for the
pre-existing `recordCompletedToolCall` typing gap that exists on main.
* fix(core): roll back partial assistant push on retryable mid-stream errors
Regression surfaced by @yiliang114 on PR #4176: a stream attempt that
yields a `functionCall` and then throws a retryable error (e.g.
`StreamContentError` with a 429 payload, or `InvalidStreamError`)
triggers the partial-assistant-turn push in `processStreamResponse`,
but the outer `sendMessageStream` retry loop catches the error and
issues a fresh attempt. The failed-attempt `model[functionCall]` was
left in history, and the successful retry's response landed as a
SECOND consecutive `model` entry — invalid user/model alternation
AND the failed-attempt `tool_use` is orphan on the wire (no matching
tool_result). The very wedge this PR is meant to escape.
Track the index of the pushed partial in a new
`pendingPartialAssistantTurnIndex` field, reset it on every
`sendMessageStream` entry, and pop it before each retry-and-continue
path in the catch block (rate-limit, reactive-compression, transient
stream anomaly, content-validation retry). Paths that `break`
(unretryable) keep the partial — the caller will see it as part of
the error surface and the existing repair / dedup machinery in
`useGeminiStream.handleCompletedTools` handles it correctly.
The pop is defensive (index-bounds + role check) so a hypothetical
intervening `setHistory` / `truncateHistory` can't cause an out-of-
bounds splice.
Adds a regression test in `geminiChat.test.ts` that reproduces
@yiliang114's exact shape: yield `functionCall`, throw
`StreamContentError(429)`, second attempt yields `Success after retry`
plain text + STOP. Asserts the final history is exactly
`[user, model(success text)]` — no leading failed-attempt model turn,
no orphan `functionCall` anywhere.
All 92 geminiChat, 133 client, 92 useGeminiStream tests pass; full
core suite green; tsc clean.
* fix(core): clear pendingPartialAssistantTurnIndex on history replacement
Audit follow-up to db344a403. The retry-rollback marker
`pendingPartialAssistantTurnIndex` captures an absolute index into
`this.history`, but `setHistory` / `clearHistory` / `truncateHistory`
wipe or shift the underlying array without touching the marker. Two
paths where this can bite:
- Reactive compression on contextOverflow calls `this.setHistory(
newHistory)` inside `tryCompress`. If a partial push has happened
earlier (extreme edge case — would require a partial push followed
by a context-overflow on retry), the marker's stale index could
coincide with a model entry in the compressed history, and
`popPartialIfPushed` would splice the wrong turn.
- `/clear` / `--resume` / programmatic `setHistory` / external
`chat.truncateHistory()` (Session.ts:244) wipe the basis the marker
was captured against, leaving the next send's
`popPartialIfPushed` with a meaningless index.
The fix is mechanical: each history-replacement method clears the
marker. The marker is per-send and ephemeral, so losing it across a
history replacement is safe (the next send either has no partial yet,
or will push a fresh one with a fresh index).
`popPartialIfPushed` already bounds-checks + role-checks before
splicing, so this is defense-in-depth — the bug above requires the
defensive check to ALSO line up. But cheap to harden and the comment
documents the invariant for future readers. 235 core/geminiChat +
core/client tests still pass.
* fix(core,cli): close mimo-v2.5-pro review gaps on partial-tool_use repair
Four review items from the mimo-v2.5-pro pass on #4176:
S1 — `addHistory` and `stripThoughtsFromHistory` did not reset
`pendingPartialAssistantTurnIndex`. `setHistory`/`truncateHistory`/
`clearHistory` already do; consistency with the defensive pattern
matters because `stripThoughtsFromHistory` filter+map produces a new
array that makes the marker stale, and any future addHistory variant
that splices into the middle could leave `popPartialIfPushed` looking
at a wrong index. Comments updated to record the actual semantics
(plain push() is safe; a future splicing variant would not be).
S2 — When the history-based dedup in `useGeminiStream.handleCompletedTools`
filters a tool out of `geminiTools` because its callId is already paired
in chat.history, `recordCompletedToolCall` was never called for it.
That silently skips the `toolCallCount` increment and the
`skillsModifiedInSession` flip — the latter gates the skills-reload
prompt at end-of-turn, so a deduped `write_file` under a project
SKILLS path would never trigger a reload. Now records inline with the
dedup mark, filtered to non-client-initiated to match the original
geminiTools loop's shape.
S3 — Existing Race A dedup test never set `isResponding=true`, so a
future refactor that moves the dedup block below the `if (isResponding)
return` guard would pass every test while silently leaving deduped
tools stuck in `completed-but-not-submitted` (the scheduler's
`onAllToolCallsComplete` is single-shot per batch). New test holds a
stream open via `submitQuery` to pin `isResponding=true`, then triggers
`onComplete` and asserts `markToolsAsSubmitted` still fires. Verified
the test fails when the dedup is moved below the guard. Existing
Race A test also gained a `recordCompletedToolCall` assertion locking
in the S2 fix.
N1 — Hoisting comment in `repairOrphanedToolUseTurns` documented the
why (mirror upstream `hoistToolResults`) but not the consequence of
removal. Added "CONSEQUENCE OF REMOVAL" paragraph spelling out the
exact 400 a naive `next.parts = [...existing, ...syntheticParts]`
re-introduces, so the constraint is unmissable for future maintainers.
Verified: 94/94 useGeminiStream, 102/102 geminiChat, 133/133 client
tests pass. tsc clean both packages, eslint + prettier clean on all
three changed files. S3 regression-injection check confirmed the new
test catches the dedup-below-guard regression.
* fix(core): defer chat-recording flush until partial-turn rollback decision
Yiliang114's PR #4176 follow-up: `popPartialIfPushed()` rolls a
failed-attempt's `model[functionCall]` out of in-memory `this.history`
before retrying, but the same partial turn was already appended to the
chat-recording JSONL by `recordAssistantTurn()`. After a successful
retry, live history was clean while the durable transcript still
carried two assistant entries — the failed attempt and the success.
`--resume` then rehydrated the failed `model[functionCall]` and the
resumed model context picked up a tool_use the live session correctly
discarded.
Fix: the recording call on the stream-error + hasToolCall path is now
deferred. processStreamResponse stashes the would-be record on a new
`pendingPartialAssistantRecord` field instead of immediately appending.
The retry loop's `popPartialIfPushed` clears the stash alongside the
in-memory splice — no flush, no leak. Once the retry loop has settled
(success-break: stash already null; unretryable-break: partial
survived), a flush hook right after the for-loop appends the stashed
record to JSONL so the transcript matches whatever lives in
`this.history`. The success path (streamError === null) still records
immediately as before — only the at-risk-of-rollback path is deferred.
Lifecycle is paired one-to-one with `pendingPartialAssistantTurnIndex`:
set together, popped together, flushed together, and reset in every
history-replacement method (sendMessageStream entry, setHistory,
clearHistory, truncateHistory, addHistory, stripThoughtsFromHistory)
so an exotic path can't leak a stale stash into a future send's flush.
Two regression tests in geminiChat.test.ts:
1. "rolls back the chat-recording entry too when the retry succeeds"
— failing-then-succeeding stream sequence asserts
`recordAssistantTurn` is called exactly once with the success
text, no functionCall part anywhere in the recorded message.
Verified the test fails (mock called twice) when the deferral
branch is bypassed.
2. "flushes the chat-recording entry on the unretryable break path"
— synthetic non-retryable error after a tool_use chunk asserts
the partial IS recorded so the JSONL stays aligned with the
in-memory partial that survives. Verified the test fails
(mock called zero times) when the post-loop flush is removed.
Tests: 104/104 geminiChat (+2 new), 133/133 client, 94/94
useGeminiStream. tsc + eslint + prettier clean.
* fix(core,cli): close 4 deepseek-v4-pro review threads on PR #4176
Four follow-ups from the deepseek-v4-pro pass on commit 2dbfc4e3b:
[A] useGeminiStream.ts — dedup recordCompletedToolCall now skips
cancelled tools. `dedupedTools` includes anything in a terminal state
(success | error | cancelled), but cancelled means the tool never
actually produced model-visible output. Counting it via
`recordCompletedToolCall` would inflate `toolCallCount` and could flip
`skillsModifiedInSession` for a never-executed skill-write. The
markToolsAsSubmitted call still fires so the scheduler unblocks.
Mirrors the rationale of the existing `allToolsCancelled` branch which
surfaces non-deduped cancellations via addHistory + reportCancelled
rather than the completed-call metric.
[B] client.ts — JSDoc on `repairOrphanedToolUseTurnsInHistory` claimed
three call points (startChat, Retry submit path, defensive
UserQuery/Cron pass) but in practice this method is only called once
from `startChat()`. The other two coverage points live one layer down
inside `GeminiChat.sendMessageStream` and call the standalone
`repairOrphanedToolUseTurns(history)` function directly without
routing through this wrapper. Updated to reflect the actual coupling.
[C] geminiChat.ts — `addHistory` now warns via debugLogger if it
clears a non-null partial-push marker. Today's callers
(useGeminiStream cancelled-tool synthesis, ACP session injects,
shellCommandProcessor) only run between sends, so the marker is null
on entry. If a future code path calls addHistory between the partial
push and the retry attempt, the silent clear would strand the
partial: popPartialIfPushed would no-op, the failed model[functionCall]
would survive into the retry, and a successful retry's response would
land as a SECOND consecutive model turn — the wedge this whole
subsystem exists to prevent. The warn surfaces the offending caller in
the log instead of forcing a blind trace through the marker lifecycle.
[D] geminiChat.ts — extracted `clearPendingPartialState()` helper
covering all 7 sites that need to reset both
`pendingPartialAssistantTurnIndex` and `pendingPartialAssistantRecord`
in lockstep (sendMessageStream entry, popPartialIfPushed, the
post-loop flush hook, clearHistory, addHistory, setHistory,
truncateHistory, stripThoughtsFromHistory). The two fields ARE always
paired by lifecycle (set together on stream-error stash, popped
together on retry, flushed together at the rethrow site), so any
single-field reset would be a bug. The helper makes the lockstep
invariant explicit and means a future history-mutating method can't
forget to clear one field.
Regression test: useGeminiStream.test.tsx adds
"skips recordCompletedToolCall for deduped CANCELLED tools" — sets up
a deduped cancelled tool with callId paired in history, asserts
markToolsAsSubmitted IS called (scheduler unblocks) but
recordCompletedToolCall is NOT called. Verified the test fails when
the cancelled-filter line is removed (regression-injection check).
Tests: 237/237 core, 95/95 useGeminiStream (+1 new). tsc + eslint +
prettier clean. Existing CI failure on Test (ubuntu-latest, Node 22.x)
is an unrelated timing flake in promptHookRunner.test.ts
("expected 49 to be greater than or equal to 50") — macOS and Windows
both pass.
* fix(core): close 3 review threads on partial-tool_use repair (PR #4176)
Three follow-ups from the qwen-latest-series-invite-beta-v28 pass on
commit fd12639c9:
[E] CORRECTNESS — `repairOrphanedToolUseTurns` now scans EVERY
consecutive `user` turn after a `model[functionCall]` (not just
`history[i+1]`) when building the matched-id set. The shape
`model[fc], user[text], user[fr_real]` arises when a user aborts a
long-running tool, types a follow-up text turn, and the React
scheduler's late `submitQuery` appends the real `tool_result` as a
SEPARATE user entry. Previously the repair saw only the immediate
follow-up text turn, found no matching fr, and synthesized a duplicate
`error` `functionResponse` for a callId that already had a real result
two turns down. The downstream dedup in
`useGeminiStream.handleCompletedTools` then dropped the REAL result on
the next submission (its callId was now "already in history" thanks to
the synthetic), and the model only ever saw the error placeholder —
silently swapping a real tool success for an error.
Two regression tests in `geminiChat.test.ts`:
- "does NOT synthesize when the real functionResponse lives in a
non-adjacent later user turn" — proves the forward-scan finds the
real fr at history[i+2]+ and skips synthesis.
- "still synthesizes for a partial mismatch when forward scan misses
one callId" — counterpart that confirms parallel tool_use shapes
where only some callIds have real fr's still get synthetic ones
hoisted onto the immediate next user turn.
Verified via regression-injection (revert to scanning only
`history[i+1]`): the non-adjacent test fails with `injected =
[{callId:'call_nonadjacent_real',...}]` — proves the test catches the
bug, not just verifies a no-op.
[F] OBSERVABILITY — added a `[PARTIAL_PUSH]` `debugLogger.warn` at the
partial-turn push site in `processStreamResponse`. The repair lifecycle
already had push/pop/repair logging at the dedup and synthesis ends
(`[REPAIR] Dropping ...`, `[REPAIR] Synthesized ...`), but the original
PUSH event — root cause of every downstream recovery — was unlogged.
At 3 AM investigating a stale-partial wedge, the trace now anchors at
the exact moment the partial was created with pendingIndex, callIds,
and the originating error message.
[G] INVARIANT — `stripOrphanedUserEntriesFromHistory` now calls
`clearPendingPartialState()` after popping. Today this is safe even
without the reset (only trailing `user` entries are popped, which
can't shift the index of an earlier `model` partial), but every other
history-mutation method in the class — `clearHistory`, `addHistory`,
`setHistory`, `truncateHistory`, `stripThoughtsFromHistory` — now
clears the partial-push state in lockstep. Omitting it here would be
a silent exception to the uniform invariant the helper extraction
established. A future caller invoking this between the deferred JSONL
flush and the next `sendMessageStream` would otherwise leave a stale
marker that happens to line up with whatever model entry is at that
index in the meanwhile.
Tests: 239/239 core (+2 new), 95/95 useGeminiStream. tsc + eslint +
prettier clean. Latest CI run: all three platforms (Linux/macOS/
Windows) green.
* fix(core): close 6 review threads on partial-tool_use repair (PR #4176)
Six follow-ups from the qwen-latest-series-invite-beta-v28 + gpt-5.5
passes on commit 2880de577:
[A] CORRECTNESS — `repairOrphanedToolUseTurns` now HOISTS a real
`functionResponse` from a non-adjacent later user turn into the
IMMEDIATE next user turn (placed before non-fr parts), in addition to
the forward-scan dedup added in 2880de577. The shape `model[fc],
user[text], user[fr_real]` arises when a user aborts a long-running
tool, types a follow-up text turn, and the React scheduler's late
`submitQuery` appends the real `tool_result` as a SEPARATE user entry.
Forward-scan alone correctly skipped the synthesis duplicate, but the
wire layout still serialized `model[tool_use] → user[text] →
user[tool_result]`, which Anthropic-compatible backends reject with
"tool_use_id ... must have a corresponding tool_use block in the
previous message". The hoist physically moves the real fr part out of
its original turn into history[i+1], drops the source turn if it
becomes empty, and reuses the existing front-of-user-turn
insertion logic so caller-supplied fr ordering stays preserved.
Hoisted ids are NOT added to `injected` — the real fr is already in
history (just relocated), so the React scheduler's history-based
dedup handles them naturally without an extra entry that would
double-trigger the dedup-drop log.
Three new tests in `geminiChat.test.ts`:
- "hoists the real functionResponse from a non-adjacent later user
turn into the adjacent one" — pure relocate case (source turn had
only the fr → removed).
- "synthesizes missing fr AND hoists real fr in a parallel tool_use
mismatch" — parallel `model[fc_a, fc_b]` with real fr_a in a
non-adjacent turn: cid_b synthesized, cid_a hoisted, source turn
removed.
- "hoists real fr but preserves the source user turn when it
carries other content" — pins the empty-turn cleanup so it only
drops turns whose parts list goes to zero (mixed text + fr source
keeps its text after the fr is extracted).
[B] CRITICAL — moved the deferred chat-recording flush from BEFORE the
max-tokens escalation block into the outer `finally`. The escalated
`makeApiCallAndProcessStream → processStreamResponse` can set a NEW
`pendingPartialAssistantRecord` if it errors mid-tool_use, and that
throw escapes through the for-await without touching the (now-passed)
retry-loop catch. Before this fix the new record was never appended
to JSONL: live history retained the partial `model[functionCall]`
that the escalated processStreamResponse pushed, but the durable
transcript silently dropped it; on `--resume` the transcript-load
path didn't see the partial, `repairOrphanedToolUseTurnsInHistory`
found nothing to repair, and the React scheduler's late real result
became a permanent orphan — reproducing the exact wedge this PR
prevents. Putting the flush in `finally` covers all throw paths
(escalation, post-retry-loop `throw lastError`, consumer `.return()`)
and the normal completion path with one statement, while keeping the
"marker and stash cleared in lockstep" invariant.
One new regression test: "flushes the JSONL record when escalated
stream throws mid-tool_use" — pins the flush behavior under the
specific shape (initial MAX_TOKENS success → escalation cuts mid-
tool_use → throw). Asserts both that the partial survives in
`this.history` and that `recordAssistantTurn` got called with the
partial functionCall id.
[C] DOC — updated `repairOrphanedToolUseTurns` doc comment to spell
out both fix-ups (synthesize + hoist), the wire-format consequence of
removal ("tool_use_id ... must have a corresponding tool_use block"),
and the rule that hoisted ids are not in the returned `injected` list.
The previous "immediately following user turn" wording contradicted
the forward-scan implementation; the new wording matches the actual
behavior across both fix-up paths.
[D] OBSERVABILITY — inline `repairOrphanedToolUseTurns` call in
`sendMessageStream` now logs `[REPAIR] sendMessageStream inline pass
synthesized N functionResponse(s) ...` when synthesis fires. The
startChat() path already logs via `repairOrphanedToolUseTurnsInHistory`
(`[REPAIR] Synthesized ...`), and `useGeminiStream.handleCompletedTools`
logs `[REPAIR] Dropping ...` on dedup. Without a tagged log at the
inline call site, an investigator looking at a dedup-drop had no way
to tell whether the synthetic was planted at session-load or at the
per-send pass.
[E] OBSERVABILITY — `popPartialIfPushed` now logs `[PARTIAL_POP]
Splice skipped` when the marker is set but `history.length <= idx` or
`history[idx]?.role !== 'model'`. This can't happen today (every
history-mutation method clears the marker in lockstep), but the warn
makes any future regression observable rather than silent: a
mutation path that forgets to clear would otherwise leave a stale
partial in history with no diagnostic trace.
[F] CLARITY — added a comment at the post-`tryCompress`
`popPartialIfPushed()` call explaining the intentional defense-in-
depth no-op. `tryCompress()` succeeds → `setHistory()` →
`clearPendingPartialState()`, so the marker is null by the time the
pop runs. The call is kept (not removed) so a future refactor that
switches `tryCompress` to in-place mutation would still drop the
stale partial before `requestContents` is rebuilt.
Tests: 336/336 (108 in geminiChat.test.ts + 4 new = +4; 95
useGeminiStream + 133 client unchanged). tsc + eslint + prettier
clean on changed files.
* fix(core,cli): close 10 review threads on partial-tool_use repair (PR #4176)
Five Critical + four Suggestion threads from the gpt-5.5 +
qwen-latest-series-invite-beta-v34 passes on commit ce68749b5, plus
one N/A documented in code/test comments where the requested test
target is provably unreachable.
[A] CORRECTNESS — `repairOrphanedToolUseTurns` now collects EVERY
location for each `functionResponse` id, not just the first.
Previously the `matched` Map stored only the first occurrence per
callId, so when the same id was echoed back more than once across
the consecutive user turns (shape `model[fc id=cid], user[text],
user[fr cid], user[fr cid]` — possible when the React scheduler
retries the late submitQuery after the orphan repair already planted
one, or two parallel late-submit paths land), hoisting only the
first left a duplicate behind. The wire payload then serialized
`model[tool_use] -> user[tool_result] -> user[tool_result]`, the
backend rejected the trailing block as an orphan, and the session
stayed wedged for the same 400 class this whole repair pass exists
to escape. Fix: track all locations per id; pick the first as the
canonical survivor (hoisted into history[i+1] when non-adjacent, or
left in place when adjacent), and drop EVERY duplicate. New tests:
"drops duplicate functionResponse entries for the same callId across
user turns" (canonical non-adjacent + duplicate further down →
3-entry result), "drops duplicate fr even when the canonical copy is
already in the adjacent turn" (no hoist needed but duplicate cleanup
must still fire). gpt-5.5 review thread on PR #4176.
[B] CORRECTNESS — Max-tokens recovery catch (`recoveryError` block)
now pops the partial `model` turn FIRST, then the
OUTPUT_RECOVERY_MESSAGE user turn. Before the fix, when a recovery
stream errored AFTER yielding a `functionCall` chunk,
`processStreamResponse` pushed a partial `model` turn into history
before re-throwing — so by the time the catch ran, the trailing
entries were `[..., user(OUTPUT_RECOVERY_MESSAGE), model(partial fc)]`
and the naive `if last is user, pop` check no-op'd, stranding the
control prompt as a real user turn. Two consequences: the recovery
prompt's instructions polluted later turns, and the inline repair
on the next sendMessageStream synthesized an `error` `functionResponse`
for the dangling `functionCall` — which the dedup then dropped when
the React scheduler's REAL tool result arrived, so the model saw an
"execution result was not recorded" error for a tool that actually
succeeded. Fix: pop the partial model turn, clear the partial-push
markers, then pop the recovery user turn. New regression test:
"should pop both the partial model turn AND the recovery user
message when recovery throws after a functionCall".
qwen-latest-series-invite-beta-v34 review thread.
[C] PERFORMANCE — added `getHistoryFunctionResponseIds(): Set<string>`
to `GeminiChat` and a wrapper on `GeminiClient`. The dedup pass in
`useGeminiStream.handleCompletedTools` previously called
`geminiClient.getHistory()`, which returns `structuredClone(this.history)`
— a recursive deep clone of every part including large tool outputs.
On long sessions (200+ entries) running on every tool-completion
batch, this caused multi-millisecond stalls on the React UI thread
during streaming. The new accessor walks `this.history` in place
and only collects the id strings the dedup actually needs.
`useGeminiStream` prefers it; falls back to the cloning getHistory()
for older mocks that don't expose it (tests stay green).
qwen-latest-series-invite-beta-v34 review thread.
[D] ROBUSTNESS — wrapped the `finally`-block JSONL flush in
try/catch. Recording-service errors (disk full, write permission,
serialization failure) MUST NOT propagate out of the generator's
`finally` — that would mask the real send outcome (success or
original throw) with a JSONL-write error the caller can't usefully
act on. On failure the partial is dropped from JSONL but stays
durable in `this.history`, so live behavior is unaffected; eventual
consistency is restored on the next successful flush.
qwen-latest-series-invite-beta-v34 review thread.
[E] TEST COVERAGE — added an InvalidStreamError transient-retry
rollback test exercising `popPartialIfPushed()` on the
NO_FINISH_REASON / NO_RESPONSE_TEXT path (separate budget from the
already-tested rate-limit branch). Stream yields a functionCall
then throws InvalidStreamError; retry succeeds; assert no orphan
functionCall remains in history. qwen-latest-series-invite-beta-v34
review thread.
[F] N/A WITH RATIONALE — verified that the InvalidStreamError
content-retry branch (geminiChat.ts ~line 1399) is unreachable for
that error class: `isTransientStreamError` and `isContentError` are
the same predicate (`error instanceof InvalidStreamError`), so the
transient branch above always either continues or breaks before
control reaches the content branch. The `popPartialIfPushed()` call
is preserved as defense-in-depth for a future error class that
should diverge the predicates. Documented at the call site (code
comment) and at the would-be test site (test-block comment) so
future readers see the unreachability analysis instead of repeating
the review-comment ask.
[G] DRIFT GUARD — `recordAssistantTurn` and `this.history.push`
gates now share the single `willPersistToHistory` binding instead of
re-deriving the same `hasToolCall && (thoughtContentPart || ...)`
expression. Drift risk: tightening one without the other would
silently desync the JSONL transcript from in-memory history.
qwen-latest-series-invite-beta-v34 review thread.
[H] DOUBLE-DISPATCH — `clientTools` filter in
`useGeminiStream.handleCompletedTools` now excludes callIds whose
fr is already in history. Previously a deduped client-initiated
tool would have `markToolsAsSubmitted` called twice (once in the
dedup block, once in the clientTools block), triggering an extra
React render cycle. qwen-latest-series-invite-beta-v34 review thread.
[I] TEST COVERAGE — added six tests under "partial-push marker
invariants on history mutation" pinning that each of the six
mutation methods (clearHistory, addHistory, setHistory,
truncateHistory, stripThoughtsFromHistory,
stripOrphanedUserEntriesFromHistory) calls clearPendingPartialState()
in lockstep. Markers planted directly via private-field assignment
(the lifecycle would otherwise clear them in finally before the
test could observe them). Future refactors that drop a
clearPendingPartialState() call from one site are now caught at
test time rather than as a silent stale-partial wedge in production.
qwen-latest-series-invite-beta-v34 review thread.
[J] TEST COVERAGE — added a mixed-batch dedup test in
useGeminiStream.test.tsx: scheduler completes two tools in the same
batch, one whose callId already has an fr in history (deduped), one
fresh. Asserts (a) markToolsAsSubmitted called with both, (b)
recordCompletedToolCall fires exactly once per tool (deduped via
the dedup-loop, fresh via the geminiTools loop — no double-record
on the deduped id), (c) sendMessageStream IS called for the fresh
tool's real result. The `!historyCallIdsWithResponse.has(callId)`
filter on `geminiTools` is the only guard against double-counting
telemetry; existing tests supplied only deduped tools.
qwen-latest-series-invite-beta-v34 review thread.
Tests: 347/347 (118 in geminiChat.test.ts, 96 in
useGeminiStream.test.tsx, 133 in client.test.ts; net +8 new tests).
tsc + eslint + prettier clean on changed files.
* fix(core,cli): close 3 review threads on partial-tool_use repair (PR #4176)
Three Suggestion threads from the qwen-latest-series-invite-beta-v34
pass on commit c8fa3143f.
[A] DIAGNOSTICS — `repairOrphanedToolUseTurns` return type now
carries a `droppedDuplicates: Array<{ callId; name }>` field
alongside `injected`. Previously a duplicate-only repair (no
synthesis, no hoist — the main scenario the prior commit added)
returned `injected.length === 0` and both call sites
(`repairOrphanedToolUseTurnsInHistory` in client.ts,
`sendMessageStream` inline in geminiChat.ts) only logged on
synthesis, leaving zero diagnostic trail. If a future callId
collision bug caused the wrong `functionResponse` to be dropped,
there was no breadcrumb pointing back to the repair function. Both
call sites now emit a `[REPAIR] Dropped N duplicate functionResponse(s)`
warn line tagged with their origin (session-load vs inline per-send)
so investigators can anchor to the exact pass.
[B] DEFENSIVE INVARIANT — max-tokens recovery catch now uses an
index-checked pop instead of a positional `history.pop()`. The
semantically equivalent `popPartialIfPushed` uses
`splice(idx, 1)` with an explicit bounds/role check and a
`debugLogger.warn` on mismatch; the recovery catch was the only
rollback site that pop'd whatever model entry happened to be last,
with zero diagnostic output. Today the invariant holds (nothing
mutates `this.history` between `processStreamResponse`'s push and
the for-await catch), but a future change that inserts a mutation
in that window — compression side-effect, abort-signal handler,
telemetry hook — would silently pop the wrong entry while
`clearPendingPartialState()` cleared markers for the actual
partial, leaving it permanently stranded. The new
`[RECOVERY_POP] Marker/last-index mismatch` warn surfaces any
future violation immediately.
[C] TEST COVERAGE — added 6 unit tests for
`GeminiChat.getHistoryFunctionResponseIds()` (empty, mixed
user/model, model[fc] ignored, duplicate collapse to Set,
malformed parts, no aliasing of internal state). Also wired the
mixed-batch dedup test in `useGeminiStream.test.tsx` through the
fast-path accessor (mock returns the dedup Set directly) and
asserted that `getHistoryFunctionResponseIds` IS called and the
legacy cloning `getHistory()` is NOT. The earlier version of that
test only mocked `getHistory()`, so the optimization the previous
commit added was never actually exercised — a regression that
dropped the fast-path branch from the dispatcher would re-route
every batch onto the slow `structuredClone` path with no test
failure. The new assertion makes that regression visible.
Tests: 353/353 (124 in geminiChat.test.ts +6, 96 in
useGeminiStream.test.tsx unchanged but mock surface expanded,
133 in client.test.ts unchanged). tsc + eslint + prettier clean
on changed files.
* test(cli): route existing dedup tests through fast-path accessor (PR #4176)
One Suggestion thread from the deepseek-v4-pro pass on commit
c30bba6e7.
`MockedGeminiClientClass` did not expose `getHistoryFunctionResponseIds`,
so 3 of the 4 dedup tests in `useGeminiStream.test.tsx` fell through
to the `else if (typeof geminiClient.getHistory === 'function')`
branch — the `structuredClone(this.history)` slow path. Only the
mixed-batch test added in c30bba6e7 wired the fast path explicitly.
Net effect: a regression in `getHistoryFunctionResponseIds` (wrong
ids, missing ids, exception) would silently re-route every dedup
batch onto the slow clone path with all 4 tests still green, while
production paid the multi-millisecond UI-thread stall this PR
specifically added the accessor to avoid.
Fix in two parts:
1. Add `getHistoryFunctionResponseIds = vi.fn().mockReturnValue(new
Set<string>())` to the `MockedGeminiClientClass` default. Every
test now exposes the fast-path accessor, so the dispatcher takes
the `getHistoryFunctionResponseIds` branch by default — matching
production. Tests that need a non-empty dedup set override the
mock explicitly.
2. Override the mock in each of the three previously-affected dedup
tests with a `Set` containing the callId(s) their `getHistory()`
fixture had paired. The dedup assertions stay identical — but
the path the production code takes to reach them now matches
the path under test.
Tests: 96/96 useGeminiStream (no new tests; existing dedup tests
now exercise the fast path the previous commit added). 353/353
across core + cli. tsc + eslint + prettier clean.
* refactor(core,cli): address yiliang114 review observations (PR #4176)
Five items from the yiliang114 review on commit 06a695156. Two P1
(observability + structural maintainability) and three editorial.
[A] P1 — repairOrphanedToolUseTurns refactored into three pure
phases: scanModelTurn / planRepair / applyRepair. Each runs in
isolation against narrow `ScanResult` / `RepairPlan` types, and only
the last mutates `history`. The outer forward-walk loop is now a
~25-line orchestrator: scan → bail on empty expected → plan → bail
on empty plan → apply → record `injected` + `droppedDuplicates` →
advance cursor past any freshly-inserted user turn. Index drift can
only happen in applyRepair, so an audit narrows to one function.
Behavior identical to the pre-refactor monolith — all 13 existing
repair tests pass unchanged.
[B] P1 — finally-block JSONL flush error log promoted from
`debugLogger.warn` to `debugLogger.error`. A persistent write
failure (disk full, permission denied, serialization broken)
silently loses every deferred partial after the first occurrence;
that's the class of failure that warrants monitoring attention, not
the warn category that fades into log noise. Single-occurrence
transient failures still surface as one error per occurrence.
[C] P2 — addHistory partial-marker log promoted to `debugLogger.error`
with `[INVARIANT_VIOLATION]` tag. The existing call graph cannot
legitimately hit this branch (it only fires when addHistory runs
mid-sendMessageStream, which no current caller does); any future
hit is a true bug in a new caller, not noise.
[D] P2 — removed the `getHistory()` fallback branch in
`useGeminiStream.handleCompletedTools`. Verified via grep: every
GeminiClient consumer (real production code + MockedGeminiClientClass
+ every individual dedup test) now exposes
`getHistoryFunctionResponseIds`, so the three-branch duck-type
dispatch was dead-code at production level and only existed to
support an interim cycle when the fast-path accessor was being
introduced. The dispatcher is now a one-liner; production path is
strictly the fast accessor, with an empty Set returned if `geminiClient`
itself is missing (only happens in hook-level unit tests with no
client at all).
[E] P2 — cleanup pass dropping reviewer/thread citations from code
comments (e.g. "qwen-latest-series-invite-beta-v34 thread on PR
#4176", "gpt-5.5 review thread", "deepseek-v4-pro thread",
"yiliang114 repro"). The "why" explanations stay — those are the
load-bearing context. Reviewer/thread attribution lives in the
PR history; embedding it in long-term comments was noise that
ages poorly. Touched 9 sites in geminiChat.ts, 2 in client.ts,
1 in useGeminiStream.ts, 4 in useGeminiStream.test.tsx, and 8 in
geminiChat.test.ts (test names + comment blocks).
Also: P2.4 (yiliang114 flagged a potential test-coverage regression
on TPM throttling + Retry-After delay) verified as a false alarm
— `should retry on TPM throttling StreamContentError with initial
delay` (geminiChat.test.ts:2959) and `should use Retry-After delay
for streamed rate-limit errors` (line 3035) both still exist.
Tests: 353/353 (no new tests; all existing pass through the
refactored repair function and the simplified dispatcher). tsc +
eslint + prettier clean.
* refactor(core): consolidate partial-tool_use repair docs into one design block (PR #4176)
Addresses the pomelo-nwu review observation on c30bba6e7:
~60% of the +918 lines added to geminiChat.ts were comments, with
several 20–40 line prose blocks repeating the same race-class /
tool_use_id wedge analysis at every call site. Net –139 / +117
(net delete ~22 lines but mostly redistributing weight from per-site
blocks to a single canonical note).
Changes:
* Add one canonical design block above ORPHAN_TOOL_USE_REPAIR_REASON
covering: the tool_use_id 400 wedge, the three race classes (A
Ctrl+Y mid-flight, B process crash, C SSE drop), the two-layer fix
(partial-push + repair), and the partial-push marker lifecycle.
Every per-site comment that used to repeat this now points back.
* Trim popPartialIfPushed COMPRESSED-branch comment from 14 lines to
4 (no-op-today + reason for keeping).
* Trim recovery-catch comment block from ~38 lines to ~7 (pop-order
matters + index-checked, pointer to canonical note).
* Trim addHistory invariant comment from ~22 lines to ~5 (when this
fires + why error-level, pointer to canonical note).
* Trim processStreamResponse partial-push comment from ~22 lines to
~8 (Race C name + signal + plain-text-not-persisted rule).
* Replace tool_use_id wedge re-explanations at 5 sites (repair doc,
scanModelTurn doc, applyRepair doc, popPartialIfPushed comment,
processStreamResponse comment) with single-line pointers. Canonical
block at line 411 is now the only authoritative copy.
Reviewer marked this as non-blocking ("shouldn't gate the merge");
done as cleanup polish while LGTM is in.
Tests: 375/375 (no test changes). tsc + eslint + prettier clean.
* refactor(core): further trim partial-tool_use repair comments (PR #4176)
Second cleanup pass on pomelo-nwu's feedback. Previous commit
(298588190) cut net –22 lines but several blocks were still
20–25 lines of prose; this pass takes the rest down to the
one-or-two-line pointer pattern the reviewer suggested.
geminiChat.ts: 2384 → 2207 lines (-177). Comment density 37% → 32%.
Trimmed:
* pendingPartialAssistantTurnIndex + pendingPartialAssistantRecord
field doc blocks (16 + 22 lines → one combined 5-line block
pointing at the canonical note).
* clearPendingPartialState method doc (10 → 4 lines).
* sendMessageStream inline-repair comment block (29 → 7 lines).
* `finally` JSONL flush block (32 → 8 lines).
* repairOrphanedToolUseTurns function doc (39 → 14 lines).
* scanModelTurn / planRepair / applyRepair phase docs (11–22 → 4–9
lines each).
* RepairPlan interface doc (14 → 1 line).
* GeminiChat.repairOrphanedToolUseTurns wrapper doc (9 → 3 lines).
* GeminiChat.getHistoryFunctionResponseIds doc (13 → 6 lines).
What stayed (intentional load-bearing context):
* The canonical block above ORPHAN_TOOL_USE_REPAIR_REASON — that's
the consolidation point every per-site one-liner points back to.
* Pre-existing upstream JSDoc (ctor, sendMessageStream, getHistory,
redactStructuredOutputArgsForRecording).
* The Reactive compression no-op note (already at the 4-line cap).
* The recovery-catch 7-line block (already at the cap).
* The addHistory invariant 5-line block (already at the cap).
Tests: 375/375 pass on the affected suites. tsc + eslint + prettier
clean on changed files. Behavior unchanged.
* chore: bump version to 0.16.0 and normalize bat line endings
* revert: restore install-qwen-standalone.bat to original CRLF encoding
The previous bump commit inadvertently normalized line endings from
CRLF to LF. Windows batch files must retain CRLF in the repository
to work correctly with cmd.exe.
* revert: remove spurious NOTICES.txt change from version bump
* feat(skills): support priority field in SKILL.md for sorting skill display order
Closes#4136
* fix(skills): make /skills respect priority and treat unset as 0
- /skills was re-sorting alphabetically after listSkills(), masking the
new priority order. Drop the redundant sort and reuse the manager's
output directly.
- Treat missing priority as 0 instead of -Infinity so an explicit
negative priority (e.g. -1) sorts below unset skills, which matches
user intent.
* fix(skills): harden priority parsing and ordering
* fix(skills): warn when extension supplies invalid priority
Extension-provided skills bypass parseSkillContent / validateConfig, so a
non-number `priority` was silently normalized to 0 in the sort with zero
diagnostic. Match the SKILL.md author signal: warn at load time so the
extension author can see and fix the typo.
Addresses PR #4155 review (the extension-bypass-validation point).
* test(skills): direct unit tests for parsePriorityField and normalizeSkillPriority
Both helpers are exported but previously had no direct tests — coverage
came only via parseSkillContent and listSkills. Adds inputs the
integration paths can't surface cleanly: -0 / NaN / Infinity, numeric
strings, objects, arrays, and the boolean coercion regression that
motivated the strict typecheck.
Also adds a NOTE on parsePriorityField warning future contributors that
SKILL.md frontmatter parsing lives in two places (parseSkillContent here
and SkillManager.parseSkillContent), so any new field must be wired into
both — the same regression that previously hit whenToUse,
disable-model-invocation, paths, and priority. Full dedup of the two
parseSkillContent bodies is left as a follow-up refactor.
Addresses the remaining two [Suggestion] items from PR #4155 review.
* fix(skills): scope priority to /skills listing only
Earlier in this PR, `skill.priority` was mapped into `SlashCommand.completionPriority`
on both bundled and non-bundled skill loaders, so a high-priority skill
also bubbled up in the slash-completion menu and the `/help` custom-commands
tab. That was broader than intended — the design goal is for `priority:`
to control the `/skills` listing only, with everything else (typing `/`,
mid-input completion, `/help`) staying purely alphabetical so a skill
can't reorder built-in commands.
Changes:
- BundledSkillLoader / SkillCommandLoader: drop the
`completionPriority: skill.priority` mapping. Skill commands now have
no `completionPriority`, falling back to alphabetical+recency in the
shared completion comparator.
- Help.tsx: revert the per-group sort to `localeCompare` and remove the
`compareCommandsForHelp` helper. `/help` is again purely alphabetical
within each group.
- Tests:
- Both loader tests assert `completionPriority` is `undefined` when
a skill has a `priority` set, locking the non-leakage in.
- Help.test.tsx's "orders by completionPriority" case is replaced
with "orders alphabetically regardless of completionPriority", so a
future change that re-introduces the leak fails the test.
- Extension-skill validation also normalizes `skill.priority` to 0 (in
addition to the existing sort-time normalization) so downstream
consumers see a clean value matching the emitted warning.
Validation:
- 177/177 unit tests pass across the 5 affected test files
- core typecheck clean
- bundled CLI built (`npm run bundle`) and exercised via tmux E2E:
E1 /skills sorted by priority, E2 / completion menu unaffected,
E3 mid-input alphabetical, E4 invalid priority warns + skill loads,
E5 order stable across restart — all 5 pass.
* fix(skills): tag priority warning with calling module's namespace
`parsePriorityField` previously hardcoded `debugLogger.warn` from
skill-load, so a warning emitted from `SkillManager.parseSkillContent`
(project / user / bundled skills) was tagged `[SKILL_LOAD]` instead of
`[SKILL_MANAGER]`. Annoying for log filtering and slightly misleading
about which parse path actually surfaced the bad priority.
Added an optional `warn` callback parameter; the existing extension
call site keeps the default skill-load logger, while skill-manager
passes its own. Behavior is otherwise unchanged.
* docs(skills): correct priority scope description
Earlier doc said priority sorts "in /skills, slash-command completion,
and the /help custom commands view." After the scope-narrowing in
96722aa67, priority only affects /skills. Updating the doc to match
the actual behavior so readers don't expect cross-surface ordering.
* fix(skills): keep listSkills() alphabetical, sort priority at /skills display
`listSkills()` previously returned priority-desc order for every consumer,
including `SkillTool.refreshSkills()` which builds the model-facing
`<available_skills>` description. That contradicted the stated design goal
(`priority:` controls the `/skills` listing only) and the user docs, which
say everything outside `/skills` stays alphabetical.
- skill-manager.ts: `listSkills()` now sorts name-asc only, giving all
programmatic consumers (SkillTool, contextCommand, loaders) a stable
alphabetical order unaffected by `priority:`.
- skillsCommand.ts: apply the priority-desc, name-asc sort at the display
layer using the shared `normalizeSkillPriority`.
- skills/index.ts: export `normalizeSkillPriority` for the CLI display sort.
- Tests: core tests now lock in that `listSkills()` stays alphabetical
regardless of priority; new skillsCommand.test.ts covers the display sort.
* fix: correct copyright year 2025 -> 2026 in new file [skip ci]
* feat(telemetry): support custom resource attributes and add metric cardinality controls
Resolves#4365.
Adds two coupled OpenTelemetry capabilities to make qwen-code's telemetry
production-ready in multi-team / multi-tenant deployments:
1. Custom resource attributes via standard `OTEL_RESOURCE_ATTRIBUTES` and
`OTEL_SERVICE_NAME` env vars and a new `telemetry.resourceAttributes`
setting. Operators can now tag every span / log / metric with `team`,
`env`, `cost_center`, or anything else their backend needs.
2. Metric cardinality controls. `session.id` is moved off the OpenTelemetry
Resource (where it auto-attached to every metric data point and caused
unbounded time-series fan-out on Prometheus / ARMS Metric / etc.) and
gated behind a new opt-in `telemetry.metrics.includeSessionId` toggle.
Spans and logs still carry `session.id` for trace and log correlation.
Reserved keys (`service.version`, `session.id`) are stripped from both env
and settings sources with a `diag.warn`. `OTEL_SERVICE_NAME` follows the
OTel spec precedence (highest priority for `service.name`). Settings JSON
values are runtime-coerced to strings as defense against hand-edited
non-conforming JSON.
Breaking change: metrics no longer carry `session.id` by default. Operators
who need it can restore the previous behavior with
`QWEN_TELEMETRY_METRICS_INCLUDE_SESSION_ID=true` or
`telemetry.metrics.includeSessionId: true` in settings.json; recommended
only for short-term debugging since it re-introduces the cardinality
problem. For long-term session-level analysis, prefer trace and log
backends which handle per-event data without cardinality pressure.
Design doc: docs/design/telemetry-resource-attributes-design.md
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(telemetry): align reserved-key descriptions with implementation
Round 1 review fixes (#4367). After session.id was added to
RESERVED_RESOURCE_ATTRIBUTE_KEYS in Codex review, four user-facing
descriptions still claimed only service.version was reserved:
- packages/core/src/telemetry/config.ts (merge comment)
- packages/core/src/config/config.ts (TelemetrySettings JSDoc)
- packages/cli/src/config/settingsSchema.ts (schema description)
- packages/vscode-ide-companion/schemas/settings.schema.json (regenerated)
Also corrects scope claim: resource attributes apply to every signal
the SDK exports (OTLP and file outfile share the same Resource), not
just OTLP.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(telemetry): clarify warning destination and surface percent-encoding hint
Round 2 self-review fixes (#4367). Two small but real UX gaps:
1. Reserved-key / malformed-pair / coerce warnings route to the debug
log (per #3986), not the console — so a user who types
`OTEL_RESOURCE_ATTRIBUTES=service.version=2.0` sees no feedback that
the value was silently dropped. Adds a "Troubleshooting" section in
telemetry.md telling users where to look, and a note in the parser
docstring documenting where warns go.
2. A literal (unencoded) comma in an env var value is a common foot-gun:
the parser splits on it, producing a malformed second half that is
silently dropped. Updates the warn text to include a "hint:
percent-encode literal commas as %2C" callout, and adds the same
guidance to the docs.
Deferred to a follow-up: startup-time stderr summary of dropped
attributes. Stderr during TUI render could break Ink rendering, so the
right surface needs separate design.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(telemetry): cover first-`=` split contract in OTEL_RESOURCE_ATTRIBUTES parser
Per review feedback on #4367. The parser uses `indexOf('=')` so
the first `=` separates key and value while subsequent `=` stay in
the value. The behavior was correct but untested; a future refactor
to `split('=')` would silently break base64-padded, JWT, or
connection-string values.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(telemetry): tighten resource-attribute input validation + startup summary
Adopts review feedback from #4367 (wenshao via Qwen Code /review).
Five accepted suggestions, bundled because they all touch the same
parse/coerce/strip pipeline:
1. Key percent-decoding (CRITICAL). `parseOtelResourceAttributes` now
percent-decodes both keys and values per the OTel / W3C Baggage spec.
Without this, `OTEL_RESOURCE_ATTRIBUTES=service%2Eversion=99` lands
on Resource as the literal key `service%2Eversion`, bypassing the
reserved-key filter; a collector that decodes keys downstream could
then resurrect `service.version` and spoof the version label.
2. Startup summary of dropped attributes. Every `diag.warn` in
resource-attributes.ts routes only to the OTel debug log (per
#3986), giving operators zero feedback when their attributes are
silently dropped. Helpers now optionally accumulate diagnostics
into a `ResourceAttributeWarnings` array; the resolver collects
them and the SDK emits a one-time console summary at init (before
Ink renders, so no TUI conflict).
3. `||` instead of `??` for service.name fallback. Settings can put
an empty string through `??`, producing a blank `service.name`
that some backends reject. `||` falls through to the default.
4. `coerceStringResourceAttributes` now trims keys and skips
empty/whitespace-only keys, matching `parseOtelResourceAttributes`.
Previously `{" ": "x"}` or `{"team ": "y"}` from settings.json
would land as malformed Resource attributes.
5. `OTEL_SERVICE_NAME` is trimmed before the truthy check, so values
like `' '` or `'\t'` are treated as unset rather than producing
a whitespace-only service name on Resource.
One suggestion declined (in-thread reply on PR):
- "Redundant `?? {}` in sdk.ts:160" — intentional defense-in-depth for
`vi.mock('../config/config.js')` callers in `telemetry.test.ts` where
auto-stub returns undefined. The reviewer is right that production
code paths never hit it, but tests do.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): trim whitespace-only service.name + add invalid-key-encoding test
Adopts two review suggestions on #4367 (wenshao via Qwen Code /review):
1. `service.name` fallback uses `.trim() || SERVICE_NAME` instead of plain
`||`. Plain `||` lets whitespace-only values (`" "`, `"\t"`) through as
truthy, producing a blank service name on Resource that some backends
reject. Both settings (no value trimming) and env (`%20` decodes to `" "`)
can deliver such values. Test added.
2. Adds `key%ZZ=val` to the parameterized parser test to cover the
invalid-percent-encoding-on-key catch branch. Previously only the
value-side catch was tested.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(cli): respect /editor preference in Ctrl+X external editor
The Ctrl+X external editor prompt previously ignored the
general.preferredEditor setting, always falling back to $VISUAL/$EDITOR
env vars. Now it consults the preferred editor first, using the correct
--wait flags for GUI editors, and falls back to env vars only when no
preference is set or the preferred editor is unavailable.
Closes#4165
* fix(cli): address review feedback on external editor feature
- Fix command injection risk: quote args when needsShell is true
- Move writeFileSync inside try/finally with mode 0o600
- Change temp file extension from .md to .txt
- Extend needsShell check to cover .bat extension
- Fix import formatting in AgentComposer.tsx
- Extract usePreferredEditor hook to deduplicate validation
- Add 12 tests for openInExternalEditor covering all branches
* test(cli): add missing vi.mock for usePreferredEditor and useWorktreeSession
AppContainer.test.tsx mocks every hook that AppContainer.tsx imports,
but the two new hooks (usePreferredEditor from this PR,
useWorktreeSession from main's #4174) were not mocked — causing the
real hooks to execute during tests, crash on missing context, and fail
all 47 downstream assertions.
* fix(cli): address review feedback on env-var fallback and spawnSync timeout
- Detect .cmd/.bat in env-var fallback path on Windows and enable shell
mode with quoted args, matching the preferred-editor path behavior
- Add 30-minute timeout to spawnSync to prevent terminal freeze when a
GUI editor hangs
- Add test cases for both changes
* fix(cli): propagate preferredEditor to TextInput component
TextInput creates its own useTextBuffer but was not passing
preferredEditor, so Ctrl+X in secondary inputs (dialogs, settings
prompts, etc.) silently ignored the /editor preference.
* fix(cli): document why simple double-quoting is safe for shell args
The args passed to cmd.exe are program-controlled (tmpdir path + fixed
flags), never arbitrary user input. cmd.exe does not expand $() or
backticks inside double quotes. This matches Claude Code's approach.
* fix(cli): handle signal-killed editor and defer undo snapshot
- Check spawnSync signal field to avoid reading stale temp file
when editor is killed by SIGTERM/SIGKILL
- Move undo snapshot creation after successful file read to prevent
phantom no-op undo entries on editor failure
* fix(cli): restore private tmpdir, skip undo on unchanged content
- Restore mkdtempSync isolation directory (was flattened to os.tmpdir)
- Skip undo snapshot when editor content is unchanged
- Update JSDoc to reflect deferred-snapshot behavior
- Remove unused crypto import
- Add tests: unchanged content skip, tmpDir cleanup, undo precision
* fix(cli): use path.join in external editor tests for Windows compat
Tests hardcoded forward-slash paths which fail on Windows where
path.join produces backslashes. Use pathMod.join for the expected
temp file path so assertions pass on all platforms.
* fix(cli): quote editorCmd in shell mode, wrap setRawMode, improve logging
- Quote editorCmd along with args when shell: true, so Windows paths
with spaces (e.g. C:\Program Files\...\code.cmd) survive cmd.exe.
- Wrap setRawMode restore in try/catch so a destroyed stdin doesn't
skip temp file cleanup.
- Include command, shell mode, and resolution source in error log.
- Add tests: CRLF normalization, readFileSync failure, editorCmd quoting.
* refactor(core): remove unused isTerminal from ExternalEditorCommand
The field was never consumed by any caller — only command, args, and
needsShell are destructured. The standalone isTerminalEditor() function
already serves the same purpose for openDiff.
* docs(cli): update stale JSDoc on openInExternalEditor
Reflect the new editor resolution order (/editor → $VISUAL → $EDITOR → vi)
and the moved undo-snapshot timing (after editor exit, not before).
* fix(cli): address review round 3 — temp dir leak, mkdtemp safety, TextInput stdin
- Split unlinkSync/rmdirSync into separate try/catch blocks to prevent
temp directory leak when unlinkSync throws (regression from main)
- Move mkdtempSync inside try block with early return on failure
- Pass stdin/setRawMode from TextInput to useTextBuffer so terminal
editors (vim/neovim/emacs) correctly toggle raw mode via Ctrl+X
* test(cli): add undo-after-successful-edit test for external editor
* fix(cli): opts.editor priority, filePath in error log, warn on invalid editor
* fix(cli): address sandbox gap and Windows env-var safety in external editor
- usePreferredEditor now checks allowEditorTypeInSandbox() and returns
undefined for GUI editors when SANDBOX env is set
- env/default editor fallback rejects commands containing " or | before
enabling shell mode on Windows
* fix(cli): address wenshao review — unsafe-char guard, debug logs, test coverage
- Add unsafe-character rejection for opts.editor .cmd paths on Windows
- Change env-var unsafe-char handling from throw to graceful return + cleanup
- Add debug logging before spawnSync and in setRawMode catch block
- Add tests for opts.editor path, .cmd shell mode, and unsafe-char rejection
* fix(cli): expand unsafe-char guard, remove stale comment, add tests
- Expand Windows unsafe-character regex to include % and ! (cmd.exe
variable expansion and delayed expansion)
- Remove stale "no hooks needed" comment in TextInput.tsx
- Add setRawMode lifecycle test (disable before editor, restore after)
- Add default fallback tests for vi (linux) and notepad (win32)
* fix(cli): remove explicit type annotation on mock.calls.findIndex callback
The `[boolean]` tuple annotation conflicts with vitest's `any[][]`
mock.calls type, causing TS2345 in CI.
* fix(cli): replace unlinkSync+rmdirSync with recursive rmSync for temp cleanup
Leftover swap files from vim/neovim would cause rmdirSync to silently
fail on non-empty directories, leaking temp dirs. Use rmSync with
recursive+force to handle this. Also fix stale JSDoc fallback comment.
* test(cli): add % and ! unsafe-char coverage and error-path raw mode test
- Expand opts.editor and env-var unsafe-char tests to cover %, !, and "
independently via it.each, preventing silent regex regressions
- Add error-path test verifying setRawMode restore when editor exits
with non-zero status
* docs: add OOM investigation reports and auto-compaction redesign proposal
- Runtime memory investigation plan
- Non-interactive memory benchmark report
- OOM reproduction report with 2GiB/4GiB synthetic tests
- Runtime diagnostics benchmark report
- Auto-compaction threshold redesign proposal
* fix(core): replace structuredClone with shallow copy to prevent OOM
Replace `structuredClone(this.history)` (called up to 4x per turn on the
send path) with a lightweight shallow copy via `copyContentContainer()`.
This eliminates the OOM root cause in long tool-heavy sessions where the
full deep clone exceeded remaining V8 heap headroom.
Key changes:
- Add `copyContentContainer()` helper ({...content, parts: [...parts]})
- Add `getRequestHistory()` private method for the send path
- Add `getHistoryShallow()`, `getHistoryTailShallow()`,
`peekLastHistoryEntry()`, `getLastModelMessageText()`,
`getHistoryLength()` for read-only callers
- Remove HEAP_PRESSURE_COMPRESSION_RATIO safety net (no longer needed
now that the underlying OOM cause is fixed)
- Update chatCompressionService to use getHistoryShallow(true)
- Update nextSpeakerChecker to send only lastMessage (not full history)
- Update memoryDiagnostics with process-tree RSS measurement
* feat(core): add runtimeDiagnostics utility for heap/memory instrumentation
Required by content generators (anthropic, openai, logging) which import
runtimeDiagnostics for optional heap-pressure telemetry during streaming.
Gated by QWEN_CODE_PROFILE_RUNTIME=1 environment variable.
* fix(cli): update doctorCommand test mocks for new MemoryDiagnostics interface
Add missing maxRSSRaw, maxRSSUnit, and processTree fields to test fixtures
to match the updated MemoryResourceUsage and MemoryDiagnostics interfaces.
* fix(vscode-ide-companion): use public core imports
* fix: address review comments — type guards, dead fallbacks, and doc accuracy
Code:
- Fix unsound type guard: `'text' in part` → `typeof part.text === 'string'`
in geminiChat.ts and client.ts (Copilot + wenshao feedback)
- Remove unnecessary optional chaining and dead fallback chains in client.ts
(getHistoryShallow, peekLastHistoryEntry, getHistoryLength, etc. now call
GeminiChat methods directly)
- Add 5s timeout to `execFileAsync('ps', ...)` in memoryDiagnostics.ts
Docs:
- Fix GiB conversion accuracy and add single-run caveat to summary
- Add Node.js version to test environment table
- Fix auto-compaction attempt count (5→4) in OOM report
- Soften root-cause attribution certainty
- Add MCP child process context to investigation plan
- Clarify "Codex" reference (→ OpenAI Codex)
- Fix truncated MCP server name (chrome → chrome-devtools)
- Remove duplicate verification commands in benchmark table
- Clarify thread exhaustion vs V8 heap OOM distinction
- Add workload confound caveat to before/after comparison
- Fix SUMMARY_RESERVE "hard relationship" vs thinking budget contradiction
* fix(core): restore fallback chains in client.ts for mock compatibility
The previous commit removed optional chaining from client.ts wrapper
methods, but client.test.ts mocks getChat() with partial objects that
lack the new shallow methods. Restore ?. fallback chains so both
production (GeminiChat) and test (mock) paths work correctly.
* docs: clarify memory review follow-ups
* docs: fix runtime benchmark unit conversion
* docs: add default-heap OOM stress report
* fix: update copyright year to 2026 in new files [skip ci]
New files added in this PR had 2025 copyright headers. Updated to 2026
to reflect the current year.
The feedback dialog (point-up/point-down) was only shown to users
authenticated via QWEN_OAUTH. With the QWEN_OAUTH free tier closed
on 2026-04-15 (#3203), the active user pool that can produce
feedback events has effectively drained, leaving the user_feedback
telemetry signal blind.
The reported payload only contains session_id, rating, model,
approval_mode, and prompt_id — no prompt content or other PII —
so there is no privacy reason to scope it to a specific auth
provider. Keep the existing usageStatisticsEnabled and
enableUserFeedback opt-ins, which already gate all telemetry.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(providers): unify provider config into core, remove CLI re-exports
Move all ProviderConfig definitions, registry (ALL_PROVIDERS), and
utility functions (buildInstallPlan, resolveBaseUrl, etc.) from
packages/cli/src/auth/ into packages/core/src/providers/ so both
CLI and VSCode can share the same provider system.
- Add core providers module with types, presets, install logic
- Rewrite VSCode AuthMessageHandler to dynamically generate provider
choices from ALL_PROVIDERS instead of hardcoding 3 providers
- Add applyProviderInstallPlanToFile in VSCode settingsWriter using
the ProviderSettingsAdapter abstraction
- Delete 11 CLI re-export wrapper files, update ~20 import sites
- Keep CLI-specific applyProviderInstallPlan (uses LoadedSettings)
and openrouterOAuth.ts (CLI-only OAuth runtime)
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* refactor(cli): drop OpenRouter OAuth + /manage-models, simplify /auth
OpenRouter now uses the standard API-key flow under "Third-party Providers"
(issue #4108). The whole OpenRouter OAuth implementation (PKCE, callback
server, model auto-install) and the /manage-models command (only OpenRouter
was wired in; /auth Step 2 already covers model selection) are removed.
/auth is renamed around the "Connect a Provider" mental model:
- Dialog title is now "Connect a Provider"; the OAuth main entry is gone
- handleAuthSelect (mixed close + auth trigger) is split into a single-purpose
closeAuthDialog; legacy wrappers (handleSubscriptionPlanSubmit,
handleApiKeyProviderSubmit, handleCustomApiKeySubmit, ...) are dropped in
favor of the unified handleProviderSubmit
Core: openRouterProvider switches to authMethod='input', uiGroup='third-party',
ships with two recommended free models, and is reordered to the end of the
third-party list to keep DeepSeek as the default highlight.
Net diff: 34 files, +124 / -3835.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* refactor(auth): unify applyProviderInstallPlan in core, drop cli/auth
CLI and vscode now share core's applyProviderInstallPlan instead of keeping
two parallel implementations. The CLI-only env rollback (snapshot
process.env, restore on error) is folded into the core version so vscode
also benefits from it.
CLI ships a LoadedSettingsAdapter that maps LoadedSettings to core's
ProviderSettingsAdapter contract. Backup/restore is layered: write a .orig
file, structuredClone settings + originalSettings, then recomputeMerged()
on restore — same guarantees as before, just routed through the adapter.
Tests for the install logic are migrated to core and rewritten against the
adapter mock (more focused than the previous LoadedSettings/Config mocks).
packages/cli/src/auth/ is gone entirely.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* refactor(providers): drop unused authMethod field from ProviderConfig
Every preset has had authMethod='input' since OpenRouter switched to the
standard API-key flow, making the field a dead dimension. Removing it
cleans up three never-taken branches and aligns the type with reality:
connecting a provider always means entering an API key.
- core: remove ProviderConfig.authMethod; shouldShowStep('apiKey') is
now unconditionally true; drop authMethod from 9 presets
- vscode AuthMessageHandler: drop the OAuth branch in handleAuthInteractive
- vscode WebViewProvider: simplify the apiKey-required guard
- tests: update provider-config.test and custom-provider.test
If a future provider needs a browser-based flow, the field can be
re-introduced; for now the smaller surface is worth more.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* refactor(providers): prefix Alibaba plan presets with alibaba-
Rename coding-plan.{ts,test.ts} → alibaba-coding-plan.{ts,test.ts} and
token-plan.{ts,test.ts} → alibaba-token-plan.{ts,test.ts} so the file
names line up with the existing alibaba-standard preset and make it
obvious at a glance which presets belong to Alibaba ModelStudio.
Export names (codingPlanProvider, tokenPlanProvider, TOKEN_PLAN_*,
CODING_PLAN_*) are unchanged — only the file paths and the two
imports in all-providers.ts / index.ts move.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(vscode): guard ProviderSettingsAdapter against prototype pollution
The dotted-key writer in createFileSettingsAdapter walked through any
segment, including __proto__/constructor/prototype, which would let a
malicious or malformed ProviderInstallPlan reach Object.prototype.
Refuse to write paths containing reserved segments and use
hasOwnProperty when traversing intermediate objects so that inherited
properties cannot redirect the walk.
Addresses CodeQL alert #226 surfaced on PR #4287.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): default Audio modality to off in provider advanced config
In the /auth Custom Provider advanced-config step, "Enable modality"
should default to Image + Video only. Audio was on by default, which
implied the model accepts audio input even though most providers
people configure here don't.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): show base URL default as placeholder, not prefilled value
In Custom Provider Step 2/6 (and on protocol switch), the base URL
input started with the protocol's default URL pre-filled. Users who
wanted a non-default endpoint had to manually clear the field first.
Switch to placeholder semantics: the input starts empty, the default
URL is shown as a hint, and submitting blank falls back to that
default (then writes it back to baseUrl so downstream steps see a
real value).
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* refactor(cli): rename /auth description to "Connect an LLM provider"
The old description ("Configure authentication information for login")
implied a Qwen-account login. After the /auth refactor it's really
about picking an LLM provider and entering credentials, so the menu
entry should say that.
Also add 'connect' as an alt-name alongside the existing 'login' so
users can type /connect when 'auth' feels wrong. Keep 'login' for
muscle-memory compatibility.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* i18n(cli): translate "Connect an LLM provider" in all locales
Strict-parity locales (zh, zh-TW) require every built-in command
description to be translated; the renamed /auth description was
falling back to English and breaking the must-translate test.
Add translations for zh / zh-TW (required) and refresh the other
seven locales (en, ru, de, ja, fr, ca, pt) so the old
"Configure authentication information for login" key is removed
everywhere rather than left as a dangling dictionary entry.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(vscode): await applyProviderInstallPlanToFile and grow test coverage
Critical: applyProviderInstallPlanToFile fired the install plan with
`void`, so any rejection (EACCES from persist(), prototype-pollution
guard throw, etc.) was silently swallowed and WebViewProvider proceeded
to disconnect/reconnect the agent as if the write had succeeded.
Make the wrapper `async` and `await` it in the only caller.
Tests added:
- core/install.test: isSameModelIdentity fallback path
(prepend-and-remove-owned with no ownsModel) — verifies models are
matched on id+baseUrl, not just id.
- vscode/AuthMessageHandler.test: happy-path with a fixed-baseUrl
third-party provider, validateApiKey error branch, and BaseUrlOption
picker presentation.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): address PR #4287 review (critical + suggestion)
vscode AuthMessageHandler (Critical):
- Add the missing protocol-selection step so custom-provider users can
pick Anthropic/Gemini instead of being silently locked to OpenAI.
- Validate free-form base URL with the same /^https?:\/\// check the
CLI uses; reject file:/javascript: schemes.
vscode AuthMessageHandler (Suggestion):
- Stop filtering separator entries from the provider QuickPick so
groups (Alibaba Cloud / Third Party / Custom) actually show as
headers instead of a flat list.
- Treat a null authInteractiveHandler as an error: surface an
authError + cancellation notification instead of silently dropping
the user's input.
- Call notifyAuthCancelled when validateApiKey rejects so the
webview state resets and the user can retry.
core/providers/presets/openrouter.ts (Critical):
- Replace the substring includes() in ownsModel with a URL-hostname
match so paths like https://api.example.com/openrouter.ai/v1 stop
being misidentified as OpenRouter models (and getting removed on
re-install).
vscode/services/settingsWriter.ts (Critical):
- stripTrailingCommas() so JSONC files with trailing commas (VSCode's
default style) parse instead of silently returning {} and then
overwriting the entire settings file.
- readSettings() distinguishes ENOENT (return {}) from parse errors
(log + rethrow) so a malformed file never gets clobbered.
- writeSettings() writes through a temp file + fs.renameSync atomic
rename, eliminating the half-written file window on EACCES /
disk-full / crash.
- setValue() refuses to overwrite a scalar at an intermediate path
segment (would have silently destroyed e.g. {"env": "legacy-string"}).
core/providers/install.ts (Suggestion):
- Move settings.backup?.() inside the try block so a backup failure
still triggers the env-rollback path in catch.
cli/config/loadedSettingsAdapter.ts (Suggestion):
- Add the same UNSAFE_KEY_PARTS guard the vscode adapter has, so
__proto__/constructor/prototype segments are rejected before
reaching the underlying setNestedPropertySafe walker. Defense in
depth: not exploitable today but the utility has no built-in guard.
vscode/webview/providers/WebViewProvider.ts (Suggestion):
- Hoist buildInstallPlan / applyProviderInstallPlanToFile to static
imports (both modules already top-level imported); drops two
per-call await import() round-trips.
cli/utils/doctorChecks.ts (Suggestion):
- Whitespace nit before the comma in the qwen-code-core import.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): second round of PR #4287 review fixes
Critical:
- settingsWriter: stripTrailingCommas now uses a char-by-char scanner so
literal ",]" inside a string value is preserved (the previous regex
silently corrupted it).
- install.ts: wrap settings.restore() in try/catch so a restore failure
doesn't mask the original error or skip the env-rollback loop.
- install.ts: snapshot the runtime ModelProvidersConfig before applying
patches and reload it in the catch path, so an in-flight refreshAuth()
failure doesn't leave the live session holding providers that were
never successfully installed.
- AuthMessageHandler: custom-provider Base URL is now a placeholder
instead of a pre-filled value, with the default selected by the
user's chosen protocol (openai/anthropic/gemini). Empty input falls
back to the protocol-appropriate URL, preventing the
pick-Anthropic-but-keep-OpenAI-URL footgun.
Suggestion:
- AuthDialog: replace the isCurrentlyCodingPlan misnomer with a uiGroup
check — resolveMetadataKey returns config.id for *any* provider with
a static models[], so the old guard made DeepSeek/MiniMax/OpenRouter
users land on the Alibaba tab instead of Third-party Providers.
- AuthMessageHandler: guard against modelIds being [] after splitting
comma input (matches the CLI's "Model IDs cannot be empty.").
- WebViewProvider: restore the explanatory comment for the
authState === true success-toast guard that the previous diff
accidentally dropped.
Tests:
- settingsWriter.test: new applyProviderInstallPlanToFile suite covering
happy path, prototype-pollution guard (built via Object.defineProperty
to bypass __proto__ literal semantics), intermediate-scalar rejection,
malformed-file no-clobber, JSONC-with-trailing-commas parsing
(including a string containing ",]"), and the atomic-write tmp-file
cleanup.
- loadedSettingsAdapter.test: new file — forwarding, UNSAFE_KEY_PARTS
rejection, getValue against merged settings, backup/restore round-trip,
cleanupBackup semantics.
- provider-config.test: added findProviderByCredentials and
getAllProviderBaseUrls coverage (preset hits, unknown-key misses,
BaseUrlOption[] preset expansion).
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(cli): satisfy strict tsc --build in loadedSettingsAdapter.test
CI's `tsc --build` (with emit) enforced two strict checks that
`tsc --noEmit` had been letting through:
- `noPropertyAccessFromIndexSignature` flagged `file.settings['env']`
reads against `Record<string, unknown>`. Switched the test fixture
shape to a named `SettingsShape` interface with explicit `env` and
`modelProviders` keys (plus an index signature for setValue's
arbitrary writes), so dot access on the known keys is no longer
"through" the index signature.
- Calling optional methods via `adapter.backup?.()` produced TS2722
(`Cannot invoke an object which is possibly 'undefined'`) under the
build flags. createLoadedSettingsAdapter always installs
backup/restore/cleanupBackup, so the tests now assert
`toBeTypeOf('function')` first and then call via non-null assertion,
which both documents the invariant and makes the call typesafe.
- Dropped the `({} as Record<string, unknown>)['polluted']` sanity
check; `expect(setValue).not.toHaveBeenCalled()` already proves the
guard short-circuits before any write reaches LoadedSettings.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(cli): guard mock setValue against prototype pollution in adapter test
CodeQL flagged the mock setValue's recursive property assignment as a prototype-pollution sink. Add UNSAFE_KEY_PARTS check at the top of the mock to align with the real setNestedPropertySafe contract.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(cli): use literal === guards for CodeQL prototype-pollution sanitiser
CodeQL re-flagged the mock setValue write even after the Set.has guard added in 2e6adf8a6d — the scanner only recognises inline literal === comparisons as prototype-pollution sanitisers, not Set lookups.
Reworked the mock to (1) merge the guard into the loop so every current[part] write is preceded by a literal === check against '__proto__'/'constructor'/'prototype', and (2) collapse the dual leaf/branch logic into a single loop body. Runtime behaviour is identical; CodeQL should now treat the write as sanitised.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): third round of PR #4287 review fixes (8 comments)
Critical:
- useAuth: handleProviderSubmit now calls setPendingAuthType at the start
of the try, so handleAuthFailure can record the AuthEvent telemetry on
applyProviderInstallPlan rejection (previously dropped silently because
pendingAuthType was undefined).
- settingsWriter: readQwenSettingsForVSCode wraps readSettings in
try/catch so a malformed settings.json no longer crashes the VSCode
extension on activation; the write paths (writeCodingPlanConfig,
writeModelProvidersConfig) deliberately keep propagating to avoid
silently overwriting a corrupt file with partial data.
Suggestions:
- settingsWriter.setValue: intermediate-segment guard now also rejects
arrays (typeof [] === 'object' previously slipped through and would
let us set string keys on an array). Loop restructured so the
literal-=== prototype-pollution guard runs at every step, satisfying
CodeQL's sanitiser detector on both the leaf and intermediate writes.
- settingsWriter atomic write: SETTINGS_FILE_MODE = 0o600 +
SETTINGS_DIR_MODE = 0o700 + best-effort chmod on existing files. API
keys persisted into env.* are no longer world-readable on multi-user
systems.
- loadedSettingsAdapter: switched its prototype-pollution guard to the
same inline literal === pattern so the two adapters stay symmetric
and CodeQL recognises both as sanitisers (Comment 6 — explicit
'keep in sync' comment + same shape rather than a shared helper that
CodeQL wouldn't trace through).
- AuthMessageHandler: protocol QuickPick now shows 'OpenAI Compatible'
/ 'Anthropic' / 'Gemini' instead of the raw AuthType enum values.
- WebViewProvider: authInteractive log now records only the parsed
hostname, not the full inputs.baseUrl, so credentials embedded in
userinfo or query strings don't leak into extension-host logs.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* test(auth): cover the rollback safety nets in applyProviderInstallPlan + useAuth failure path
Addresses the missing-coverage points in the latest review pass: every deliberately-engineered rollback path in install.ts and the visible side effects of handleAuthFailure now have a regression test, so a future refactor that 'simplifies' these paths can't silently break them.
applyProviderInstallPlan (install.test.ts, +4 cases):
- restores runtime model providers when refreshAuth rejects after
reloadModelProviders ran (asserts the second reloadModelProviders call
receives the pre-install snapshot).
- still rolls back env vars when backup() throws before persist (pins
the 'backup inside try' invariant added in 38a214d0ec).
- continues env rollback even when settings.restore itself throws
(pins the nested try/catch around restore added in 38a214d0ec).
- continues throw + env rollback when the rollback-time
reloadModelProviders itself throws (the original error must still
surface; env vars must still revert).
useAuth (useAuth.test.ts, +1 case):
- surfaces install-plan rejection as an auth error and records
telemetry — refreshAuth throws, the test asserts authError is set,
the dialog reopens, isAuthenticating clears, no success toast is
added, and pendingAuthType is populated (which is what the new
setPendingAuthType call lets handleAuthFailure key the AuthEvent on).
- createSettings now mocks recomputeMerged + forScope.settings so the
loaded-settings-adapter restore() path doesn't emit a noisy stderr.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): fourth round of PR #4287 review fixes
Critical:
- settingsWriter JSONC scanner: \uXXXX is a 6-char escape, not 2.
The previous stripJsonComments / stripTrailingCommas used j+=2 for
every backslash, so a value containing \u0022 would let the embedded
quote terminate the string early — turning a single string value into
multiple top-level keys after the strip passes. That's a parser
differential vs JSON.parse and enables settings.json key injection
(e.g. an attacker-controlled API_KEY string could inject env.NODE_OPTIONS).
Now we branch on text[j+1] === 'u' and skip 6, satisfying both scanners.
- resolveBaseUrl no longer crashes on an empty baseUrl array. The
previous config.baseUrl[0].url threw 'Cannot read undefined.url' on []
and brought down the whole install flow. Falls back to selectedBaseUrl
or '' instead.
- providerMatchesCredentials now resolves function-typed envKey by
calling it with (protocol, baseUrl). The previous typeof-string gate
made the custom provider invisible to findProviderByCredentials —
/doctor and system-info diagnostics couldn't see custom-provider users.
Catches the function call so a misbehaving custom envKey can't crash
the matcher.
Suggestions:
- AuthDialog: defaultMainIndex now also returns 2 for uiGroup === 'custom'
so a custom-provider user lands on the Custom Provider tab instead of
Alibaba ModelStudio.
- install.ts: env-var rollback loop is now wrapped in try/catch matching
the same shape as the settings.restore() and reloadModelProviders
rollbacks. A process.env write throwing (custom property descriptors,
some sandboxes) won't skip the runtime-providers rollback below.
- readSettings: SyntaxError is now wrapped in an actionable Error
('Cannot parse ~/.qwen/settings.json ($name: $message). Standard
JSONC is supported... Please fix or delete $path...') so users facing
a corrupt file get a clear message instead of a bare SyntaxError. The
cause is preserved via Error.cause.
Tests:
- settingsWriter: new \u0022 injection regression — asserts that a
string containing \u0022 stays a single string and no injected key
lands at the top level.
- provider-config: new edge-case suite for resolveBaseUrl with [] and
providerMatchesCredentials with function-typed envKey (matching path,
wrong-key path, function-throws path). Re-imports via the relative
source path so the new behaviour is exercised even before dist/ is
rebuilt.
Not addressed:
- handleProviderSubmit error-path test (Comment 3264567491) was already
added in 7d8b4785ad — same test, same surface (refreshAuth rejection
+ authError set + dialog reopen + isAuthenticating false + no success
toast + pendingAuthType populated).
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(vscode): import AuthType as value not type
AuthMessageHandler now references AuthType.USE_OPENAI etc. as enum values (for the protocolLabels map added in cdc17cbba0), but the import was 'import type AuthType' which strips the runtime binding. TS1361 fired in CI's emitting build even though --noEmit was happy locally.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(providers): restore modelscope test + tighten openrouter ownsModel
Two findings from the latest /review pass that survived earlier rounds:
1. modelscope.test.ts was deleted in the move-from-CLI step (60 lines / 4 cases under packages/cli/src/auth/providers/thirdParty/) but never recreated in core's preset test folder. Re-added a 3-case suite (config shape, install plan with per-model metadata for known IDs, graceful fallback for unknown IDs) so the third-party preset coverage is symmetric again. Also exported modelscopeProvider from packages/core/src/providers/index.ts so the public API matches the other presets.
2. openrouter.ts ownsModel previously claimed any model on an openrouter.ai hostname, which would silently delete a user's hand-added entry that happened to route through openrouter.ai under a different envKey (e.g. a personal gateway). Now requires both model.envKey === OPENROUTER_ENV_KEY AND the openrouter.ai hostname match. Existing openrouter.test.ts updated and extended to cover: matching path, envKey mismatch path, host mismatch path, missing/malformed baseUrl.
The remaining findings in that /review were either already addressed in earlier rounds (custom provider visibility / resolveBaseUrl empty array / useAuth telemetry / TS4111 errors — verified 0 locally) or architectural concerns beyond this PR's scope (LoadedSettings.setValue's per-call saveSettings).
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): fifth round of PR #4287 review fixes
Critical:
- provider-config.ts providerMatchesCredentials: iterate config.protocolOptions
when resolving a function-typed envKey instead of relying on the default
config.protocol. A custom provider configured under USE_ANTHROPIC or
USE_GEMINI persists an envKey derived from THAT protocol, not from
USE_OPENAI — without iteration the matcher silently misses them and
custom-provider users disappear from /doctor + AppHeader +
systemInfoFields + AuthDialog.defaultMainIndex.
- provider-config.test.ts: the existing test asserting 'returns false for
function-typed envKey' was holding on the old broken behaviour. Flipped
to assert toBe(true) for the matching path, and routed it through the
relative source import so it doesn't run against stale dist.
Suggestions:
- settingsWriter.clearPersistedAuth: now wipes every preset's string envKey
(iterates ALL_PROVIDERS, plus the existing subscription-plan loop kept
for explicitness) and every QWEN_CUSTOM_API_KEY_* key by prefix match.
Previously DeepSeek / MiniMax / Z.AI / IdeaLab / ModelScope / OpenRouter
/ custom keys lingered on disk after clearing auth.
- custom-provider.ts generateCustomEnvKey: the readable-only normalization
collapsed 'api.example.com', 'api-example.com', and 'api_example.com'
into the same env key, so two structurally different custom providers
would overwrite each other's API key. Now appends a 6-hex-char SHA-256
suffix derived from (protocol, baseUrl-with-trailing-slash-stripped).
The trailing-slash invariant from the prior implementation is preserved
(api/v1 and api/v1/ still hash equal). Suffix collision probability at
6 hex chars is ~1/16M per pair — fine for an interactive flow.
Tests:
- provider-config.test.ts: added a 'iterates protocolOptions' case that
configures a custom-style provider, derives the key under
USE_ANTHROPIC, and asserts the matcher finds it.
- custom-provider.test.ts: regex-matches the new readable+hash format
for the deterministic / special-character / empty-string cases, and a
new 'disambiguates structurally distinct URLs that normalize
identically' case that pins down the collision fix
(api.example.com vs api-example.com vs api_example.com all differ).
Not addressed:
- TS1361 'type AuthType' import — already fixed in 8f94b018bd
- modelscope re-export — already fixed in 7228d73d80
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(custom-provider): replace polynomial regex with linear char scans
CodeQL alerts 225 + 232 flagged `/_+/g`, `/^_+|_+$/g`, and `/\/+$/` in generateCustomEnvKey as polynomial regex on user input. V8 handles these patterns linearly in practice, but the scanner can't see that and any baseUrl with many '_' or '/' would be flagged as a theoretical worst case.
Replaced both passes with single-pass character scans:
- normalizeEnvSegment: walks the string once, emits alphanumerics verbatim, collapses any non-alphanumeric run to a single '_', then trims leading/trailing underscores via charCodeAt index walks. Equivalent to the prior three regexes but with no quantifier backtracking surface.
- stripTrailingSlashes: walks backwards from the end while charCodeAt === 47, then slices. Equivalent to `replace(/\/+$/, '')`.
All 11 custom-provider tests still pass — output format and invariants (trailing-slash equivalence, hash suffix, protocol/URL disambiguation) are unchanged.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): seventh round of PR #4287 review fixes
Critical:
- i18n: 9 locale files updated to replace orphaned 'Select Authentication
Method' / 'You must select an auth method...' keys with the new
'Connect a Provider' / 'You must connect a provider...' keys the
AuthDialog actually references. Non-English users no longer see the
English fallback for the main heading + exit-prevention warning.
- settingsWriter.writeSettings: renameSync is now wrapped in try/catch
that unlinks the temp file on failure (EPERM/EBUSY on Windows from
watchers/AV would otherwise orphan a secret-bearing .tmp file in
~/.qwen on every failed write).
- settingsWriter.restore(): write to disk FIRST, then update in-memory
data. The previous order left memory clean while disk retained the
failed install's partial state if writeSettings threw. Now matches
the CLI adapter's order.
- AuthMessageHandler custom-provider tests: added 4 cases covering
protocol picker → free-form URL → API key → comma-split model IDs →
advanced config (one happy path), plus the http(s) scheme guard, the
protocol-aware blank-URL fallback, and the whitespace-only model
IDs guard. Previously the entire custom path through
runProviderSetupFlow had zero coverage.
- settingsWriter clearPersistedAuth tests: added cases for the
expanded preset/custom/subscription cleanup (asserts NODE_OPTIONS
survives, every QWEN_CUSTOM_API_KEY_* is wiped, providerMetadata
entries for every preset are gone) plus a no-settings-file no-op.
Suggestions:
- loadedSettingsAdapter.restore(): now checks restoreSettingsFromBackup's
boolean return value and logs an explicit warning when on-disk rollback
fails (EACCES / missing .orig). Previously the failure was silent and
the next CLI restart would read a corrupted file.
- generateCustomEnvKey: hash suffix lengthened from 6 → 12 hex chars
(24 → 48 bits). Brings collision search out of milliseconds-range
enumeration; offline 'pick a URL that collides' attack is no longer
practical at interactive setup time.
- getDefaultBaseUrlForProtocol: new shared helper in core consumed by
both the CLI (useProviderSetupFlow) and VS Code (AuthMessageHandler)
flows. Removes the duplicated DEFAULT_BASE_URLS map; one source of
truth for the OpenAI/Anthropic/Gemini placeholder URLs.
- settingsWriter.clearPersistedAuth: providerMetadata cleanup now
iterates ALL_PROVIDERS with resolveMetadataKey instead of hardcoding
coding-plan/token-plan. Stale metadata for deepseek/minimax/zai/
idealab/modelscope/openrouter no longer lingers after logout.
- resolveMetadataKey: explicit guard against provider ids containing
'.'. A dotted id would split into multiple nested objects under
providerMetadata, silently corrupting the settings tree. Now throws
loudly at registration time.
- customProvider: added explicit ownsModel that prefix-matches against
QWEN_CUSTOM_API_KEY_*. Reinstalling a custom provider under a
different baseUrl now reliably replaces (not accumulates) the old
entries.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): eighth round of PR #4287 review fixes
Suggestions:
- clearPersistedAuth metadata cleanup loop: per-iteration try/catch
around resolveMetadataKey so a future dotted-id provider can't abort
the loop and leave secrets on disk.
- VS Code AuthMessageHandler: removed the hardcoded
|| 'https://api.openai.com/v1' fallback after
getDefaultBaseUrlForProtocol — defaults must live in core. The CLI
flow has no such fallback, and the silent OpenAI default would mask
a new AuthType core hadn't been taught about.
- settingsWriter restore() comment: clarified the deliberate divergence
from the CLI adapter's trade-off (disk-fail-throws here, disk-fail-
logs-and-continues there) so the comment doesn't read 'same order'.
- useAuth handleAuthFailure: closure staleness — setPendingAuthType
queues an async React update, so handleAuthFailure's pendingAuthType
read could see undefined when a synchronous throw beats the next
render. Added an optional protocolForTelemetry argument that the new
handleProviderSubmit passes explicitly; closure fallback kept for
legacy callers. AuthEvent error telemetry is no longer silently
dropped.
- install.ts: track currentStep before each phase (backup → env →
modelProviders → authType → legacyCredentials → modelSelection →
providerState → persist → reloadModelProviders → syncAuthState →
refreshAuth → cleanupBackup) and annotate the rethrown error with
the failing step + authType. Original error preserved via Error.cause
so callers matching on err.code still work.
- custom-provider.ts: stale '6-hex-char' comment updated to 12. Added
a migration note explaining that old 6-char keys persist as harmless
orphan disk state until clear-auth.
- settingsUtils.restoreSettingsFromBackup: was swallowing fs errors
with catch(_e); now logs the underlying cause so the adapter's
on-disk-rollback-failed warning has something specific to point at.
Tests:
- useAuth: new cancelAuthentication case asserts isAuthenticating
clears, externalAuthState clears, dialog opens, authError clears.
- provider-config: new resolveMetadataKey suite — normal id, no-models
→ undefined, dotted id → throws.
- install: new case asserting the rethrown error names the failing
step ('refreshAuth') + authType and preserves the original error
via Error.cause.
Not addressed:
- 6→12 hash backward compat (Comment 3267562667): The 6-char keys are
orphan disk state — never read by applyProviderInstallPlan (the new
model provider entries reference the new 12-char key), so no security
or correctness issue, just disk noise that clears on next sign-out.
Documented in custom-provider.ts. A full clean-up pass would need a
new ProviderSettingsAdapter delete API + a migration scan — better
as its own PR.
- writeSettings renameSync error path test + loadedSettingsAdapter
restore-failure log test (terminal-only findings): adding these
requires fs mocking surgery that's worth its own PR.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(format): four prettier/JSDoc nitpicks from review
All four are Critical-tagged formatter / docs issues caught by the latest /review pass:
- AppHeader.tsx: `AuthType ,` (stray space before comma) → standard newline-after-{ form. Was breaking CI Lint.
- useProviderUpdates.test.ts: same `AuthType ,` pattern → standard form.
- apiPreconnect.ts: double blank line after the closing `}` of the
import block (left behind when getAllProviderBaseUrls was removed
from the old auth/allProviders path) → single blank line.
- types.ts (Suggestion): JSDoc for `modelsEditable` said
"false → skip model step; use models as-is (e.g. Coding Plan)" but
codingPlanProvider actually sets modelsEditable: true (every preset
in the registry does), so the example contradicts the registry.
Dropped the parenthetical.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* test(scripts): raise install-script suite timeout to survive Windows
Windows CI flaked on `standalone release packaging > rejects unexpected dist assets` with a 5000ms timeout. The test shells out to `node scripts/create-standalone-package.js` which produces a tar.gz; observed real runtimes from sibling tests in the same run: 4780ms / 1666ms / 1079ms — the 4.8s case is already at vitest's default 5s limit, so a slightly slower subprocess startup (antivirus inspection, contended runner) tips it over.
Pre-existing test (added 2026-05-11 in cb7059f54db), unrelated to this PR's auth refactor. Bumped the suite-wide testTimeout to 30s in scripts/tests/vitest.config.ts — the tests still complete in seconds when subprocess startup is healthy; the headroom only kicks in to cover Windows-slow variance.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): ninth round of PR #4287 review fixes
Critical:
- WebViewProvider.handleAuthInteractive: roll back bad credentials when the
agent reconnect rejects them. applyProviderInstallPlanToFile commits the
key + calls cleanupBackup before the disconnect/reconnect runs, so the
plan's own rollback can't cover an authState=false outcome. Now snapshot
settings before the write (snapshotSettingsForRollback) and restore it
(restoreSettingsSnapshot) on both the authState!=true branch and the
catch branch. Without this a rejected key persisted and every VS Code
restart retried it. Two new helpers added to settingsWriter; never-throw
snapshot so a malformed pre-state degrades to a no-op restore.
Suggestions:
- AuthMessageHandler: trim the API key before validateApiKey + persistence,
matching the CLI flow (useProviderSetupFlow trims in two places). A key
pasted with trailing whitespace no longer causes silent auth failures or
VS-Code-only validateApiKey rejections.
- install.ts: the annotated rethrow no longer bakes 'step "persist"' into
the user-facing message. Step + authType are now structured properties on
a new exported ProviderInstallError (message stays the underlying error
text, cause preserved). Callers can show a clean message and log
err.step/err.authType to the dev console.
- provider-config.ts: providerMatchesCredentials no longer swallows a throw
from a function-typed envKey — console.warn surfaces the programming
error so a custom provider silently vanishing from /doctor has a trace.
- types.ts: documented that ProviderSettingsAdapter.setValue MAY flush to
disk eagerly (the CLI LoadedSettings adapter does) and that persist() can
be a no-op for such adapters — so future authors don't insert pre-persist
steps assuming atomicity.
- settingsWriter: moved the orphaned stripJsonComments JSDoc off
jsonEscapeLength (the \u-escape helper inserted between the doc and its
function) back onto stripJsonComments itself.
Tests:
- settingsWriter: snapshot/restore round-trip, malformed→null→no-op-restore,
no-file→{} snapshot.
- install: updated the step-annotation test to assert err.step/err.authType
structured properties + clean message instead of the embedded string.
- WebViewProvider.test: settingsWriter mock extended with
applyProviderInstallPlanToFile/snapshotSettingsForRollback/
restoreSettingsSnapshot.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): tenth round of PR #4287 review fixes
Critical (both from the previous round's own changes):
- WebViewProvider.handleAuthInteractive: restoreSettingsSnapshot →
writeSettings can throw (EPERM on Windows renameSync / disk full /
EACCES). Both rollback call sites are now routed through a local
safeRollback() that try/catches and logs, so a rollback failure can
never (a) re-throw out of the else-branch into the outer catch and
trigger a second rollback that skips the error message, nor (b) throw
out of the catch-branch and leave the webview auth dialog hanging with
no feedback.
- provider-config.providerMatchesCredentials: the new envKey-throw
console.warn logged the full baseUrl, which can embed credentials
(https://user:sk-secret@host). Now logs only new URL(baseUrl).hostname
(with an [invalid] fallback) and err.message, matching the
sanitization WebViewProvider already uses.
Tests:
- WebViewProvider.test: new 'credential rollback' describe with three
cases — (1) authState!==true after reconnect → restoreSettingsSnapshot
called with the snapshot, (2) authState===true → restore NOT called,
(3) restore throws (EPERM) → handleAuthInteractive still resolves and
the authError message is still sent. Hoisted mocks extended with
applyProviderInstallPlanToFile / snapshotSettingsForRollback /
restoreSettingsSnapshot refs so the scenario is controllable.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): eleventh round of PR #4287 review fixes
Critical:
- AuthMessageHandler: validation-failure paths (bad URL scheme, invalid
API key, empty model IDs, handler-not-set) no longer call
notifyAuthCancelled after sendToWebView({authError}). The webview's
ProviderSetupForm clears the error on authCancelled, so the two
messages raced and the error flashed away before the user could read
it. authCancelled is now reserved for genuine user dismissals (Escape
on a QuickPick/InputBox); authError already clears the connecting state.
- WebViewProvider: after rolling back rejected credentials, also
disconnect the agent. The reconnect spawned a process holding the bad
key in memory; without disconnect a subsequent chat message hit a
stale-credential error unrelated to the original auth failure. Now
agentManager.disconnect() + agentInitialized=false so the next /auth
reconnects cleanly.
Suggestions:
- install.ts: added a DENY_ENV_KEYS denylist (NODE_OPTIONS, NODE_PATH,
LD_PRELOAD, LD_LIBRARY_PATH, DYLD_INSERT_LIBRARIES, DYLD_LIBRARY_PATH,
PATH, HOME, TMPDIR), checked case-insensitively before writing any
plan.env entry to settings + process.env. Defense in depth: all callers
go through buildInstallPlan with hardcoded keys today, but
ProviderInstallPlan is exported.
- settingsUtils: setNestedPropertySafe AND setNestedPropertyForce now
refuse __proto__/constructor/prototype path segments (inline literal
=== so CodeQL recognises the sanitiser). migrateProviderMetadata feeds
field names from Object.entries on user settings.json, and JSON.parse
keeps __proto__ as an own property — guarding at the utility protects
every caller, not just the adapters.
Already fixed in f31224bac1 (review ran against 9f45a7536b):
- restoreSettingsSnapshot throw masking the original error → safeRollback.
- baseUrl logged verbatim in providerMatchesCredentials → hostname only.
Tests:
- install: NODE_OPTIONS rejected + not leaked to process.env/settings;
case-insensitive Path rejection.
- AuthMessageHandler: validation authError is NOT followed by
authCancelled.
- WebViewProvider: rollback path disconnects the agent + clears
agentInitialized.
- settingsUtils: setNestedPropertySafe/Force refuse __proto__/
constructor/prototype and don't pollute Object.prototype.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(test): use bracket access in settingsUtils prototype-pollution tests
The new setNestedProperty guard tests asserted obj.a.b.c / obj.x.y dot-access on Record<string, unknown>, which trips noPropertyAccessFromIndexSignature (TS4111) under the emitting tsc --build the CI 'Install dependencies' step runs. Local npm run typecheck (--noEmit) had a stale tsbuildinfo and didn't re-check the file. Switched to bracket access (obj['a']['b']['c']) to match the strict option. Behaviour unchanged; 78 settingsUtils tests still pass.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* test(vscode): cover the outer-catch rollback path in handleAuthInteractive
All prior rollback tests exercised the else-branch (authState !== true). The outer catch — reached when applyProviderInstallPlanToFile or doInitializeAgentConnection throws (disk errors, partial writes) — had no coverage, and that's the higher-risk path. New test makes doInitializeAgentConnection reject and asserts (1) restoreSettingsSnapshot called with the snapshot, (2) authError sent containing 'Configuration failed', (3) handleAuthInteractive resolves without throwing. Guards against a regression that drops the safeRollback wrapper in the catch.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* test(providers): make NODE_OPTIONS denylist test env-independent
The test asserted process.env.NODE_OPTIONS toBeUndefined after the rejected plan, but CI sets NODE_OPTIONS (--max-old-space-size=3072 from the build script), so it failed there while passing locally where NODE_OPTIONS is unset. Snapshot the original value and assert the rejected plan left it UNCHANGED (and specifically not the evil --require value) — that's the actual invariant: the denylist throws before mutating process.env.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(vscode): disconnect stale agent in handleAuthInteractive catch block too
The else-branch (authState !== true) disconnected the agent after rollback, but the outer catch only rolled back. If doInitializeAgentConnection partially initializes (agentInitialized=true, agent process spawned) then throws — e.g. a disk error during post-connect setup — the stale-credential agent stayed connected.
Extracted a disconnectStaleAgent() local helper (alongside safeRollback) and called it in both the else-branch and the catch, so the two paths are symmetric. Extended the outer-catch test to spawn a partial agent before the throw and assert disconnect() is called + agentInitialized cleared.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(auth): twelfth round of PR #4287 review fixes (5 suggestions)
All from DeepSeek's pass, all on recent commits:
- settingsUtils: stale comment referenced a non-existent UNSAFE_PATH_SEGMENTS const; the actual guard is pathHasUnsafeSegment(). Fixed both comment sites.
- settingsWriter.snapshotSettingsForRollback: was silently returning null on a readSettings throw (disabling credential rollback with no signal). Now console.warn's the cause so oncall can tie repeated cross-restart auth failures back to a transient unreadable settings file.
- provider-config.providerMatchesCredentials: the envKey-throw warn logged err.message, which a user-defined envKey fn could populate with the API key (new Error(`bad config: ${apiKey}`)). Now logs only err.constructor.name — no message, no URL.
- install.ProviderInstallError: was an interface (erased at compile time → instanceof always false). Converted to a class extending Error so instanceof works at runtime; exported as a value (not type) from the barrel. Construction simplified to new ProviderInstallError(msg, step, authType, { cause }).
- install.DENY_ENV_KEYS: added Windows TMP/TEMP alongside TMPDIR so a crafted plan can't redirect temp-file creation on Windows.
Tests:
- install: assert the thrown error is instanceof ProviderInstallError; new it.each covering TMP/TEMP/tmp rejection (case-insensitive).
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(vscode): log error class name not message in snapshotSettingsForRollback
Consistency with the err.constructor.name approach applied in provider-config.providerMatchesCredentials. The risk here is lower (the catch is filesystem errors from readSettings/structuredClone, not user-defined functions), but logging only the class name keeps the security stance uniform across the codebase.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
---------
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix: pin fetch to bundled undici for Node.js 26 (undici 8.x) compat
Node.js 26 bundles undici 8.x, which differs from the project's undici 6.x.
Using Node's built-in fetch mixed with ProxyAgent/Client from the bundled
undici causes handler-interface mismatches (e.g. 'invalid onError method').
* fix(core): export undici fetch alongside proxy dispatcher to avoid version mismatch
for review of #4238
When a custom dispatcher (ProxyAgent) is passed, pin fetch to the bundled undici's implementation so both share the same undici version. Without this, Node's built-in fetch (e.g. undici v8) rejects a ProxyAgent from the bundled undici (e.g. v6) with "invalid onError method".
* fix: move pinning fetch alongside with dispatcher in runtimeOptions, change back default.ts
* docs(core): update code comment reference in runtimeFetchOptions test
* feat(cli): add session path status command
* fix(cli): add status paths translations
* fix(core): use secure subagent id suffix
* fix(cli): harden status paths log lookup
* fix(cli): use secure prompt id randomness
* test(cli): cover status paths formatting
* feat(cli): per-turn /diff with interactive dialog (#4272)
`/diff` now opens an interactive dialog in TUI mode with:
- Current (working tree vs HEAD) plus one entry per past user turn
- ←/→ to switch source, ↑/↓ to select a file, Enter for hunks, Esc to close
- File list paginates at 8 entries, with new/deleted/untracked/binary tags
Per-turn diffs are computed by FileHistoryService.getTurnDiff(promptId),
which compares the snapshot at the start of that turn against the next
snapshot (or the live worktree for the most recent turn). Files the
snapshotter failed to capture are skipped rather than rendered against a
stale predecessor.
Non-interactive and ACP modes keep the existing plain-text summary so
pipes, logs, and remote transports are unchanged.
* refactor(core): align getTurnDiff promptId lookup with findSnapshot
Two small audit-driven cleanups, no behavior change in normal sessions:
- Match findSnapshot's last-occurrence-wins semantics so /rewind and
/diff agree if a promptId is ever reused (defensive — promptIds are
unique per submission in practice).
- Drop the redundant `?? undefined` in the fast-path skip; `?.` already
short-circuits to undefined, so the extra coalesce was noise.
* fix(cli): head-truncate file paths in diff dialog to keep layout intact
Long absolute paths (~> 90 chars) previously overflowed the dialog and
wrapped, shattering the file-list and detail-view alignment. Reserve a
fixed budget for the tag/stats columns, head-truncate the path with a
leading ellipsis so the basename — the part users actually read — is
always visible.
Also drop the dead MAX_FILES_FOR_DETAILS guard from currentToFiles:
fetchGitDiff already bounds perFileStats at MAX_FILES (=50), and returns
an empty map when the diff exceeds MAX_FILES_FOR_DETAILS upstream, so
the 500-entry counter could never fire.
* fix(diff): address review comments — backup-read safety, oversized cap, sanitization, Ctrl+C routing
Five review-driven fixes; details inline on the PR.
Core (getTurnDiff):
- Treat unreadable backup files as "unavailable" (return null for the
row) instead of coercing to '' and fabricating phantom hunks. Same
guard for both before and after endpoints.
- Cap structuredPatch input at MAX_DIFF_SIZE_BYTES so a single multi-MB
file in history can no longer balloon TUI memory when /diff opens.
Oversized rows still surface in the file list with best-effort line
stats and a new `oversized` flag.
CLI (DiffDialog):
- Distinguish over-large dirty trees (filesCount > 0 but empty
perFileStats) from a clean tree; the empty state now reports the
capped file count and totals instead of claiming "Working tree is
clean."
- Render the `oversized` flag with an explicit "(oversized — diff
omitted)" tag in the file list and a corresponding detail-view note.
Sanitization (#4):
- Move sanitizeFilenameForDisplay from diffCommand.ts into the shared
textUtils module, apply it to every path rendered in DiffDialog
(file rows, detail header, empty messages, DiffRenderer filename
prop, generated unified-diff envelope), and keep raw paths for map
lookups via a separate UnifiedFile.displayPath field.
Ctrl+C routing (#7):
- Register isDiffDialogOpen / closeDiffDialog with useDialogClose so
Ctrl+C dismisses the dialog through the centralized handleExit path,
matching how the background-tasks dialog is wired. Drop the dialog's
internal Ctrl+C handler to avoid double-fire that would close the
dialog AND escalate to the exit prompt.
Tests: 2 new core regression tests (unreadable backup, oversized cap)
plus the existing 35 still pass. CLI tests for diff/slashCommand/
AppContainer paths unchanged at 148/148.
* fix(diff): second review round — candidate scope, binary, concurrency, semantics
Addresses 14 of 19 outstanding review comments. Per-thread detail will
be replied on the PR.
Correctness (P0):
- Restrict getTurnDiff candidates to keys(target.trackedFileBackups).
Files first tracked in turn N+1 no longer get phantom-attributed to
turn N. Drop the now-redundant union with state.trackedFiles for the
latest-turn case (makeSnapshot guarantees state.trackedFiles ⊆
keys(latest.trackedFileBackups)).
- Add `beforeBackup !== undefined` guard to the fast-path skip so a
future broadening of the candidate set can't silently collapse a
newly created file as "unchanged".
- Add binary detection via NUL-byte sniff (`looksBinary`, mirrors git's
heuristic). New `TurnFileDiff.isBinary` flag short-circuits hunk
generation; the dialog renders the existing italic "binary" marker
instead of feeding raw bytes to DiffRenderer.
- Cap per-turn concurrent file reads at MAX_TURN_DIFF_FILES=500 so a
500-file turn won't issue 1000+ simultaneous open()s and hit the
process fd ceiling.
UX / stability:
- Stabilize the dialog's keypress handler with `useCallback(()=>..,[])`
reading state via refs, eliminating subscribe/unsubscribe churn on
every render.
- Disentangle `isNewFile` (snapshot-derived, "added in this turn")
from `isUntracked` (git "never tracked") in perFileToUnified so
untracked files no longer get mislabeled as "(new)" — they could
not be recovered by /rewind, and the wrong tag implied otherwise.
- Reorder FileRow tag priority around the disentangled flags; remove
duplicate "(binary)" tag (the stats column already shows it italic).
- Drop the early-exit `useEffect` clamps for sourceIndex / fileIndex
in favor of inline `Math.min` derivations; effect-based clamping
caused an extra render frame that could look like a flicker in Ink.
- Inner `cancelled` checks in useTurnDiffs reduce wasted disk I/O when
the dialog is closed mid-load.
- Guard hunksToUnifiedDiff against empty hunk arrays (would otherwise
hand DiffRenderer a header-only string).
- Surface "…and N more (showing first M)" indicator for the Current
source when fetchGitDiff capped perFileStats at MAX_FILES.
- useDiffData JSDoc clarifies the snapshot-at-open semantics; catch
branches now console.debug the underlying error instead of swallowing
silently.
Tests:
- 3 new core regression tests: deleted-during-turn detection, binary
detection, and the cross-turn attribution boundary. fileHistoryService
tests now at 40/40.
Pending review comments (deferred): the lazy-load suggestions remain
intentionally deferred per the earlier reply chain; the MAX_DIFF_SIZE
cap landed in the prior round mitigated the underlying memory risk.
* fix(diff): third review round — per-file isolation, ENOENT semantics, binary tail scan
Six review-driven correctness fixes; details inline on the PR.
Core:
- `readEndpointContent` now distinguishes ENOENT (genuine deletion) from
other read failures (EACCES/EISDIR/EBUSY/decoding) on the live
worktree branch. Previously every failure collapsed to `exists:false`
and produced a phantom delete hunk for files whose perms changed
mid-session.
- `computeTurnFileDiff` is wrapped in per-file try/catch so a single
`structuredPatch` crash or transient read error can no longer poison
the whole turn's `Promise.all` and silently erase every row.
- `looksBinary` now scans both the head AND the tail of the string. The
head-only scan could be defeated by an 8KB+ text prefix in front of a
binary payload; the oversized cap (1 MB) bounds the work either way.
- `getTurnDiff` calls the existing `findSnapshotIndex` helper instead of
inlining a duplicate reverse-scan loop, so a future change to
`findSnapshot`'s tie-break rules can't silently desync /rewind and /diff.
UI:
- Add `hasHunks` to `UnifiedFile` and gate Enter on it. Untracked files
don't appear in `git diff HEAD` output, and capped/oversized turn
entries have empty hunks — pressing Enter on those previously landed
the user on a dead-end "No hunks available" screen.
- Drop the misleading `total > MAX_LINES_PER_FILE` heuristic from
`perFileToUnified`'s `truncated` flag. `s.truncated` (from
`parseGitNumstat`) is the only authoritative source — the OR was
conflating "untracked file too big to count" with "tracked file with
many accurately-counted lines", incorrectly flagging the latter.
Tests:
- 1 new core regression test: live-worktree EISDIR failure must not be
reported as a deletion. fileHistoryService tests now at 41/41.
* fix(diff): fourth review round — diagnostics, paths, UX feedback
- Deterministic candidate cap in getTurnDiff: sort trackedFileBackups
keys before slicing at MAX_TURN_DIFF_FILES; emit debugLogger.warn
when truncating so the dropped count is traceable.
- Log unreadable before/after endpoints in computeTurnFileDiffUnsafe
instead of dropping rows silently — backup corruption, permission
flips and EISDIR now leave a trace.
- Return trackingPath as TurnFileDiff.filePath (already repo-relative
via maybeShortenFilePath) so per-turn rows match the Current source
on narrow terminals. The internal absolute path is kept only for
live-worktree I/O.
- useDiffData: replace bare console.debug with createDebugLogger
('DiffDialog') to match project convention.
- DiffDialog: show a transient warning-coloured hint in the footer
when Enter lands on a binary / oversized / no-hunks row (cleared on
the next navigation key) so the keypress isn't silently consumed.
- useDialogClose: swap diff-dialog and background-tasks branches to
match DialogManager render order — Ctrl+C now dismisses whichever
dialog the user actually sees when both flags are open.
- useTurnDiffs: sanitize previewOfUserItem via escapeAnsiCtrlCodes so
prompt previews on the source tabs can't reach the terminal raw
(matching the chat-history defense).
- Tests: expect repo-relative filePath in getTurnDiff regression
cases; add `warn` to the mocked debugLogger.
Refs PR #4277 review comments 3259062434, 3259062465, 3264541365,
3259062480, 3259062498, 3264541346, 3264541351.
* fix(diff): fifth review round — OOM guard, concurrency cap, type safety
- readEndpointContent now stats both worktree and backup paths before
readFile and returns a `{ kind: 'oversized' }` sentinel when the
file exceeds MAX_DIFF_SIZE_BYTES. computeTurnFileDiffUnsafe handles
the sentinel without allocating, so a 2 GB write_file blob no longer
lands in the Node heap just to be rejected downstream.
- useTurnDiffs now batches `getTurnDiff` calls at TURN_CONCURRENCY = 4
instead of an unbounded Promise.all across every user turn. Prevents
EMFILE on long sessions (worst case ~4000 fds vs. unbounded N × 1000).
- Add `filesOmitted` to `TurnDiff.stats` and plumb it through the
dialog's `hiddenFileCount` so per-turn rows now also surface "…and N
more" when MAX_TURN_DIFF_FILES truncates the candidate list (matches
the Current source's existing behavior).
- Make isRealUserTurn a type predicate (`item is HistoryItem &
HistoryItemUser`) so callers in useTurnDiffs drop both `as` casts —
a future regression that loosens either side will now be caught by
tsc rather than silently bypassing the narrowing.
- Add trailing `.catch()` to the Promise.all chains in useDiffData and
useTurnDiffs so a thrown setState during unmount doesn't propagate
to Node 22+'s default unhandled-rejection terminator. Both branches
log via createDebugLogger and unstick `loading`.
- Tighten the comment above the diff/background-tasks branch in
useDialogClose: the invariant is scoped to that pair, not a
full mirror of DialogManager's render priority.
- Add focused unit tests for sanitizeFilenameForDisplay (C0 controls,
DEL + C1, multi-byte ANSI CSI, mixed crafted paths, clean
passthrough) — security-relevant function previously untested.
Refs PR #4277 review comments 3265032536, 3265032548, 3265032551,
3265032556, 3265032560, 3265032569, 3265032574.
* fix(diff): sixth review round — discriminated union, TOCTOU, tests
- Refactor EndpointRead into a proper discriminated union with explicit
`kind: 'ok' | 'unreadable' | 'oversized'`. Removes the six manual
`as EndpointReadOk / as EndpointReadOversized` casts in
computeTurnFileDiffUnsafe; branch narrowing is now driven by tsc.
- Close the stat()-then-readFile() TOCTOU window. Replace the separate
syscalls with `open()` + `fh.stat()` + `fh.readFile()` against a
single file descriptor, so a concurrent write_file appending to the
same path between calls can't grow past MAX_DIFF_SIZE_BYTES and slip
the OOM guard. Shared helper readPathWithSizeGuard handles both
worktree and backup endpoints (worktree ENOENT → absence, backup
ENOENT → unreadable to match prior semantics).
- Document filesOmitted as an upper bound on candidates dropped at the
cap (some may have been unchanged; we can't know without paying the
read the cap was specifically meant to avoid). Surface that in the
dialog's truncation indicator: turn sources now read "…and up to N
more (showing first M)" while Current keeps the exact wording.
- Tests: 3 new fileHistoryService cases covering the live-worktree
oversized branch (single-snapshot path), mixed-size endpoints (small
before + oversized after) exercising the discriminated-union narrowing,
and a baseline filesOmitted === 0 regression. 7 new renderHook tests
for useTurnDiffs covering disabled / missing-service short-circuits,
filtering of slash/no-promptId/empty-diff turns, most-recent-first
ordering, per-turn error isolation, batch progression beyond
TURN_CONCURRENCY, and the in-flight concurrency cap itself.
Refs PR #4277 review comments 3267108813, 3267108827, 3267108831,
3267108839, 3267108847.