mirror of
https://github.com/QwenLM/qwen-code.git
synced 2026-07-09 17:19:02 +00:00
150 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
2786afb2b5
|
fix(core): compact on the window ceiling, not the max of the threshold ladder (#6583)
* fix(core): compact on the window ceiling (min), not the max of the ladder
computeThresholds combined the proportional term (pct*window) and the
absolute term (effectiveWindow - AUTOCOMPACT_BUFFER) with Math.max, which
pushed the auto-compaction trigger toward the top of the window on large
windows — a 1M-token window compacted at ~97%, leaving ~33K headroom.
The absolute term is structurally a ceiling ("compact before the prompt
leaves too little room for the summarization side-query, which needs up
to SUMMARY_RESERVE of output"), so it composes with Math.min, matching
the claude-code reference (services/compact/autoCompact.ts, which uses
Math.min and whose default trigger is the absolute term alone).
auto = absoluteCeiling > 0 ? min(pct*window, absoluteCeiling) : pct*window
warn = max(0, auto - WARN_BUFFER) // WARN_PCT_OFFSET retired
hard = unchanged
Effect: large windows compact at ~85% (the DEFAULT_PCT ceiling) instead
of ~97%; small/mid windows keep room to run compaction (a 128K window's
summary now provably fits); sub-33K windows are unchanged. A lower
context.autoCompactThreshold now pulls compaction earlier on large
windows, matching the reference's Math.min override semantics.
Updates the threshold unit tests, the settings schema description, and
the user docs to describe the setting as a ceiling on the trigger.
* refactor(core): trim threshold doc comments; name the hard-edge term
Post-review cleanup (no behavior change):
- Collapse the duplicated regime explanation shared between the DEFAULT_PCT
and computeThresholds doc comments into one canonical block; point the
constant's doc at computeThresholds.
- Rename rawHard -> hardEdge and note it is the window-edge ceiling, so the
two roles of the hard tier (window edge vs. auto + HARD_BUFFER) are legible.
- Shorten the context.autoCompactThreshold description in settings.md to the
concise schema wording (also un-widens the docs table).
|
||
|
|
1144e2dcee |
Merge remote-tracking branch 'origin/main' into fix/max-tokens-window-clamp
# Conflicts: # packages/core/src/core/openaiContentGenerator/pipeline.ts |
||
|
|
b3e2996a85 |
fix(core): clamp max_tokens to the context window; retire the output reservation
Auto-compaction was firing far too early — a 200K-window session compacted at roughly half the window. The cause was not the compaction engine but that every request manufactured a large max_tokens, which forced a defensive reservation of that output budget out of the window before computing compaction thresholds. The reservation shrank the effective window, pulled the trigger down, and spawned a chain of band-aids. Size max_tokens to the room actually left in the window instead — the smaller of the model's output ceiling and (window − prompt − margin) — so an oversized request can never exceed the context limit. Once output is guaranteed to fit, the reservation is unnecessary and is removed; compaction gates on the full window again. Raise the default proportional threshold from 0.70 to 0.85, and replace the temporary half-window reservation cap with a flat 64K output ceiling. This resolves early compaction, the 400 "maximum context length" error on request, the "hard limit: 0" pre-send NOOP for env-configured models, and retires the half-window reservation cap, while keeping max_tokens on the wire for both OpenAI- and Anthropic-shaped providers. Fixes #5950 Fixes #6384 Claude-Session: https://claude.ai/code/session_014DW2TynKHLjsbRqTBSyQue |
||
|
|
0a54652e07
|
fix(core): configurable vision bridge timeout + retry with fresh budget (#6541)
* fix(core): configurable vision bridge timeout + retry with fresh budget The vision bridge capped image transcription at a hardcoded 30s. On a slow or proxied vision endpoint one latency spike permanently lost the image: the retry inside the side query shared the same abort signal, so a second attempt inherited whatever seconds were left of the first attempt's budget. Add a visionBridgeTimeoutMs setting (per attempt; unset keeps 30s, non-positive values are ignored) and retry a timed-out attempt once at the bridge level with a freshly created timeout signal. Non-timeout failures still fail immediately, and user cancellation is still reported as skipped. Fixes #6524 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(core): harden visionBridgeTimeoutMs against invalid timer values Maintainer E2E review found that fractional or out-of-range values such as 30000.5 and 4294967296 could pass the old number-typed config path and Config's Number.isFinite && > 0 guard. Node rejects fractional AbortSignal.timeout values with RangeError and can degrade oversized timer values to a 1ms timeout, which made image turns fail before any model request. Tighten the Config guard to positive integers within the supported 32-bit timer ceiling, make visionBridgeTimeoutMs a bounded integer setting so /config and the generated JSON schema reject bad values up front, and move AbortSignal.timeout/any creation inside the bridge try block so any future bad value becomes a safe failure result instead of an escaped rejection. Also mark the setting requiresRestart because it is read once in the Config constructor. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
6dafb330f2
|
docs: fix model-provider config shape and refresh feature/setting drift (#6552)
Audit findings against the current codebase:
- model-providers.md, auth.md: the documented modelProviders shape used
the reverted `{ protocol, models }` wrapper. The canonical shape is a
bare `ModelConfig[]` array per provider id (a wrapped entry in a
migrated settings file is silently skipped). Update all examples and
prose, document the separate top-level `providerProtocol` map for
custom provider ids, and correct the unknown-key behavior.
- settings.md: correct the default for
`model.chatCompression.screenshotTriggerThreshold` (20, not 50).
- commands.md: add the missing `/reload-plugins` command and note that
`/dream` and `/forget` are registered only when managed auto-memory
is available.
- Add a Computer Use feature page (on-by-default desktop automation via
the cua-driver native driver) and wire it into the features nav and
the qc-helper doc index.
Co-authored-by: Claude <noreply@anthropic.com>
|
||
|
|
87cad6f1ae
|
feat(memory): make background memory agent timeouts configurable (#6459)
* feat(memory): make background memory agent timeouts configurable Adds a memory.agentTimeoutMinutes setting that overrides the hardcoded max runtime of the four background memory agents (extraction, dream, remember, skill review). Unset keeps each agent's built-in default (2-5 minutes); 0 disables the time limit entirely. Local LLM setups load large extraction prompts far slower than hosted models, so the fixed 2-minute extractor budget times out before the context even finishes loading — and each retry carries a longer conversation, making the next timeout more likely. Fixes #6308 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(memory): address review — wire agentTimeoutMinutes to skill review, clamp negatives, add tests The auto-skill scheduling path always passed an explicit timeoutMs, so the new setting never reached the skill review agent; drop the redundant pass-through so the planner's config fallback applies. Clamp negative settings values at the Config constructor (schema validation only runs on interactive edit paths). Add positive override tests for the dream, remember, and skill review planners, and reduce the settings.md diff to the single new table row. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(memory): cover negative-clamp and remember default-timeout paths Review follow-up: assert the Config constructor treats a negative memory.agentTimeoutMinutes as unset, and that the remember planner keeps its built-in 5-minute default when nothing is configured. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com> |
||
|
|
be0b0749c1
|
docs: fix settings.json reference drift against schema (#6351)
Correct and complete the user-facing settings documentation against packages/cli/src/config/settingsSchema.ts: - settings.md: fix general.defaultFileEncoding type (enum, not string); document the general.voice.* dictation settings, top-level modelFallbacks and modelPricing, tools.computerUse.idleTimeoutMs, mcp.toolIdleTimeoutMs, and the skills.disabled denylist. - model-providers.md: correct the resolution-layers table — only --openai-api-key/--openai-base-url exist; there are no provider-specific credential CLI flags. Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
e1f5d21008
|
fix(core): treat request timeout of 0 as disabled instead of aborting immediately (#6288)
* fix(core): treat request timeout of 0 as disabled instead of aborting immediately A provider `generationConfig.timeout` of `0` (and `QWEN_CODE_API_TIMEOUT_MS=0`) now disables the request timeout, matching the existing `QWEN_STREAM_IDLE_TIMEOUT_MS=0` convention, instead of being coerced to the 120s default (Anthropic `||`) or passed to the OpenAI SDK as `timeout: 0` (which the SDK treats as an immediate abort). - add `resolveRequestTimeout()` + `DISABLED_REQUEST_TIMEOUT_MS`, mapping a disabled timeout to the JS timer ceiling (2^31-1 ms), reusing the same ceiling already used for `MAX_STREAM_IDLE_TIMEOUT_MS` - use it in the OpenAI default/dashscope providers and the Anthropic provider - accept `0` in the `QWEN_CODE_API_TIMEOUT_MS` env override without weakening the shared `parsePositiveIntegerEnv` (relied on by ~15 other callers to reject 0) - document the timeout unit and 0-disables semantics in settings.md Fixes #6049 * Update packages/core/src/core/openaiContentGenerator/provider/dashscope.test.ts Co-authored-by: qwen-code-ci-bot <qwen-code-ci@service.alibaba.com> * test(core): fix broken constants mock merge in dashscope.test Commit 0f5aa0c interleaved two vi.mock('../constants.js') blocks, leaving orphaned fragments that produced TS syntax errors and stopped the dashscope suite from loading. Replace with a single importOriginal-based mock that overrides only DASHSCOPE_PROXY_BASE_URL and delegates every other constant (timeouts, DISABLED_REQUEST_TIMEOUT_MS, resolveRequestTimeout) to the real module, so the mock cannot drift from the implementation. --------- Co-authored-by: qwen-code-ci-bot <qwen-code-ci@service.alibaba.com> |
||
|
|
cdf83d8bd0
|
fix(core): give Stop-hook continuations a fresh per-turn tool-call budget; make the cap configurable (#6238)
* fix(core): give Stop-hook continuations a fresh per-turn tool-call budget; make the cap configurable A blocking Stop-hook continuation (e.g. a /goal iteration) feeds a fresh user-role prompt to the model — a new logical turn — but the loop detector never reset, so an entire goal chain billed one per-turn tool-call budget and healthy long-running goals halted with turn_tool_call_cap. The ACP daemon path already used per-continuation budgets; core now matches. - Reset loop detection at each blocking Stop-hook continuation - Add model.maxToolCallsPerTurn setting (default 100; <= 0 disables), resolved once in Config (<= 0 maps to Infinity) - Honor the in-session 'Disable loop detection for this session' choice in the per-turn cap, as the dialog always claimed - Point the headless halt message at the setting; update dialog/docs * test(cli): add DEFAULT_MAX_TOOL_CALLS_PER_TURN to core module mocks --------- Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com> |
||
|
|
fe3dd93e8f
|
Add sessionless workspace memory forget and dream (#6227)
* feat(serve): add sessionless memory forget and dream * fix(serve): thread abort through memory forget * fix(serve): address workspace memory review feedback * fix(serve): address memory review follow-up * fix(memory): harden forget review paths * fix(serve): classify memory availability failures * fix(serve): document memory task capacity tiers * fix(memory): address review edge cases * chore: remove mobile-mcp formatting noise |
||
|
|
9658dccfbb
|
feat(daemon): add session artifact APIs (#5895)
* docs: add session artifacts daemon API design * docs: tighten session artifacts design scope * docs: frame artifacts API as complete v1 capability * docs: address artifacts review follow-ups * docs: clarify artifacts reset boundary * docs: clarify batch hook artifact flow * docs: address latest artifact design audit * docs: tighten artifact event and store semantics * docs: simplify artifact v1 merge policy * docs: resolve artifact v1 review blockers * docs: tighten artifact trust and retention semantics * docs: close artifact v1 boundary gaps * feat(daemon): add session artifact APIs * fix(daemon): harden session artifact semantics * fix(sdk): update daemon browser bundle budget * fix(daemon): tighten artifact ingestion boundaries * fix(daemon): cache artifact workspace realpath * fix(daemon): sanitize artifact add dispatch input * docs(daemon): align artifact change wire shape * fix(daemon): harden artifact status validation * test(daemon): cover artifact acp dispatch * test(daemon): update artifact capability baseline * fix(daemon): clear workspace locator on published artifacts * fix(core): forward post-tool batch artifacts * fix(daemon): harden artifact status refresh * fix(daemon): guard artifact event ingestion * test(daemon): cover non-strict artifact drops * fix(core): align artifact display validation * fix(daemon): serialize artifact store operations * chore(daemon): clarify artifact publisher tool name * fix(daemon): coordinate artifact route mutations * fix(daemon): harden artifact refresh comparison * fix(daemon): harden artifact ingress edge cases * fix(daemon): guard artifact rpc mutations during archive * fix(daemon): gate session metadata mutation auth * fix(daemon): harden artifact route boundaries * fix(channels): compact drained group history * fix(daemon): address artifact review findings * fix(daemon): address artifact review follow-ups * fix(daemon): preserve hook artifact success output * fix(daemon): handle artifact review edge cases * fix(daemon): address artifact review hardening * test(daemon): cover artifact review edge cases * fix(daemon): validate hook artifact aggregation * fix(daemon): improve artifact ingestion diagnostics * fix(daemon): address artifact review feedback * fix(daemon): address artifact review feedback * fix(daemon): harden session artifact ingress * fix(daemon): harden artifact edge cases * fix(daemon): tighten artifact path validation * fix(daemon): address artifact review races * fix(daemon): surface artifact path inspection errors * fix(daemon): forward batch hook artifacts in ACP * fix(daemon): clean artifact bridge metadata * test(daemon): cover artifact store edge cases * fix(daemon): resolve artifact file url symlinks * fix(daemon): harden artifact ingestion paths * fix(daemon): harden artifact review paths * test(daemon): cover artifact tool name sync * fix(daemon): harden artifact republish validation * chore(daemon): remove unrelated artifact PR churn * fix(daemon): address artifact review gaps * test(daemon): cover artifact url rejection * chore(daemon): drop unrelated formatting churn * chore(daemon): update settings schema * fix(daemon): harden artifact validation * fix(daemon): tighten artifact event validation * docs(core): clarify artifact env flag comment * test(cli): align soft failure artifact expectation * fix(daemon): address artifact review edge cases * fix(daemon): enable artifact metadata recording * fix(daemon): harden artifact store review paths --------- Co-authored-by: 秦奇 <gary.gq@alibaba-inc.com> Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com> |
||
|
|
0633b8a985
|
feat(scheduler): make recurring cron/loop job expiration configurable (#6173)
* feat(scheduler): make recurring cron/loop job expiration configurable Recurring cron/loop jobs previously auto-expired after a hardcoded 7 days with no way to extend or disable the limit, forcing long-running daemon deployments to recreate jobs weekly. Add an experimental.cronRecurringMaxAgeDays setting (default 7) and a QWEN_CODE_CRON_MAX_AGE_DAYS environment-variable override (takes precedence, for cloud/container deployments). A value of 0 disables expiry so jobs run until deleted; negative or unparseable values fall back to the 7-day default. The configured limit also applies to durable tasks restored from disk, and the CronCreate tool description now reflects the effective limit instead of a hardcoded '7 days'. Closes #6167 * refactor(scheduler): drop unused DEFAULT_RECURRING_MAX_AGE_MS export Review feedback on #6173 — the ms constant is only used inside the module as the constructor default; keep only the days constant public. * fix(scheduler): align zero max-age semantics and warn on cron expiry misconfiguration Review feedback on #6173: - CronScheduler constructor now maps 0 to Infinity (never expire), matching the config layer instead of silently substituting the 7-day default for direct callers. - Invalid QWEN_CODE_CRON_MAX_AGE_DAYS / cronRecurringMaxAgeDays values now log a warning before falling back to the default, leaving a breadcrumb for misconfigured deployments. - Durable tasks found past the recurring max age at load now log a warning before their final fire + delete, since a lowered max age retroactively expires long-lived tasks and deletion is unrecoverable. - New durable-restore tests: a custom max age applies to tasks reloaded from disk, and a disabled max age (Infinity) restores a 30-day-old task as live instead of aging it out. * fix(scheduler): surface cron expiry warnings on the console Review feedback on #6173: - The invalid-config and retroactive-expiry warnings moved from debugLogger (file-only, off unless QWEN_DEBUG_LOG_FILE is set) to console.warn so they reach container/daemon logs where this knob matters; the config warning is latched to fire once per Config instance. - CronCreateTool's constructor now resolves the max age once instead of three times, so an invalid env var can't emit duplicate warnings during tool registration. * fix(scheduler): reject non-finite timestamps in durable task validation Review feedback on #6173: JSON like -1e999 parses to -Infinity, which passes the typeof-number check and then poisons date math — with a finite lastFiredAt the entry reads as an overdue aged task and the retroactive-expiry warning's toISOString() throws RangeError mid-load, so one malformed persisted entry blocks durable cron startup/takeover. Validation now requires finite createdAt (and lastFiredAt when non-null), routing such entries through the existing fix-or-delete contract for corrupt files. Verified the new end-to-end test reproduces the RangeError without the fix. * refactor(scheduler): single-source the max-age contract and freeze it at Config construction Review follow-ups on #6173: - Extract normalizeRecurringMaxAge as the single owner of the 0/Infinity no-expiry contract, used by both the Config layer and the CronScheduler constructor, so the constructor's 0 handling can no longer be removed as apparent dead code. - Resolve QWEN_CODE_CRON_MAX_AGE_DAYS once at Config construction into a readonly field, honoring the setting's requiresRestart contract; mid-session env changes can no longer make the tool description, tool output, and scheduler report different expiries. The warn once-latch is now unnecessary (construction warns at most once). |
||
|
|
8de93b876b
|
feat(core): allow sub-agents to spawn nested sub-agents up to a configurable depth (#6189)
* feat(core): allow bounded nested sub-agent spawning via maxSubagentDepth Sub-agents may now spawn sub-agents up to a configurable maximum nesting depth (default 5; 1 reproduces the previous no-nesting behavior). Enforced in two layers sharing one predicate: prepareTools() hides the agent tool from leaf-depth sub-agents, and AgentTool.execute() rejects over-depth spawns as an authoritative backstop. Teammates, forks, and the workflow tool remain excluded from nesting. Launch depth is persisted in the agent meta sidecar and restored on resume (including deferred-approval continuations and in-process AgentInteractive frames) so a resumed nested agent cannot regain spawn capacity. See knowledge/qwen-code/design/nested-subagents.md. * fix(core): address review findings on nested sub-agent spawning - Deny the agent tool to workflow-spawned subagents: depth gating would otherwise re-admit it, letting a workflow leaf spawn outside the orchestrator's concurrency cap, agent accounting, and token budget. - Reject non-finite maxSubagentDepth values (JSON 1e309 parses to Infinity and would unbound the recursion cap; NaN would silently block all nesting) and cap the knob at 100 to catch typos. - Add a --max-subagent-depth CLI flag mirroring sibling budget flags, with loud validation for flag typos, and document the setting. - Log guard rejections (depth, fork containment) and silent fork-to-subagent downgrades through the agent debug logger. - Refresh stale comments (depthOverride resume pinning, depth-gated AgentTool exclusion) and drop references to a design doc that lives outside the repository. - Fill review-noted test gaps: nesting predicate primitives, fork-context prepareTools, persisted-depth restoration on background resume, nested AgentInteractive depth pinning, nested fork fallback, and the blocked-spawn returnDisplay shape. * fix(cli): add maxSubagentDepth to the CliArgs test literal The exhaustive CliArgs mock in gemini.test.tsx missed the new field, failing CI's clean tsc build (the local incremental build skipped the test file). * fix(core): add a teammate backstop to the agent spawn guards execute() backstopped depth and fork containment but not the teammate exclusion, so its guards covered less than prepareTools() gates. A teammate spawn call that slipped past schema-hiding would have nested. Block it symmetrically with the fork guard, log the rejection, and pin the behavior in a test. * fix(core): normalize persisted maxSubagentDepth on resume The resume path trusted the raw sidecar value, bypassing the Config clamp — a tampered or malformed sidecar (1e309 parses to Infinity; JSON.stringify turns Infinity into null) would remove the nesting cap for resumed agents. Extract the clamp into a shared normalizeMaxSubagentDepth used by both the Config constructor and the flag-restore path, and refresh the stale settings schema description (clamp range, non-finite fallback, workflow-agent wording). * test(core): pin null-to-default normalization of resumed maxSubagentDepth JSON.stringify(Infinity) === 'null', so a sidecar can legitimately carry null; widen the persisted flag type to admit it and parameterize the resume test over both the clamp (5000 -> 100) and the null fallback (null -> 5). * fix(core): harden nesting depth edges from final review pass - Normalize persisted meta.depth on resume: the sidecar is untrusted JSON, and a tampered negative depth (or -1e309 → -Infinity) would pin the resumed frame below zero and pass canSpawnNestedAgent for every cap. Invalid values fail closed to the depth ceiling — the agent keeps running but cannot spawn. - Register monitor notification routing for in-process interactive agents: framing runLoop() made their monitors agent-owned, and owned dispatch has no session fallback, so notifications were silently dropped. InProcessBackend now routes them into the agent's message queue and tears the routing down on release. - Downgrade background spawn requests from nested launchers to awaited foreground runs: a nested launcher cannot honor the background completion contract (send_message/task_stop excluded, notifications session-scoped), which orphaned the child's results. - Extract spawnBlockReason() as the single spawn-exclusion policy shared by prepareTools() and execute(), replacing two hand-kept copies of the depth/teammate/fork rules. - Share DEFAULT_MAX_SUBAGENT_DEPTH / MAX_SUBAGENT_DEPTH_LIMIT across the core normalizer, the CLI flag validator, and the settings schema. - Log dropped teammate names from nested spawns; revert the impossible |null persisted-flag widening to an honest tampered-sidecar framing; document the constructor-time depth capture invariant. * test(cli): add DEFAULT_MAX_SUBAGENT_DEPTH to core package mocks settingsSchema.ts now imports the shared constant, so CLI tests that mock @qwen-code/qwen-code-core with an explicit export list need the new export. * feat(cli): display nested sub-agents as a tree in the TUI (#6191) * feat(core): allow bounded nested sub-agent spawning via maxSubagentDepth Sub-agents may now spawn sub-agents up to a configurable maximum nesting depth (default 5; 1 reproduces the previous no-nesting behavior). Enforced in two layers sharing one predicate: prepareTools() hides the agent tool from leaf-depth sub-agents, and AgentTool.execute() rejects over-depth spawns as an authoritative backstop. Teammates, forks, and the workflow tool remain excluded from nesting. Launch depth is persisted in the agent meta sidecar and restored on resume (including deferred-approval continuations and in-process AgentInteractive frames) so a resumed nested agent cannot regain spawn capacity. See knowledge/qwen-code/design/nested-subagents.md. * feat(cli): display nested sub-agents as a tree in the TUI Render nested agents depth-first with indent + dim '↳' in the live agent panel and background tasks view; promote orphaned children to root with a '· from <parent>' annotation. Detail view gains a level badge, Parent breadcrumb, and Sub-agents section. The [blocking] tag and two-step cancel confirm now apply only to provably user-blocking foreground chains. Parent completion summaries carry a '· N sub-agents' tail (guard-rejected spawns now record as failed tool calls so the count stays honest). Also fixes the live-panel Enter-for-detail order mismatch by sharing one display order between the panel render and the composer keyboard mapping. * fix(core): address round-1 review on nested sub-agent spawning - Derive launch metadata (hooks, spans, task rows, meta sidecar) from the resolved subagent config instead of the raw requested type, so a fork request that falls back to the awaitable path no longer reports "fork". - Pin the blocked-spawn failure contract in tests: error is set and returnDisplay.status is 'failed' for both the depth and fork guards; also document the failure-path routing at buildSpawnBlockedResult. - Drop source-comment references to private knowledge/ design docs that do not exist in this repository. * test: address round-2 review on sub-agent counting and fork fallback - Exercise the legacy 'task' alias in the scrollback sub-agent count so the migration-aware name set is covered, not just the canonical name. - Pin the nested-fork downgrade: a sub-agent requesting a fork falls back to the awaitable general-purpose subagent even in interactive mode. - Drop a duplicated 'nesting depth guard' describe block left behind by the automated base-branch merge (kept the copy with the failure-shape assertions). * fix(core): keep actionable guidance in blocked-spawn error messages The scheduler's failure path sends only error.message to the model and the scrollback, discarding llmContent. With the terse terminateReason as the message, a blocked spawn lost its "do the task yourself instead" instruction, inviting retry loops. Carry the full guidance text in error.message and keep terminateReason for the display card. * test(cli): pin the tree indent clamp at depth beyond TREE_INDENT_MAX_LEVELS Maintainer mutation-testing on the PR found that removing the clamp in treeRowPrefix survived the suite. Assert a depth-4 row indents 3 levels (12 spaces), plus the base marker/indent behavior. --------- Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com> --------- Co-authored-by: qwen-code-dev-bot <qwen-code-dev-bot@users.noreply.github.com> |
||
|
|
dc8e155927
|
docs: correct stale CLI flags/keybinding and document model.reasoningEffort (#6219)
- Remove nonexistent --all-files/-a and --show-memory-usage flags from the CLI arguments and headless option tables (no longer defined in the yargs parser in packages/cli/src/config/config.ts). - Add the commonly-needed --model/-m flag to the headless options table and fix the --approval-mode example to use the valid choice auto-edit (the parser rejects the underscore form auto_edit). - Drop the stale Meta+Enter alias from the external-editor shortcut; that chord is bound to NEWLINE, while OPEN_EXTERNAL_EDITOR binds only Ctrl+X. - Document the model.reasoningEffort setting (set via /effort), which is exposed in the settings dialog but was missing from the settings reference. Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
427b5ade33
|
docs: document model/auth settings, /model --vision, and --safe-mode (#6028)
* docs: document model/auth settings, /model --vision, and --safe-mode Refresh user docs to match the current codebase: - commands.md: add the /model --vision override (vision-bridge model) - settings.md: add model.baseUrl, model.sessionTokenLimit, visionModel, and voiceModel; document the deprecated security.auth.apiKey and security.auth.baseUrl keys with a pointer to modelProviders - troubleshooting.md: document the --safe-mode flag for isolating customization issues * docs: address review feedback on sessionTokenLimit, safe-mode, deprecation notes - model.sessionTokenLimit: correct default to -1 (runtime fallback in core/config.ts) and clarify breach behavior (current send dropped, not session abort) per client.ts SessionTokenLimitExceeded handling. - --safe-mode: expand the disabled-customizations list to also cover permission rules, approval mode overrides, memory features, and sandbox settings, matching cli/config.ts. - security.auth.apiKey/baseUrl: align deprecation wording with the existing tools.* entries (**Deprecated.**) and drop the unsubstantiated '(slated for removal)' qualifier. * docs: note QWEN_CODE_SAFE_MODE env var as a safe-mode alternative Document the QWEN_CODE_SAFE_MODE=true environment variable as an alternative activation path for safe mode, for cases where the CLI cannot accept flags (verified against isSafeModeEnv in packages/core/src/utils/safe-mode.ts). * docs: clarify model.baseUrl, sessionTokenLimit=0, and safe-mode subagents - model.baseUrl: describe it as a picker-managed disambiguator, not a hand-editable override (stale values can misroute to a same-id provider). - model.sessionTokenLimit: note that 0 is treated as unlimited (same as -1), unlike model.maxToolCalls where 0 disallows all calls. - --safe-mode: include custom subagents in the list of disabled customizations (only built-in subagents load in safe mode). * docs: clarify sessionTokenLimit semantics and add --safe-mode to headless flags - settings.md: reword model.sessionTokenLimit to reflect that the gate compares the last recorded prompt token count before the next send (not a per-send preflight cap), and that the next send is dropped. - headless.md: add a --safe-mode row to the CLI flags table so the diagnostic flag is discoverable there, cross-referencing Troubleshooting. * docs: align safe-mode sandbox wording to 'sandbox settings' Safe mode passes an empty Settings object to loadSandboxConfig (packages/cli/src/config/config.ts:1793), so it strips settings-sourced sandbox config while the --sandbox flag and QWEN_SANDBOX env still apply. Match headless.md to troubleshooting.md's accurate 'sandbox settings'. * docs: correct safe-mode approval-mode wording and align both lists Safe mode only strips settings-sourced approval mode; the --yolo and --approval-mode CLI flags are evaluated before the safeMode guard (packages/cli/src/config/config.ts:1521-1528) and still take effect. Reword to 'settings-sourced approval mode overrides' and note the CLI flags in troubleshooting.md and headless.md, and make the enumerated safe-mode disable list identical (same items and order) across both. --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
1a46df5d92
|
fix(cli): load browser MCP tools by default (#6006)
* fix(cli): load browser MCP tools by default * fix(cli): cover browser MCP env flags * fix: address browser MCP review follow-ups * fix(cli): add browser MCP diagnostics * fix(cli): tighten browser MCP auto-wiring * fix(cli): address browser MCP diagnostics * revert(cli): drop browser MCP diagnostic churn * revert(cli): drop optional CDP startup diagnostic * refactor(cli): load browser MCP dynamically * fix(cli): lazily attach CDP tunnel * test(cli): use repo deps for CDP tunnel acceptance * fix(cli): scope browser MCP defaults to extension origins * fix(cli): recover from lazy CDP attach failures * fix(chrome-extension): bind CDP replies to source socket * ci: allow slower actionlint runs * fix(cli): harden chrome devtools runtime MCP registration * test(cli): satisfy lint in CDP registration race test * test(cli): cover chrome devtools MCP retry loop * test(cli): cover chrome devtools skip paths * ci: restore actionlint timeout |
||
|
|
e324104ce8
|
docs: refresh settings, MCP glob, auth alias, and autonomous loop docs (#6090)
Audit docs/ against the current codebase and correct user-facing drift: - Document glob-pattern support (* and ?) for mcp.allowed / mcp.excluded in settings.md and the MCP feature page (feat #6012). - Add missing user-facing settings rows: general.terminalBell, general.preventSystemSleep, general.chatRecording; ui.showStatusInTitle, ui.disableWorkflowKeywordTrigger, ui.enableUserFeedback, ui.compactInline, ui.useTerminalBuffer, ui.hideBuiltinWorktreeIndicator; memory.enableTeamMemory, memory.enableTeamMemorySync; tools.toolSearch.enabled. - Note the QWEN_MODEL alias for OPENAI_MODEL in the auth protocol table. - Document the autonomous (bare /loop) mode in scheduled-tasks (feat #5991). Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
7b9e31885b
|
feat(web-shell): add mobile sidebar drawer with session list (#6003)
* feat(web-shell): add mobile sidebar drawer with session list Replace the display:none behavior at viewport <=760px with an overlay drawer pattern. A hamburger menu button appears on mobile, tapping it slides the existing WebShellSidebar in as a fixed overlay with a semi-transparent backdrop. Selecting or creating a session auto-closes the drawer. Desktop layout (>=761px) is unaffected. Closes #6000 * fix(web-shell): address review feedback for mobile sidebar drawer - Use display:contents for desktop wrapper transparency (Critical: sidebar was hidden) - Fix z-index stacking so sidebar renders above backdrop in drawer - Force sidebar expand when mobile drawer is open (collapsed state) - Hide resizeHandle on mobile to prevent touch scroll conflicts - Reset drawer state on viewport resize via matchMedia listener - Add role=dialog, aria-modal, Escape key dismissal, body scroll lock - Add aria-expanded to hamburger button - Close drawer when opening Settings or resuming sessions * fix(web-shell): address second round of review feedback - Remove dead :global(.sidebar) selector (CSS Modules hash class names) - Fix Escape key capture-phase handler to not intercept sidebar inputs - Conditionally apply role=dialog/aria-modal only when drawer is open - Stop toggling collapsed prop on drawer open/close to preserve sidebar state - Add closeMobileDrawer() for bare /resume command path - Fix hamburger button vertical centering in empty chat state on mobile * fix(web-shell): fix stacking context and escape handler in mobile drawer * fix(web-shell): prevent iOS Safari background scroll when drawer is open * chore: remove accidentally committed .qwen-session and gitignore it The .qwen-session file is a developer-local session UUID generated by qwen serve. It was accidentally committed to the repo and should never be tracked. * fix(web-shell): address review feedback for mobile drawer - Don't preventDefault touchmove inside the drawer so the session list can scroll natively; only block scrolling on the page behind it. - Defer Escape to a pending tool/permission approval (reject) instead of closing the drawer when a prompt is visible. - Reuse isEditableTarget from utils/dom and only bail out for editable targets outside the drawer, so the drawer search input still closes on the first Escape. - Close the drawer before awaiting loadSession so it doesn't linger over the old transcript, matching the other session-switch paths. - Keep the drawer panel visible until the backdrop finishes fading out to avoid a one-frame flicker on close. Co-Authored-By: Qwen-Coder <noreply@qwen.ai> * fix(web-shell): mobile drawer ignores collapsed rail + block backdrop scroll - collapsed: a user who collapsed the desktop sidebar got a mobile drawer that still rendered as the icon rail (no session list — the whole point of the drawer). Force the expanded layout while the drawer is open. - touchmove: the allowlist matched the outer [data-mobile-drawer] wrapper, which also contains the full-screen backdrop, so a touchmove starting on the dim backdrop skipped preventDefault and let iOS Safari scroll the page behind. Exclude the backdrop so only the panel keeps native scroll. Co-Authored-By: Qwen-Coder <noreply@qwen.ai> * fix(web-shell): harden mobile drawer collapse, error path, and width cap - Hide the sidebar collapse button while the mobile drawer is open so its no-op toggle can no longer silently persist desktop collapsed state. - Close the drawer before awaiting createSession() so a failed create no longer leaves the drawer stuck open with page scroll locked. - Drop redundant width/min-width/position from .sidebar.mobileOpen and cap it with max-width:100vw so a wide persisted width can't overflow phones. Co-Authored-By: Qwen-Coder <noreply@qwen.ai> --------- Co-authored-by: pomelo-nwu <czynwu@gmail.com> Co-authored-by: Qwen-Coder <noreply@qwen.ai> |
||
|
|
f3694dde67
|
feat(ui): add ui.history.collapsePreviewCount to show last N turns when resuming collapsed sessions (#5848)
* feat: add ui.history.collapsePreviewCount to show last N turns on resume * chore: regenerate settings schema for collapsePreviewCount --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com> |
||
|
|
8daeb5b1f9
|
feat(core): add configurable auto-compact threshold and Stop hook context usage (#4025) (#5868)
* feat(core): add configurable auto-compact threshold and Stop hook context usage (#4025) Add two features requested in issue #4025: 1. Configurable auto-compact threshold via settings.json - Add context.autoCompactThreshold setting (0-1, default 0.7) - Extend computeThresholds(window, pct?) to accept optional pct parameter - Wire all 4 call sites (chatCompressionService, geminiChat, contextCommand, useContextualTips) - Large windows (>110K) dominated by absolute branch, custom threshold mainly affects small windows 2. Stop hook stdin payload includes context usage data - Add ContextUsageData interface and buildContextUsage helper - Extend StopInput with context_usage, context_limit, input_tokens fields - Wire 3 callers (Session.ts, client.ts, config.ts) - Enables hook scripts to observe context usage and suggest compact strategies * fix(test): add getAutoCompactThreshold mock to geminiChat.test.ts, add NaN guard to buildContextUsage * fix(review): address round 4 findings — schema constraints, Partial<ContextUsageData>, buildContextUsage validation * docs: add context.autoCompactThreshold and Stop hook context usage fields documentation * fix(review): add contextWindowSize fallback, pct clamp, doc accuracy, threshold propagation test * fix: correct warn value in contextCommand test comment * test(chatCompressionService): fix misleading pct=1 test name and assertion * fix(chatCompressionService): prevent negative warn threshold for low pct values * docs(chatCompressionService): update JSDoc warn formula to include max(0, ...) floor * test(chatCompressionService): add pct clamping tests and fix NaN handling Add tests for out-of-range pct values (-0.5, 1.5, NaN) to verify computeThresholds clamping behavior. Fix implementation to use Number.isFinite() check so NaN falls back to DEFAULT_PCT instead of propagating through Math.max(0, NaN) which yields NaN. * test(config): add MCP Stop dispatch validation tests Add tests for buildContextUsage runtime validation in MCP Stop dispatch path: - Valid numeric inputs produce correct ContextUsageData - Missing/undefined fields return undefined - String values rejected by Number.isFinite validation - Negative values return undefined Also add Number.isFinite check for contextWindowSize in buildContextUsage to properly validate MCP input types at runtime. * fix(chatCompressionService): fix TypeScript type narrowing for pct parameter Use explicit undefined check before Number.isFinite to properly narrow the number | undefined type in the ternary expression. --------- Co-authored-by: 俊良 <zzj542558@alibaba-inc.com> |
||
|
|
f33dd61f8a
|
fix(core): stop repeated truncated write_file/edit retries from looping (#5934)
* fix(core): stop repeated truncated edit retries * fix(core): default output tokens to the model limit instead of the 8K cap The 8K CAPPED_DEFAULT_MAX_TOKENS made normal large responses (esp. file writes) truncate, forcing a truncate->escalate round-trip and, worst case, a retry loop. Default to the model's declared output limit instead; the existing escalation + multi-turn recovery stay as the truncation backstop. The 8K cap was a slot-reservation optimization. Claude Code keeps the same cap but gates it behind a feature flag that defaults OFF for third-party providers; qwen-code's providers are all third-party / OpenAI-compatible / self-hosted, so matching that default-off behavior is the safe choice. The capacity tradeoff stays opt-in via QWEN_CODE_MAX_OUTPUT_TOKENS. Refs #5756 * fix(core): use a truncation-specific stop directive for repeated truncated writes * docs: update max tokens configuration wording |
||
|
|
07beac1ddb
|
feat(telemetry): Make sensitive span attribute limit configurable (#5804)
* feat(telemetry): Make sensitive span attribute limit configurable Default sensitive native OTel span attribute payload truncation to 1 MiB and allow users to override the limit via settings or environment. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: fix CI failure on PR #5804 Add the new sensitive span attribute default export to telemetry/core mocks used by the full Windows test suite. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Include invalid telemetry max-length values in errors, make the telemetry parser stricter, include the configured truncation limit in markers, and cover the exact truncation boundary. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * test(cli): fix ACP worktree mock for telemetry limit Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): honor telemetry limit for model output spans Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * test(core): cover telemetry span limit edge cases Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Keep sensitive span truncation results within the configured max length, make response-text extraction require an explicit cap, and cover whitespace-only sensitive span max length env values. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Keep model-output span attribute writes best-effort and share visible response text extraction between log and sensitive span paths. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): address telemetry review feedback Bound prefixed tool span payloads, share sensitive max-length validation, and cover multi-part sensitive model output. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(cli): update workspace facade core mock Add telemetry sensitive span length constants to the qwen-code-core mock used by the workspace service facade test so settings schema imports can load. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5804) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> --------- Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com> Co-authored-by: 易良 <1204183885@qq.com> |
||
|
|
44b80da0db
|
feat(memory): confirm auto-generated skills before persisting (#5616)
* feat(memory): add memory.autoSkillConfirm setting schema * feat(memory): add Config.getAutoSkillConfirmEnabled() * feat(memory): wire memory.autoSkillConfirm through cli/acp/desktop settings * feat(memory): add pending-skills staging helpers * feat(memory): stage auto-skills for confirmation in runSkillReview * feat(memory): pass autoSkillConfirm flag from client to skill review * feat(memory): skill-review subscriptions + accept/reject pending APIs * feat(cli): add skill-review dialog state to UI context * feat(cli): add SkillReviewDialog component * feat(cli): render SkillReviewDialog from DialogManager * feat(cli): wire skill-review subscription and idle dialog routing * feat(cli): show pending auto-skill review hint in footer * feat(cli): add autoSkillConfirm toggle to /memory dialog * docs(memory): document memory.autoSkillConfirm setting * fix(cli): focus and Ctrl+C-close the skill-review dialog * fix(memory): address review on auto-skill confirmation - stage only newly-created skills, never agent-edited pre-existing ones, so Discard can't delete a skill the user already confirmed - re-read pendingSkills after the await in resolvePendingSkill so concurrent Keep-all/Discard-all removes every entry, not just the last - surface accept/reject fs failures (try/catch + log + .catch) instead of silently swallowing them - remount SkillReviewDialog per task via key so its snapshot never goes stale across consecutive skill-review batches - skip redundant skillReviewPending updates with a signature compare - remove the unreachable openSkillReviewDialog action - add debug logging to the pending-skills module - ignore .qwen/pending-skills/ explicitly in .gitignore * fix(memory): address round 2 review on auto-skill confirmation - acceptPendingSkill: when the staged dir is gone, no-op only if the skill is already in the skills root; otherwise throw so resolvePendingSkill keeps it pending and logs, preventing silent data loss - fall back to the agent's systemMessage for progress text when staging yields zero pending (a pre-existing-skill edit is still a durable change) - log the no-task / no-target early returns in resolvePendingSkill - replace internal tracker references in an AppContainer comment * fix(memory): harden auto-skill confirmation for multi-batch and edge cases - parseDescription: keep an empty description empty instead of spilling onto the next YAML line - namespace staged dirs under the task id so a later same-named batch can't clobber a still-deferred earlier one - track Esc-dismissed batches in a Set (not a single value) and only mark a batch dismissed on Esc, so a partially-failed Keep-all can reopen for the unresolved skills - document the in-place updateRecord invariant the accept/reject race fix relies on - add the missing license header to pending-skills.test.ts * fix(memory): strip quoted descriptions; Ctrl+C defers skill-review dialog - parseDescription: strip a matching pair of surrounding quotes so a `description: "..."` frontmatter value isn't rendered with literal quotes - useDialogClose: Ctrl+C on the skill-review dialog now calls dismissSkillReviewDialog (records the batch as dismissed) instead of plain close, matching Esc — otherwise the idle effect immediately reopened it --------- Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com> |
||
|
|
9254852211
|
feat(serve): Add daemon workspace voice and control APIs (#5765)
* feat(daemon): add setup-github route Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * feat(serve): add daemon workspace voice and control APIs Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address daemon voice review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address daemon voice review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(cli): require auth for voice transcription Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(cli): address voice persistence review feedback Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: fix CI failure on PR #5765 Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(cli): address daemon voice review feedback Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(cli): ignore untrusted workspace proxy for setup-github Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(serve): address daemon workspace review feedback Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(serve): address daemon voice review followups Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(serve): address workspace voice review feedback Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(serve): address settings and git utility review feedback Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * test(serve): align permission cwd expectation Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix: address review feedback on settings logs and sdk types Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(cli): Bound ACP workspace voice model input Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: fix CI failure on PR #5765 Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5765) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> --------- Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com> |
||
|
|
a234860a4a
|
fix(core): Align MCP OAuth guidance and docs (#5589)
Some checks are pending
Qwen Code CI / Classify PR (push) Waiting to run
Qwen Code CI / Test (ubuntu-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Test (macos-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Test (windows-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Post Coverage Comment (push) Blocked by required conditions
Qwen Code CI / CodeQL (push) Blocked by required conditions
Qwen Code CI / Integration Tests (CLI, No Sandbox) (push) Waiting to run
E2E Tests / E2E Test (Linux) - sandbox:docker (push) Waiting to run
E2E Tests / E2E Test (Linux) - sandbox:none (push) Waiting to run
E2E Tests / E2E Test - macOS (push) Waiting to run
* docs: Align docs with current CLI behavior Update stale documentation and user-facing MCP OAuth guidance to match the current dialog-based flows, SDK permission semantics, current links, and Qwen OAuth status. Also replace Ink internal imports with public Ink APIs for the shared text input so the workspace builds against Ink 7. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: fix BaseTextInput Ink import (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * codex: address PR review feedback (#5589) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): surface MCP OAuth credential read failures Fix SSE OAuth credential pre-check failures by reporting token storage read errors before connecting. Update SDK coreTools docs and extension release link text from the follow-up review. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): harden MCP OAuth error handling Handle stderr warning failures as best-effort and keep SSE 401 OAuth guidance when credential re-read fails. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): keep SSE OAuth pre-read best effort Avoid blocking SSE MCP connections when the diagnostic credential pre-read fails, and cover BaseTextInput absolute-position edge cases. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): handle SSE OAuth validation errors Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): surface MCP OAuth recovery guidance Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): cover MCP OAuth retry paths Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): address OAuth guidance review Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> --------- Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> |
||
|
|
099b47edca
|
fix(core): require integer microcompaction keep count (#5652) | ||
|
|
f1ef9d32b9
|
docs: fix config/command/auth drift and surface the model-providers page (#5735)
* docs: fix config/command/auth drift and surface model-providers page
Audit docs/ against the current code and correct the highest-impact drift:
- settings.md: move the mis-filed experimental.emitToolUseSummaries row into a
new experimental section (cron/agentTeam/artifact/emitToolUseSummaries) and
add general.language/outputLanguage/dynamicCommandTranslation and
output.showTimestamps.
- commands.md: document /cd, /history, /voice, /import-config and the
/model --voice and /model <model-id> forms.
- auth.md + model-providers.md: convert all modelProviders examples to the v5
{ protocol, models } object shape, correct the /auth menu (Alibaba
ModelStudio / Third-party Providers / Custom Provider), fix the default
OpenAI model (qwen3.5-plus), document the vertex-ai auth type, mark envKey
optional, and use kebab-case --openai-api-key/--openai-base-url flags.
- overview.md + quickstart.md: rewrite the stale first-run auth flow; fix typo.
- configuration/_meta.ts: surface the orphaned model-providers page in the nav.
- qc-helper SKILL.md: add the 8 missing feature pages to the doc index.
* docs: resolve review feedback — fix provider-name and ModelStudio casing
Align docs with the code's provider labels and UI strings:
- Z.ai -> Z.AI (presets/zai.ts: label 'Z.AI API Key')
- iDeaLab -> Idealab (presets/idealab.ts: label 'Idealab API Key')
- 'Model Studio' -> 'ModelStudio' (UI flowTitle 'Alibaba ModelStudio'; no 'Model Studio' in code)
Applied across auth.md, overview.md, quickstart.md. Used --no-verify to avoid
lint-staged reformatting pre-existing, unrelated (non-CI-enforced) table padding
in auth.md; the five changed lines are individually prettier-clean.
* docs: resolve review feedback — /history subcommands, language type, jsonc fence
- commands.md: add missing '/history expand-on-resume' subcommand (historyCommand.ts registers collapse-on-resume, expand-on-resume, expand-now)
- settings.md: general.language Type string -> enum (settingsSchema.ts declares type: 'enum')
- model-providers.md: relabel the Example fence json -> jsonc (it contains // comments and two JSON docs)
--no-verify: avoids lint-staged re-padding pre-existing, unrelated (non-CI-enforced)
table columns; the three changed lines are content-only.
|
||
|
|
9b20c47f46
|
feat(core): respect configurable agent ignore files (#4653)
* Respect agent ignore conventions through configurable filtering Constraint: Issue #1746 requests .agentignore/.aiignore compatibility and maintainer feedback asks for a custom ignore-file configuration path. Rejected: Hardcode only .agentignore/.aiignore | would not satisfy the maintainer's configurable-ignore direction. Confidence: high Scope-risk: moderate Directive: Keep .qwenignore always included when respectQwenIgnore is enabled; route extra filenames through customIgnoreFiles. Tested: Core targeted vitest suite; CLI targeted vitest plus config integration; npm run build && npm run typecheck; targeted eslint; git diff --check. Not-tested: Full repository test suite and model-driven end-to-end CLI integration tests. * fix(cli): keep custom ignore settings type-safe and honest The schema default otherwise narrows customIgnoreFiles to the built-in tuple and the UI text implies additive behavior that the implementation does not provide. Constraint: Address wenshao's two review comments without changing replacement semantics. Rejected: Merge user values with defaults | Larger behavior change was not requested for this follow-up. Confidence: high Scope-risk: narrow Directive: Preserve replacement semantics unless a future change intentionally updates config merging and docs together. Tested: cd packages/cli && npx vitest run src/config/config.test.ts src/config/settingsSchema.test.ts; npm run build; npm run typecheck; npm run lint; git diff --check Not-tested: Full integration suite. * fix(core): keep custom ignore settings consistent Ensure review-sensitive file discovery paths, grep ignore resolution, and user-facing ignore names preserve the configured custom ignore behavior instead of falling back to defaults or search-directory-local files. Constraint: PR #4653 review feedback requires customIgnoreFiles to behave consistently across secondary discovery and grep paths. Rejected: Merge custom ignore files with defaults | The current PR documents replacement semantics and prior review feedback accepted that contract. Confidence: high Scope-risk: narrow Directive: Keep .qwenignore always included, but treat customIgnoreFiles as the replacement list for additional AI ignore files. Tested: packages/core targeted vitest for qwenIgnoreParser, fileDiscoveryService, ripGrep, config, read-file; packages/cli config vitest; targeted workspaceFileSystem custom-ignore vitest; Prettier check; ESLint on touched files; git diff --check. Not-tested: Full workspace typecheck/build because current branch fails before this change on environmentContext.test.ts syntax and unrelated CLI type errors; full workspaceFileSystem suite on Windows because existing symlink tests fail with EPERM. * test(core): cover subagent custom ignore inheritance Keep the in-process backend tests aligned with the new per-agent file filtering contract so CI catches missing custom-ignore propagation. Constraint: PR review fixes require subagents to inherit parent custom ignore settings. Confidence: high Scope-risk: narrow Tested: npx vitest run src/agents/backends/InProcessBackend.test.ts Tested: npx vitest run src/utils/qwenIgnoreParser.test.ts src/services/fileDiscoveryService.test.ts src/tools/ripGrep.test.ts src/config/config.test.ts src/tools/read-file.test.ts src/agents/backends/InProcessBackend.test.ts src/tools/agent/agent.test.ts Tested: npx vitest run src/serve/fs/workspaceFileSystem.test.ts -t "uses configured custom ignore files" Tested: npx prettier --check packages/core/src/agents/backends/InProcessBackend.test.ts Tested: npx eslint packages/core/src/agents/backends/InProcessBackend.test.ts Tested: git diff --check Not-tested: full npm run typecheck remains blocked by existing branch-wide TypeScript errors outside this test change * test(core): fix subagent custom ignore test typing Keep the custom-ignore regression test type-checkable under the repo build, where createMockConfig is intentionally cast to never. Constraint: CI runs package build during dependency installation and type-checks test files. Confidence: high Scope-risk: narrow Tested: npx vitest run src/agents/backends/InProcessBackend.test.ts Tested: npx prettier --check packages/core/src/agents/backends/InProcessBackend.test.ts Tested: npx eslint packages/core/src/agents/backends/InProcessBackend.test.ts Tested: git diff --check Not-tested: npm run build --workspace=packages/core is still blocked locally by src/utils/environmentContext.test.ts(599,1): error TS1005: '}' expected * test(core): align notebook ignore message expectation Keep notebook ignore validation tests in sync with the comma-separated ignore file display used by the review fix. Constraint: PR review fixes changed ignore file display text from slash-separated to comma-separated. Confidence: high Scope-risk: narrow Tested: npx vitest run src/tools/notebook-edit.test.ts Tested: npx vitest run src/utils/qwenIgnoreParser.test.ts src/services/fileDiscoveryService.test.ts src/tools/ripGrep.test.ts src/tools/read-file.test.ts src/tools/notebook-edit.test.ts src/config/config.test.ts src/agents/backends/InProcessBackend.test.ts src/tools/agent/agent.test.ts Tested: npx prettier --check packages/core/src/tools/notebook-edit.test.ts Tested: npx eslint packages/core/src/tools/notebook-edit.test.ts Tested: git diff --check Not-tested: full npm run build --workspace=packages/core remains blocked locally by src/utils/environmentContext.test.ts(599,1): error TS1005: '}' expected * fix(core): keep ripgrep ignore roots canonical Constraint: PR #4653 review 4453010590 requested absolute ignore-root fallback behavior. Rejected: Broader customIgnoreFiles semantic changes | outside the review scope and replacement semantics stay unchanged. Confidence: high Scope-risk: narrow Directive: Keep customIgnoreFiles as replacement for compatibility defaults while always including .qwenignore. Tested: cd packages/core && npx vitest run src/tools/ripGrep.test.ts; npx prettier --check src/tools/ripGrep.ts src/tools/ripGrep.test.ts; git diff --check Not-tested: npm run typecheck --workspace=packages/core fails on existing src/utils/environmentContext.test.ts parse error. * test(core): align ripgrep ignore path expectation Constraint: macOS canonicalizes temporary paths through /private/var after process.chdir. Rejected: Changing ripgrep ignore-root behavior | implementation already uses path.resolve correctly. Confidence: high Scope-risk: narrow Directive: Keep the regression test tied to path.resolve behavior rather than raw temp-dir spelling. Tested: cd packages/core && npx vitest run src/tools/ripGrep.test.ts; npx prettier --check src/tools/ripGrep.test.ts src/tools/ripGrep.ts; git diff --check Not-tested: Full CI rerun is remote-only after push. * fix(core): make custom ignore feedback actionable Review feedback for PR #4653 showed users could not tell which ignore file blocked a path, and worktree isolation lacked coverage for inherited custom ignore files. This also closes the existing environmentContext.test describe block so build can progress to the current unrelated converter type blocker. Constraint: PR #4653 keeps replacement semantics for customIgnoreFiles and always includes .qwenignore. Rejected: Exposing matching pattern text | merged ignore and negation semantics can make pattern-level attribution misleading. Confidence: high Scope-risk: moderate Directive: Keep customIgnoreFiles as replacement semantics unless the config contract changes deliberately. Tested: core targeted Vitest suite; ripGrep regression test; cli settingsSchema test; Prettier check. Not-tested: npm run build && npm run typecheck blocked by existing FinishReason type errors in converter.ts. * fix(core): isolate qwen ignore sources * test(cli): mock qwen ignore defaults in acp test * test(scripts): make dev launcher test path portable * fix(core): prevent ripgrep ignore negation bypass * fix(core): post-filter ripgrep qwenignore matches * fix(core): preserve ignore negations in grep - Preserve non-.qwenignore negation semantics for grep searches - Skip workspace-external ignore-file discovery - Add coverage for ignore diagnostics and addSource behavior * test(core): update yaml nested parser expectations * chore: remove unrelated formatting churn |
||
|
|
977313b5ae
|
fix(cli): parse force hyperlink override strictly (#5489) | ||
|
|
0ba245ea3d
|
feat(cli): add persistent history collapse on resume with refined commands (#4085)
* feat(cli): add --quiet-restore flag to suppress history output on session resume * fix: preserve history state for /rewind while suppressing rendering * refactor: model quiet-restore as display policy with shared utilities * refactor: replace --quiet-restore with /history collapse|expand slash command * fix: persist history collapse state as user setting * fix(cli): address maintainer feedback on history collapse persistence and i18n * test(cli): fix TypeScript compilation errors in historyCommand tests * fix(cli): address maintainer review feedback on history collapse * test: fix act() warning in slashCommandProcessor.test.ts * fix: make applyCollapsePolicyAndSummary pure to avoid React batching bug * chore: revert unrelated changes to lockfile and NOTICES.txt * test: verify isRealUserTurn handles suppressOnRestore items correctly * wip(cli): preserve local history review fixes before redesign * feat(cli): refine history resume collapse commands * fix(cli): address maintainer review feedback on history collapse * test(cli): cover cold-boot collapsed resume * fix(cli): address reviewer feedback on history collapse * fix(cli): resolve rebase conflicts and missing imports * fix(cli): strip suppressOnRestore in handleRewindConfirm * fix(i18n): add Chinese translations for history collapse commands * fix: address wenshao review comments on PR #4085 - Restore restoreGoalFromHistory call in cold-boot resume path - Extract stripSuppressOnRestore to shared utility in resumeHistoryUtils - Add comment explaining historyRef pattern in slashCommandProcessor - Use historyCommand.name constant instead of string literal - Add missing i18n translation for collapse summary message - Fix pluralization in createHistoryCollapseSummaryItem * fix(i18n): add missing English translations for history collapse commands * fix: address wenshao follow-up review comments - Filter out collapse-summary items in rewind path (AppContainer.tsx) - Show info messages for collapse-on-resume/expand-on-resume commands (slashCommandProcessor.ts) - Use visibleHistory instead of uiState.history in summaryByCallId useMemo (MainContent.tsx) - Remove dead hasHistoryManager guard and optional chaining (useResumeCommand.ts) * fix: restore optional chaining for remount in useResumeCommand * test: update slashCommandProcessor tests for history command feedback changes * chore: remove generated artifact files from branch - Remove .learnings/LEARNINGS.md (local workflow artifact) - Remove .pr-body.md (PR description draft) - Remove build_output.log (build log) - Remove vscode_test_output.log (test output log) These files are unrelated to the history-collapse feature and were causing git diff --check whitespace errors. * fix: address wenshao review comments on PR #4085 - Remove stray [!tip] file from repo root - Add selfManaged flag to MessageActionReturn for explicit UI feedback control - Fix expand-now to return load_history type instead of calling loadHistory directly - Replace hardcoded isSelfManaged path check with result.selfManaged in processor - Fix MainContent merge detection to use visibleHistory.length (avoid flicker) - Refactor applyCollapsePolicyAndSummary to not mutate input array - Extract expandCollapsedHistory shared helper - Restore dialog:memory test in slashCommandProcessor.test.ts - Add stripSuppressOnRestore dedicated tests - Add visibleHistory filtering test in MainContent.test.tsx - Update historyCommand tests for new load_history return type - Fix eslint errors: remove unused imports and fix dependency array * fix: address wenshao review comments on PR #4085 - Remove stray [!tip] file from repo root - Add selfManaged flag to MessageActionReturn for explicit UI feedback control - Fix expand-now to return load_history type instead of calling loadHistory directly - Replace hardcoded isSelfManaged path check with result.selfManaged in processor - Fix MainContent merge detection to use visibleHistory.length (avoid flicker) - Refactor applyCollapsePolicyAndSummary to not mutate input array - Extract expandCollapsedHistory shared helper - Restore dialog:memory test in slashCommandProcessor.test.ts - Add stripSuppressOnRestore dedicated tests - Add visibleHistory filtering test in MainContent.test.tsx - Update historyCommand tests for new load_history return type - Fix eslint errors: remove unused imports and fix dependency array - Fix TypeScript errors: add useEffect import, fix display.kind type assertions * fix: add braces around if statement body (eslint curly rule) Fixes lint error in editorGroupUtils.ts: - Expected { after 'if' condition on line 32 * fix: address wenshao follow-up review comments on PR #4085 - Revert expand-now to use loadHistory/refreshStatic directly (no load_history return) - Remove dead selfManaged flag from MessageActionReturn and processor - Fix visibleHistory filter to also exclude collapse-summary items - Simplify applyCollapsePolicyAndSummary (return rawItems when !collapseOnResume) - Fix test assertion shapes (content→text, timestamp as separate arg) - Add mockClient for expand-now test - Update historyCommand tests for new behavior - Add expandCollapsedHistory dedicated tests - Fix MainContent filtering test to use historyItemDisplayPropsSpy * fix: address wenshao latest review comments on PR #4085 - Fix visibleHistory filter: remove collapse-summary exclusion (summary should render when all items suppressed) - Update MainContent test: assert summary item IS rendered alongside unsuppressed items - Remove dead selfManaged flag from MessageActionReturn type - Remove dead selfManaged check from slashCommandProcessor.ts - Add remount?.() to useResumeCommand error path - Remove unused 'History expanded.' translation key from en.js, zh.js, zh-TW.js - Fix expand-now test: mock action to return undefined (matching real behavior) * fix: address wenshao latest review comments on PR #4085 - Add missing i18n translations to ca.js, de.js, fr.js, ja.js, pt.js, ru.js - Simplify applyResumeDisplayPolicy: remove dead options parameter - Fix expand-now test: mock action to return undefined (matches real behavior) - Revert unrelated changes to package-lock.json and editorGroupUtils.ts * fix: address wenshao latest review comments - Add openDiffDialog to createMockActions() in slashCommandProcessor.test.ts - Add sentToModel: false to user message assertions in slashCommandProcessor.test.ts - Fix useResumeCommand.test.ts mock: spread original @qwen-code/qwen-code-core exports to include createDebugLogger - Remove dead optional chaining (addItem?., clearItems?., loadHistory?.) in useResumeCommand.ts - Simplify if (!config || !startNewSession) to if (!config) since startNewSession is required - Fix truncatedCount off-by-one in AppContainer.tsx rewind path: exclude collapse-summary from effective length - Apply collapse policy (applyCollapsePolicyAndSummary) in useBranchCommand.ts for /branch - Add settings to UseBranchCommandOptions with proper useCallback dependency * fix: add missing mockUpdateItem arg to test renderHook calls, remove stray file - Add mockUpdateItem (17th arg) to resume-direct and memory dialog test calls - Remove accidentally committed packages/core/.qwen/computer-use/installed.json - Add .qwen/computer-use/installed.json to .gitignore * fix: address review comments (type, gitignore, test, split-brain) 1. UIActionsContext: handleResume return type → Promise<void> 2. .gitignore: split corrupted merged line into .codegraph + .qwen/... 3. useBranchCommand.test: add settings to makeOptions(), add collapseOnResume test 4. useResumeCommand: reorder core-before-UI with rollback (matches branch pattern) 5. useResumeCommand.test: add getSessionId to mocks, add rollback test * fix: complete history collapse translations in 6 locale files - Added missing translation text for 'History collapsed' message - Fixed syntax errors in de, fr, ja, pt, ru, zh-TW locale files * fix: add missing history parameter in slashCommandProcessor test - Fixed parameter order in 'should skip reload when consumeSlashReloadSuppression' test - Added missing empty array for history parameter - All 58 tests now pass * merge: resolve conflicts with upstream main - docs: keep ui.history.collapseOnResume setting, adopt upstream showCitations default - fix: update rewindRecording call to include file history snapshots parameter * fix(cli): repair history collapse CI failures --------- Co-authored-by: qqqys <qys177@gmail.com> |
||
|
|
b773b895c2
|
feat(cli): show optional response token rate (#5401) | ||
|
|
0430ff7af4
|
fix(openai): add string tool result compatibility mode (#5399)
Some checks are pending
Qwen Code CI / Classify PR (push) Waiting to run
Qwen Code CI / Lint (push) Blocked by required conditions
Qwen Code CI / Test (macos-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Test (ubuntu-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Test (windows-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Post Coverage Comment (push) Blocked by required conditions
Qwen Code CI / CodeQL (push) Blocked by required conditions
Qwen Code CI / Integration Tests (CLI, No Sandbox) (push) Waiting to run
E2E Tests / E2E Test (Linux) - sandbox:docker (push) Waiting to run
E2E Tests / E2E Test (Linux) - sandbox:none (push) Waiting to run
E2E Tests / E2E Test - macOS (push) Waiting to run
|
||
|
|
26ad36e95b
|
feat(cli): show follow-up suggestion in input placeholder (#5145)
* feat(cli): show follow-up suggestion in input placeholder
When enableFollowupSuggestions is true, display the generated
follow-up suggestion as the input placeholder text (replacing
the default "Type your message..."). Tab/Enter/Right arrow
accepts the suggestion; typing dismisses it.
Also change the default of enableFollowupSuggestions from false
to true so the feature is on by default.
Key changes:
- AppContainer: dismissPromptSuggestion no longer clears
promptSuggestion state, preserving it for placeholder restore
after user types then deletes
- InputPrompt: Tab/Enter/Right arrow/typing handlers check
promptSuggestion prop as fallback when followup.state is not
visible (e.g. after 300ms delay or user dismissed)
- Composer: placeholder shows suggestion text when available
- hasTabConsumer: include promptSuggestion to prevent Windows
bare Tab from cycling approval mode
* chore: update settings.schema.json (enableFollowupSuggestions default: false → true)
* test(cli): add tests for promptSuggestion prop fallback paths (#5145)
- Add unit tests for Tab/Right arrow/Enter accepting promptSuggestion
when followup.state.suggestion is null (type-then-delete path).
- Add unit test for hasTabConsumer reporting true immediately when
promptSuggestion prop is set (no followup debounce needed).
- Update stale comment on speculation abort useEffect in AppContainer.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(cli): address PR #5145 review feedback for promptSuggestion
- Fix Enter key to fill buffer instead of submitting suggestion (matches
Tab/Right-arrow behavior and Claude Code design)
- Add suggestionDismissed state to hasTabConsumer for Windows Tab cycling
- Fix suggestionDismissed to be set to true on user input (paste/typing)
- Add speculation abort to dismissPromptSuggestion callback
- Remove dead placeholder branch from Composer.tsx
- Update tests to reflect Enter no longer auto-submits suggestion
* fix(cli): address PR #5145 review from wenshao + telemetry gap
wenshao's review (posted after the previous fixes) flagged two issues,
both still valid against the current code; doudouOUC's telemetry gap
is addressed too.
- settings description: replace stale "Enter to accept and submit" with
"Press Tab, Right Arrow, or Enter to accept into the input buffer" in
both settingsSchema.ts and settings.schema.json (Enter now only fills
the buffer, and the feature defaults to enabled).
- hasTabConsumer / handler consistency: drop the redundant
`suggestionDismissed` state and gate hasTabConsumer on
`buffer.text.length === 0` — the exact condition the Tab/Right/Enter
handlers already use. Fixes the type-then-delete desync where Windows
bare Tab would both insert the suggestion and cycle approval mode
(regression of #4171).
- fallback telemetry: add a `fallbackText` option to the followup
controller's accept() so the prop-fallback path (no live suggestion,
e.g. within the show delay or after type-then-delete) routes through
accept() and logs onOutcome instead of silently bypassing telemetry.
Tab/Right/Enter handlers now call accept(method, { fallbackText }).
- tests: add core-level coverage for accept() with/without fallbackText,
and fix the InputPrompt "fallback" tests that advanced 700ms (which
silently exercised the normal visible-suggestion path) to advance only
100ms so followup.state.suggestion truly stays null.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(cli): add accept_source telemetry + tests for promptSuggestion fallback
Follow-up to wenshao's second review pass on #5145.
- accept_source telemetry: fallback accepts report time_to_accept_ms: 0
(the suggestion was never shown via the timer), which is indistinguishable
from an instant accept. Add an `accept_source: 'live' | 'fallback'` field to
the followup controller's onOutcome and PromptSuggestionEvent so analytics
can tell the two apart. The controller derives it from whether a live
`currentState.suggestion` was present before applying `fallbackText`.
- tests: assert accept_source on the fallback accept; add a test that a live
suggestion takes priority over fallbackText (guards the `?? fallbackText`
ordering); add an InputPrompt test pinning the new buffer.text.length === 0
gate — hasTabConsumer reports false when a promptSuggestion is set but the
buffer is non-empty (the old Boolean(promptSuggestion) gate wrongly reported
true). The empty-buffer → true direction stays covered by the existing test.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor(cli): address doudouOUC review on #5145 (dedupe, rename, telemetry)
Three [Suggestion]-level items from the latest review pass.
- Extract `availableSuggestion`: the compound condition
`(followup.state.isVisible || promptSuggestion) && (followup.state.suggestion ?? promptSuggestion)`
was copy-pasted across the Tab/Right/Enter accept guards, both
typing-dismiss guards, and the placeholder prop. Collapse them into one
derived value so the sites can't drift apart. Behavior is unchanged
(the controller keeps `isVisible` and `suggestion` in lockstep).
- Rename `dismissPromptSuggestion` -> `abortPromptSuggestion` across the
UIState context, AppContainer, Composer, and the MainContent mock. The
function only aborts in-flight generation/speculation and deliberately
does NOT clear `promptSuggestion` (so the placeholder can restore it);
the "dismiss" name implied the suggestion was gone.
- Omit `time_to_first_keystroke_ms` for fallback accepts. With
`accept_source: 'fallback'` the suggestion was never shown via the timer
(shownAt stayed 0), so `prevShownAtRef` still holds a previous
suggestion's timestamp and the delta would be meaningless.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(cli): actually enable followup suggestions by default
PR #5145 changed the schema default to `true`, but `mergeSettings` never
applies SETTINGS_SCHEMA defaults, so the runtime `=== true` gates left the
feature off while the settings panel read it as on (verified by wenshao).
- Flip both runtime gates to treat an unset value as enabled — only an
explicit `false` opts out: `AppContainer.tsx` and the ACP `Session.ts`
(`#maybeEmitFollowupSuggestion`).
- Add a Session test for the unset/default-on path.
- Fix the stale `UIStateContext` JSDoc left over from the dismiss→abort
rename (it no longer clears state).
- Docs: mark the feature on-by-default, correct Enter (fills the input,
does not submit), ghost-text → placeholder text, and add a cost note that
`fastModel` forks to a separate cache and can cost more than the default
main-model + shared-cache path on long conversations.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(core): reject control chars and ANSI escapes in prompt suggestions
The follow-up suggestion is influenceable through conversation history
(tool/file/web output) and is rendered verbatim in the input placeholder
now that enableFollowupSuggestions defaults to on. Raw control bytes (CR,
ESC/CSI, C1) reached the terminal because getFilterReason only rejected
newlines and asterisks. Reject them at the source so the displayed and
inserted text always match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(cli): clear promptSuggestion on submit and accept paths
Addresses doudouOUC review on #5145. Since abortPromptSuggestion was
changed to preserve `promptSuggestion` for type-then-delete restore, the
submit and accept paths leaked stale suggestion text:
- handleSubmitAndClear only called followup.dismiss(); after a synchronous
command (/clear, /help) that never triggers AppContainer's streaming
transition, the placeholder kept showing the old suggestion.
- Tab/Right/Enter accept never cleared the prop, so clearing the buffer
without submitting (Ctrl+U) made the accepted suggestion reappear as a
ghost placeholder.
Both now call onPromptSuggestionDismiss?.() after the followup action. Also
reuse the availableSuggestion single-source-of-truth in hasTabConsumer
instead of an inlined parallel expression, and add useFollowupSuggestions
tests asserting the accept_source guard suppresses time_to_first_keystroke_ms
on fallback accepts.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* test(cli): assert promptSuggestion is cleared on accept and submit
Regression coverage for the state-leak fixed in
|
||
|
|
ad6368b3ae
|
docs: fix stale defaults, CLI syntax, and tool naming drift (#5158)
- common-workflow.md: fix --p flag syntax (→ -p) and --print (→ -p/--prompt) - settings.md: fix ui.theme default (undefined → "Qwen Dark"), skipNextSpeakerCheck (false → true), enableInteractiveShell (false → true), add auto approval mode to settings and CLI flag tables - keyboard-shortcuts.md: fix Shift+Tab cycling (add auto mode), correct newline keybinding (Ctrl+Enter/Cmd+Enter/Shift+Enter/Ctrl+J) - model-providers.md: fix stale codingPlan.region reference → modelProviders - developers/tools: rename task → agent tool, remove stale save_memory and read_many_files references, fix todo_write activeForm → id field |
||
|
|
57a90f7302
|
fix(core): Bound active tool result history (#5111)
* fix(core): bound active tool result history Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): keep tool result budget defaults lightweight Move the new tool-result history budget default into a lightweight config defaults module so microcompaction does not load the full Config graph during service tests. Update the ACP worktree test mock to include the public default export used by settings schema imports. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): address tool result budget review Handle negative legacy idle thresholds consistently, clarify size compaction diagnostics for pending tool results, promote successful microcompaction logs to info, and strengthen tests/docs around skipped results and soft thresholds. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(core): log protected tool result overages Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> --------- Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> |
||
|
|
bb1e71911c
|
feat(computer-use): configurable screenshot max dimension (setting + env) (#5122)
* feat(computer-use): configurable screenshot max dimension (setting + env)
Add a user-level knob for cua-driver's screenshot longest-edge cap. The
old open-computer-use backend exposed this via OPEN_COMPUTER_USE_IMAGE_*
env vars; the cua-driver migration dropped them, leaving only the
model-driven set_config tool. This restores deterministic user control.
- Setting tools.computerUse.maxImageDimension (number; default -1 = keep
cua-driver's built-in default of 1568; 0 disables resizing / full
resolution; a positive value caps the longest edge).
- Env override QWEN_COMPUTER_USE_MAX_IMAGE_DIMENSION (takes precedence
over the setting; invalid/negative values fall through).
- Resolution lives in resolveMaxImageDimension(); applied via the
cua-driver set_config tool once per (re)connect in
ComputerUseClient.doStart — best-effort, never aborts startup, and
re-applied after a daemon-restart reconnect.
- Docs: document tools.computerUse.{enabled,maxImageDimension} in
settings.md (the block was previously undocumented). Refresh stale
ocu/npx comments left in client.ts + install-state.ts by the migration.
Precedence: env var > setting > cua-driver default.
* chore(computer-use): finish ocu→cua-driver cleanup in schema-sync script
The cua-driver migration (#5051) left scripts/sync-computer-use-schemas.ts
pointing at the old open-computer-use backend: it npx'd
@qwen-code/open-computer-use, hard-coded the 9-tool ocu surface, and emitted an
"open-computer-use" header. Re-running it — which constants.ts' version-bump
procedure tells maintainers to do — would have clobbered the migrated 35-tool
cua-driver schemas.ts.
- Drive the locally-pinned `cua-driver mcp` binary (binaryPath /
CUA_DRIVER_VERSION from constants.ts) instead of npx'ing ocu; expect 35
tools and warn (don't fail) on drift.
- Emit the cua-driver-flavored schemas.ts header.
- Refresh install-state.test.ts fixtures from ocu package specs to the
cua-driver-rs approval-key form the field actually stores now.
Verified the fixed script reproduces the committed 35-tool surface exactly
(modulo prettier formatting). No dead env-var handling remained — the module
reads only QWEN_COMPUTER_USE_{AUTO_APPROVE,DOWNLOAD_HOST,MAX_IMAGE_DIMENSION}.
|
||
|
|
546b2758fb
|
fix(docs): correct stale settings keys, wrong defaults, and missing commands (#4969) | ||
|
|
240c99c186
|
fix(openai): default splitToolMedia so tool-returned images reach strict backends (#4917)
OpenAI Chat Completions only permits text on `role:"tool"` messages, so an image read via read_file — the only image path available to a subagent — was embedded there and silently dropped by strict OpenAI-compatible backends (doubao / new-api / LM Studio). The model never saw the image and returned content unrelated to it (#4876). Permissive backends (e.g. DashScope) happen to parse it, which is why the same model worked for the main agent via @-image (role:"user") but not for the subagent via read_file (role:"tool"). Flip the runtime default of splitToolMedia to true so tool-returned media is lifted into a follow-up role:"user" message — spec-compliant and visible to all backends. Opt out via generationConfig.splitToolMedia = false. Also: - modalityDefaults: recognize ByteDance Doubao (Seed chat + *vision/*vl => image; seedance/seedream generation models => text-only). - settingsSchema + docs: default true, description corrected to cover the built-in read_file (not only MCP tools). Tests: pipeline default-true regression, modalityDefaults doubao cases, converter opt-out wording. |
||
|
|
9e4c87a7e4
|
refactor(core): remove GitService, migrate /restore to FileHistoryService (#4871)
* refactor(core): remove GitService, migrate /restore to FileHistoryService Remove the shadow-git-based GitService and rewire /restore to use the existing FileHistoryService for file restoration. This eliminates the `checkpointing` config flag (off by default) and unifies file recovery under `fileCheckpointingEnabled` (on by default in interactive mode). Key changes: - /restore now calls FileHistoryService.rewind(promptId, true) instead of GitService.restoreProjectFromSnapshot(commitHash) - File restoration runs before conversation history replacement to avoid inconsistent state on failure - Legacy checkpoint files (commitHash format) are explicitly rejected - Fix EDIT_TOOL_NAMES bug: 'replace' → ToolNames.EDIT, add ToolNames.NOTEBOOK_EDIT (checkpoint creation and AUTO_EDIT auto-approval were broken for edit tool) - Add isClientInitiated guard to prevent redundant checkpoint creation from /restore re-submitted tool calls - Remove checkpointing settings schema, CLI flag, docs, and all GitService references across 27 files 🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code) * fix: address wenshao review — improve error message, add tests, remove tombstones - Improve partial-restore warning: show files reverted/failed count - Add 3 tests: legacy format rejection, rewind partial failure, rewind exception - Remove dead tombstone comments in config.test.ts 🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code) * fix: align restore success message with turn-level semantics 🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code) |
||
|
|
13f37dc9f0
|
feat(cli): background housekeeping for stale file-history dirs (#4414)
PR #4064 introduced ~/.qwen/file-history/{sessionId}/ for /rewind but had no cross-session cleanup — directories accumulated indefinitely. This adds a generic background housekeeping framework with file-history cleanup as its first user. - 30-day mtime sweep, configurable via general.cleanupPeriodDays - 10-min startup delay (1-min catch-up if last run >7d ago) - 24h recurring cadence, idle-gated (defers if user typed in last 1 min) - O_EXCL lockfile + marker mtime throttle (multi-process safe) - Current session whitelisted via lazy config.getSessionId() — defends against long-idle active sessions and /clear minting a new session - Negative cleanupPeriodDays values clamp to 1h minimum (defends against schema-bypass: a future cutoff would otherwise sweep everything) - Zero new prod dependencies; ~70 lines of self-written O_EXCL throttle primitive in lieu of proper-lockfile (which pulls graceful-fs and monkey-patches every fs method on first require) - All setTimeout(...).unref() — never blocks process exit Closes #4173. 🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code) |
||
|
|
2d8052b02c
|
feat(cli): add respectUserColors and hideContextIndicator options for statusline (#4670)
* feat(cli): add respectUserColors option to preserve ANSI colors in
statusline command output
* test(cli): add respectUserColors tests for useStatusLine and Footer
* feat(cli): add hideContextIndicator option to hide built-in context usage in footer
* docs: update statusline configuration docs with respectUserColors and hideContextIndicator
|
||
|
|
365409366d
|
refactor(core)!: replace tail-preservation compaction with summary + restoration attachments (#4599)
* refactor(core): rewrite compression prompt to 9-section claude-code-style format
Replaces the <state_snapshot> XML template with a numbered 9-section
structure that mandates verbatim preservation of user messages, including
the historical chronological list (section 6). The new format is
designed to pair with post-compact file/image restoration (separate work)
so the agent can resume long single-turn tasks without losing intent.
* refactor(core): align compaction trigger string with new 9-section prompt
The user-turn trigger injected after the system prompt still said
'generate the <state_snapshot>' from the old XML prompt era. Updated to
'produce the 9-section summary' to match Task 1's new prompt format.
Also tightens the prompt test to assert the specific user-message
verbatim mandate (not just the word 'verbatim' anywhere) so a future
regression that drops the mandate won't silently pass.
* feat(core): add postCompactAttachments module with file path extractor
extractRecentFilePaths walks history newest-first and returns the top N
unique file paths touched by read_file/write_file/edit/replace tool calls.
Pure function, no side effects, no state cache — readiness for the next
compaction-rewrite tasks.
* refactor(core): simplify extractRecentFilePaths internals
Three small cleanups from code review:
- Map<string, number> -> Set<string> (the index value was never read)
- Guard against maxFiles <= 0 explicitly (avoids returning 1 result
when caller passes 0 as a 'disable' sentinel)
- Document 'replace' as a legacy alias for 'edit' so a future cleanup
pass does not delete it as apparent dead code
Adds one test covering the maxFiles=0 path.
* feat(core): add image extractor with source-tool metadata
extractRecentImages walks history newest-first, collects up to N image
inlineData parts, and attributes each one to the model+functionCall that
preceded it (when one exists). Returns chronological order so callers
can render a meaningful 'last visual state ends here' strip.
* feat(core): add size-adaptive file reader for post-compact restore
readFileSizeAdaptive reads a file and returns one of: embed (full content
for files ≤ maxTokens × 4 chars), reference (path-only for large files),
missing (deleted since last touch), or binary (non-text content). The
embed/reference distinction mirrors claude-code's compact_file_reference
vs file attachment behavior, but without introducing new message types.
* refactor(core): harden readFileSizeAdaptive size accounting
Three corrections from code review:
- Import CHARS_PER_TOKEN from tokenEstimation.ts (canonical) instead of
redeclaring locally, preventing silent drift between modules.
- Compare decoded character length, not raw byte length, against the
cap. Otherwise a 10k-char Chinese file would be ~30k bytes and would
be mis-classified as 'reference' despite fitting the budget.
- Rename FileReadResult -> FileEmbedResult to avoid a name collision
with the unrelated FileReadResult interface in fileUtils.ts.
Adds a CJK-text test that catches the byte/char regression.
* feat(core): add file restoration block composer
buildFileRestorationBlocks reads each candidate file, classifies it as
embed/reference/missing/binary, and emits one consolidated reference
block (path-only list) plus one user message per embedded small file.
Total embed size is capped at POST_COMPACT_TOKEN_BUDGET; over-budget
files downgrade to reference.
* test(core): make budget test actually exercise the downgrade path
The previous version of this test wrote 3 files totalling 9k chars
against a 200k char budget. The assertions trivially passed regardless
of whether the budget check existed in the implementation.
The new version writes 11 files of 20k chars (each at the per-file cap)
so the budget is exhausted by the 10th and the 11th must downgrade
from embed to reference. Asserts both: file 11 appears in the reference
block, and file 11's content does NOT appear in any embed block.
* feat(core): add image restoration block composer
buildImageRestorationBlock emits a single user message whose first part
is a metadata header (turn index + source tool name + args per image),
followed by the inlineData parts themselves. Handles user-paste images
(no source tool) by labeling them as 'user-provided'.
* feat(core): add composePostCompactHistory orchestrator
Assembles the full post-compact history in order:
summary → model ack → file references → file embeds → image block.
Each section is built by the per-concern extractors and builders added
in previous tasks. This is the single integration point that
chatCompressionService.compress() will call once the wire-up task lands.
* feat(core)!: rewrite compress() to claude-code-style full-history model
Replaces the split-point + tail-preservation model with full-history
compression + composePostCompactHistory. The entire curated history is
sent to the summary side-query, and the post-compact history is
assembled by the new composer (summary + ack + file restores + image
restore).
BREAKING: the previously-exported findCompressSplitPoint,
splitPointRetainingTrailingPairs, COMPRESSION_PRESERVE_THRESHOLD, and
TOOL_ROUND_RETAIN_COUNT will be removed in the next commit. Tests that
exercise them remain failing temporarily.
* chore(core): remove obsolete split-point compression infrastructure
Deletes findCompressSplitPoint, splitPointRetainingTrailingPairs,
COMPRESSION_PRESERVE_THRESHOLD, MIN_COMPRESSION_FRACTION, and
TOOL_ROUND_RETAIN_COUNT, plus the tests that exercised them. The new
behavior is covered by composePostCompactHistory and its unit tests.
Also cleans up:
- Stale orphan-strip comment in compress() that described the deleted
manual-trigger orphan-funcCall handling.
- TEST_ONLY.COMPRESSION_PRESERVE_THRESHOLD hatch in client.ts.
- Docstring references in config.ts and compactionInputSlimming.ts.
* test(core): add single-turn computer-use compaction regression
Reproduces the scenario the rewrite targets: one user prompt kicks off
many screenshot tool calls. Asserts that (a) the user prompt is carried
into the summary verbatim and (b) the 3 most recent screenshots are
restored as an image block with source-tool metadata. This is the canary
test for the computer-use UX claim made in the design discussion.
* docs(core): remove stale "split point" references in tokenEstimation comments
Aligns the docstrings with the new compose-based compression flow. The
"split point" and "splitter" concepts no longer exist after the rewrite.
* fix(core): iterate parts reverse so parallel tool calls keep the last N
Real-session E2E surfaced a bug: a model that issues N parallel ReadFile
calls puts all N functionCall parts in ONE model+fc content. The
extractor's outer history walk is newest-first, but the inner parts
walk was forward — so for a 6-parallel batch hitting the cap of 5,
the FIRST 5 parts won and the actually-most-recent (last-listed) file
was dropped.
Fix: walk parts in reverse within each content. Applied symmetrically
to extractRecentImages (same shape, even rarer trigger).
Adds a regression test that hits a 6-parallel batch.
* fix(core): code-review fixes — fence escape, path sanitize, alias removal
- CommonMark-safe fence in file embed blocks. The old 3-backtick fence
closed prematurely when a file's content contained a triple-backtick
run (Markdown, CLAUDE.md, JSDoc with code examples) — leaking the
remainder as unfenced text. Now uses a fence one longer than the
longest backtick run in the content.
- Strip control characters (\r, \n, \t) from file paths before
rendering into attachment markdown. Paths come from model-controlled
history; a \n could inject markdown structure. The actual path stays
intact for tool calls — only the displayed string is sanitized.
- Remove the historyForCompression alias for curatedHistory in
compress(). The alias was added as a comment anchor during the
rewrite but didn't carry semantic information.
* refactor(core): rewrite compression prompt to <state_snapshot> XML with 9 claude-aligned sections
Replaces the 9-section numbered-text prompt with qwen-code's original
<state_snapshot> XML envelope, but with the 9 inner section tags
content-aligned to claude-code:
<primary_request_and_intent>
<key_technical_concepts>
<files_and_code_sections>
<errors_and_fixes>
<problem_solving>
<all_user_messages>
<pending_tasks>
<current_work>
<next_step>
Also:
- <scratchpad> -> <analysis>, stripped by postProcessSummary (saves
~600-800 tokens of CoT noise per compaction).
- "Resume directly..." trailer moved out of the prompt body and into
postProcessSummary (no longer re-generated by the model every
compaction; lives once in code with our own wording).
- Section 6 verbatim-policed mandate relaxed to "chronological, include
short messages like 'ok' / 'continue'" — matches claude-code intent
without forcing the model to literally copy long user messages.
E2E (qwen3.6-plus, 6 substantial .ts files + thorough analysis):
raw history 6508 -> summary 1513 (after strip ~947), 38% history
compression. Overall context 24642 -> 20647 reported (-16%), with
another ~664 tokens actually saved by the post-strip but not
reflected in the conservative token-math heuristic.
* docs(core): code-review polish on XML prompt rewrite
Four small follow-ups from review of
|
||
|
|
0c3cd0052f
|
feat(cli): default auto-dream/auto-skill to on and add /memory toggle (#4547)
* feat(cli): default auto-dream/auto-skill to on and add /memory toggle Bring the managed memory pipeline closer to its intended out-of-the-box experience: auto-dream and auto-skill now default to enabled (matching the existing auto-memory default), so users get summarized memories and reusable project skills without having to opt in. The /memory dialog previously only exposed Auto-memory and Auto-dream toggles. With auto-skill now on by default, users need an equally discoverable way to opt out, so this adds an Auto-skill row alongside the existing two with the same focus/Enter toggle semantics and workspace-scoped persistence (memory.enableAutoSkill). Default-value updates are kept consistent across all three sources of truth (settings schema, CLI loader, core Config), and the generated vscode settings.schema.json is regenerated to match. * test(cli): add getAutoSkillEnabled to MemoryDialog test mock The new Auto-skill toggle row reads config.getAutoSkillEnabled() at render time; without it on the mocked config the component throws and the existing list-navigation tests assert against an empty frame. * fix(cli): guard managed auto-dream in bare mode, sync tests and docs - enableManagedAutoDream in loadCliConfig was missing the bareMode guard that its two siblings already had; once the default flipped to true, this caused a raw-field inconsistency in bare-mode sessions (the getter still returned false via its own !getBareMode() guard, but the Config.enableManagedAutoDream field itself was now true). - docs/users/configuration/settings.md still listed enableManagedAutoDream's default as false, and was missing the new enableAutoSkill row entirely. Both fixed. - MemoryDialog.test.tsx now covers the autoSkill row render, the new focus chain (list ↑ autoSkill ↑ autoDream and back down), and the Enter-toggle path that writes memory.enableAutoSkill to workspace settings. - config.test.ts gains a non-bare default test asserting all three getManaged*Enabled() / getAutoSkillEnabled() return true, and the bare-mode test now asserts auto-dream/auto-skill also resolve to false in bare mode. |
||
|
|
331f45e907
|
feat(cli): headless / non-interactive runaway-protection guardrails (#4103) (#4502)
* feat(cli): headless runaway-protection guardrails (#4103)
Adds two opt-in run-level budgets and a startup safety warning for
non-interactive / CI / SDK runs. All defaults preserve existing
behavior; the budgets only fire when the user explicitly sets a limit.
Phase 1 — surface unsafe configs and fix doc drift
- New `--yolo`-without-sandbox stderr warning at startup of every
non-interactive run, emitted by `getHeadlessYoloSafetyWarning` in
`packages/cli/src/utils/headlessSafetyWarnings.ts`. Suppressible
via `QWEN_CODE_SUPPRESS_YOLO_WARNING=1` (strict `1`/`true` match so
`=0` / `=false` don't silence it). Strict env match also applied to
the `SANDBOX` check so values like `SANDBOX=0` don't accidentally
bypass the warning.
- Gated on `!config.isInteractive()` at the gemini.tsx call site so
TUI users aren't nagged.
- `docs/users/configuration/settings.md`: corrected
`model.skipLoopDetection` default (`true`, not `false`) and reworded
the `--yolo`/sandbox section — `--yolo` does NOT auto-enable a
sandbox; sandboxing must still be opted into explicitly.
Phase 2 — run-level budgets with distinct exit code
- `--max-wall-time` / `model.maxWallTimeSeconds`: wall-clock duration
for the whole run. Flag accepts `90` (s), `30s`, `5m`, `1h`,
`500ms`. Settings is plain seconds.
- `--max-tool-calls` / `model.maxToolCalls`: cumulative tool
executions (success + failure). Ticked BEFORE each `executeToolCall`
so a budget of N caps the run at exactly N executions.
- New `FatalBudgetExceededError` (exit code 55), distinct from
`FatalTurnLimitedError` (53) and `FatalCancellationError` (130) so
CI scripts can branch on the reason. JSON output mirrors the
`handleMaxTurnsExceededError` / `handleCancellationError` envelope
convention.
- Enforced via `RunBudgetEnforcer` in
`packages/cli/src/utils/runBudget.ts`, wired to the same
`AbortController` as SIGINT so existing cancellation plumbing
carries the abort. A `routeAbort` helper distinguishes budget vs.
SIGINT at the abort-check sites and at the outer catch.
Critical correctness fixes (informed by the #4105 review pass)
- Drain-loop fall-through: the inner drain-item `for await` previously
exited via `finalizeAssistantMessage(); return;`, swallowing a
budget abort that fires during the last drain item and surfacing
exit code 0. Now routes through `routeAbort` so exit 55 is
preserved.
- Settings symmetry: `maxWallTimeSeconds: 0` in settings.json is now
rejected (same as `--max-wall-time 0`); the enforcer treats `<=0`
as "no timer" so silent disable would be a foot-gun.
`validateMaxWallTimeSetting` also rejects `Infinity` / `NaN`.
- `setTimeout` overflow: both parser paths reject durations above
`Math.floor((2^31 - 1) / 1000)s` (~24.8 days). Node clamps
oversized delays to 1ms and fires the timer almost immediately;
fail loud at startup instead.
- First-fence-wins + SIGINT race: `markExceeded` no-ops if the
controller was already aborted by a third party, so a budget tick
arriving after user SIGINT doesn't misattribute the abort to exit
code 55.
- Outer catch re-routes mid-stream `AbortError`s through the budget
handler so users see "Run aborted: …" instead of raw "AbortError".
Tests
- `runBudget.test.ts` (32 tests): parser happy / reject paths,
setting validator, post-increment off-by-one, `maxToolCalls=0`
meaning "disallowed", `-1` meaning unlimited, wall-clock under
fake timers, `stop()` cancels pending timer, idempotent `start()`,
first-fence-wins, SIGINT-race protection.
- `headlessSafetyWarnings.test.ts` (7 tests): YOLO + sandbox / env
matrix; strict-truthy `SANDBOX` check; suppression env.
- Pre-existing suites: `nonInteractiveCli.test.ts` (46),
`gemini.test.tsx` (23), `config/config.test.ts` (220),
`core/utils/errors.test.ts` (12), `core/config/config.test.ts`
(172) all green after picking up the new config getters / CliArgs
fields.
Backward compatibility
- All budgets default to `-1` (unlimited); existing CLI invocations
behave identically.
- New stderr warning only fires in the narrow YOLO-no-sandbox case,
with an explicit suppress env.
- New exit code 55 is purely additive; no existing exit codes change
meaning.
* fix(cli): address audit findings for headless guardrails (#4103, #4502)
Round-1 audit (3 angles × line-by-line + removed-behavior + cross-file)
plus an open-ended design pass surfaced eight correctness issues. This
commit lands all of them; the larger ACP / serve-mode structural items
are documented for follow-up.
Correctness fixes
- headlessSafetyWarnings: `SANDBOX` env check reverted to plain truthy.
The sandbox transport sets `SANDBOX` to `sandbox-exec` (macOS
seatbelt) or the container name (`qwen-code-sandbox`), neither of
which matches `isTruthyEnv`. The PR's strict-`1`/`true` check was
emitting the "no sandbox" warning INSIDE real sandboxes. Match the
rest of the codebase (sandboxConfig.ts, gemini.tsx, Footer.tsx,
prompts.ts, …) which all treat any non-empty value as "sandboxed".
- nonInteractiveCli main-loop abort: add `finalizeAssistantMessage()`
before `routeAbort()`. The drain-item loop already had it (PR #4502
Critical bug #1); the main loop was asymmetric — stream-json
consumers would see an unterminated `message_start` when a budget /
SIGINT abort landed mid-stream.
- nonInteractiveCli drain-loop `routeAbort`: also flush
`flushQueuedNotificationsToSdk(localQueue)` and
`finalizeOneShotMonitors()` before exiting. The old `return`-and-
fall-through path went through the outer holdback loop, which did
this flushing; switching to `routeAbort()` skipped it, so
`task_started` envelopes lost their paired `task_notification`.
- nonInteractiveCli catch handler: emit `adapter.emitResult({...})`
BEFORE `handleBudgetExceededError`, with the budget message as
`errorMessage` when budget tripped. Previously the budget handler
`process.exit(55)`ed before the adapter could emit a terminal
`result` envelope, so STREAM_JSON consumers never saw a stream
terminator on budget exits and hung waiting for one.
- runBudget: new `validateMaxToolCalls` mirrors
`validateMaxWallTimeSetting`. yargs coerces non-numeric flag values
(`--max-tool-calls abc`) to `NaN`, and the enforcer's `>= 0` gate
treats `NaN` and negatives as "no limit", silently disabling the
budget. Reject `NaN`, `Infinity`, fractional, and negative-other-
than-`-1` values at both flag and settings layers. `0` remains
legal (`first tick aborts`), unlike wall-time where 0 is fatal.
- runBudget: new `MIN_WALL_TIME_SECONDS = 1` floor. Previously
`--max-wall-time 500ms` parsed cleanly and aborted on the next
event-loop tick before any model round-trip — almost certainly a
typo (`5m`?) and not a useful guardrail at any rate.
- nonInteractiveCli `tickToolCall`: exempt `ToolNames.STRUCTURED_OUTPUT`.
Under `--json-schema` this is the terminal "I'm done" contract tool,
not real work. Without the exemption a budget-edge completion is
aborted as a false positive (model used N tools then emitted
structured_output as call N+1 → exit 55 instead of success).
- commands/serve.ts: emit the YOLO-no-sandbox warning at daemon
startup when settings.json statically configures
`tools.approvalMode: 'yolo'` with no `tools.sandbox` /
`SANDBOX` env. The daemon can't use `getHeadlessYoloSafetyWarning`
(no Config yet — sessions get their own) so we re-derive the
predicate from settings. Per-session ACP override is documented as
out of scope.
Documentation
- `docs/users/features/headless.md`: new "Scope" subsection under
Run-level budgets explaining (a) `--max-tool-calls` counts top-level
dispatches only — subagent / `agent` tool inner calls are not
counted, (b) `structured_output` is exempt, (c) stream-json input
mode resets budgets per user message, (d) `qwen serve` / ACP
sessions do not currently consult budgets from settings.json.
Tests
- `runBudget.test.ts` grows from 32 → 41 tests: `validateMaxToolCalls`
(NaN / Infinity / negatives / fractional), `parseDurationSeconds`
sub-second rejection, `validateMaxWallTimeSetting` sub-second
rejection.
- `headlessSafetyWarnings.test.ts`: replaced the "still warns when
SANDBOX is 0/false/no" case (which encoded the strict-check bug) with
positive coverage for the real sandbox-set values
(`sandbox-exec`, `qwen-code-sandbox`).
All previously-green suites still green: cli/nonInteractiveCli (46),
cli/gemini.test (23), cli/config/config.test (220), core/utils/errors
(12), core/config/config.test (172). 337 tests across the touched suites.
Won't-fix (out of scope, documented or pre-existing)
- Unpaired `tool_use` in stream-json when a tool is aborted mid-execution
— pre-existing structural gap (SIGINT mid-tool has the same outcome);
PR amplifies it but doesn't introduce it.
- Narrow SIGINT-vs-budget-timer race — already mitigated by
`markExceeded`'s `signal.aborted` check.
- `tickToolCall` increments past abort (cosmetic; only affects the
`observed` value in the error envelope for a pathological caller).
* fix(cli): round-2 audit fixes for headless guardrails (#4103, #4502)
Round-2 audit (after round-1 commit
|
||
|
|
a8a6ad2d06
|
feat(core)!: redesign auto-compaction thresholds with three-tier ladder (#4345)
* 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
|
||
|
|
ed14a33064
|
feat(core): add NotebookEdit tool for Jupyter notebooks
Some checks are pending
Qwen Code CI / Classify PR (push) Waiting to run
Qwen Code CI / CodeQL (push) Blocked by required conditions
Qwen Code CI / Lint (push) Blocked by required conditions
Qwen Code CI / Test (macos-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Test (ubuntu-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Test (windows-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Post Coverage Comment (push) Blocked by required conditions
E2E Tests / E2E Test (Linux) - sandbox:docker (push) Waiting to run
E2E Tests / E2E Test (Linux) - sandbox:none (push) Waiting to run
E2E Tests / E2E Test - macOS (push) Waiting to run
Adds NotebookEdit as the structured write counterpart to existing notebook read support. Summary: - Add `notebook_edit` for safe cell-level `.ipynb` replace/insert/delete operations. - Integrate notebook editing with tool registration, permissions, Claude conversion, prior-read enforcement, IDE/inline modify flow, commit attribution, docs, and SDK permission docs. - Harden notebook read/edit behavior for truncated notebook renders, ambiguous fallback cell IDs, internal modify metadata, compact JSON, UTF-8 BOM notebooks, and cache behavior after structural edits. - Add unit and integration coverage for notebook read/edit behavior. Follow-up work remains for tab-indented notebook formatting preservation, a few low-risk unit-test additions, and non-blocking hardening suggestions from review. |
||
|
|
9985d91e08
|
feat(cli): add configurable plansDirectory for Plan Mode (#4062)
* feat(cli): add configurable plansDirectory for Plan Mode Add a plansDirectory setting that allows users to define a custom directory for approved Plan Mode files. Relative paths are resolved against the project root and validated to prevent path traversal. - Storage: add isPathWithinDirectory() with realpathSync-based symlink resolution to prevent traversal bypass attacks (direct, intermediate, and cross-drive) - Config: cache plansDir at construction time, use atomic write (write-temp then rename) to prevent corrupted plan files on crash - CLI: respect bareMode by clearing plansDirectory in minimal mode - Docs: document plansDirectory with requiresRestart and gitignore hint - Tests: 26 new tests covering path validation, symlink attacks (direct and intermediate), Windows cross-drive paths, mixed separators, and configuration integration Closes #3548 * fix(core): align symlink test with return value * fix(core): harden plans directory handling * fix(config): address PR #4062 review findings for plansDirectory - Handle EXDEV during atomic plan writes (cross-device rename fallback) - Sanitize session IDs to prevent path traversal in plan filenames - Expand tilde (~) in configured plansDirectory paths - Preserve plansDirectory in bare mode - Add EACCES/EPERM handling to getPlanFileNames with user-visible warnings - Close TOCTOU gap with post-write path containment validation - Fix docs to clarify plansDirectory is a top-level key - Add happy-path I/O tests for configured plansDirectory |
||
|
|
54fd5c50f0
|
feat(telemetry): add detailed sensitive span attributes (#4097)
Layer detailed content attributes onto the existing hierarchical spans (qwen-code.interaction / qwen-code.llm_request / qwen-code.tool) gated by includeSensitiveSpanAttributes: - Interaction span: user prompt (new_context) - LLM request span: system prompt + hash + preview + length (full text deduped per session via SHA-256), tool schemas (per-tool tool_schema events, also hash-deduped), model output - Tool span: tool input, tool result on every exit path (success + pre-hook block + post-hook stop + tool error + try-block cancel + catch-block cancel + execution exception) All large content truncated at 60KB with *_truncated and *_original_length metadata. Heavy serialization (safeJsonStringify on tool I/O, partToString on user prompt) is guarded by the sensitive flag at the call site so it doesn't run when telemetry is off. Also adds: - getActiveInteractionSpan() helper for client.ts to attach prompt attributes to the interaction span. - Updated config schema description and docs (telemetry.md + settings.md) to reflect expanded scope and add security/cost notes. - 28 unit tests for detailed-span-attributes, 4 tests for getActiveInteractionSpan, integration mocks updated. |
||
|
|
d343e2c15e
|
feat(perf): progressive MCP availability — MCP no longer blocks first input (#3994)
Some checks are pending
Qwen Code CI / Classify PR (push) Waiting to run
Qwen Code CI / Lint (push) Blocked by required conditions
Qwen Code CI / Test (macos-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Test (ubuntu-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Test (windows-latest, Node 22.x) (push) Blocked by required conditions
Qwen Code CI / Post Coverage Comment (push) Blocked by required conditions
Qwen Code CI / CodeQL (push) Blocked by required conditions
E2E Tests / E2E Test (Linux) - sandbox:docker (push) Waiting to run
E2E Tests / E2E Test (Linux) - sandbox:none (push) Waiting to run
E2E Tests / E2E Test - macOS (push) Waiting to run
* feat(perf): progressive MCP availability — MCP no longer blocks first input
Today `Config.initialize()` runs MCP discovery synchronously and the cli
can't accept input until every configured MCP server finishes its
discover handshake. One slow or hung server bottlenecks every user with
MCP configured. Validated by the profiler instrumentation added in this
PR (set `QWEN_CODE_PROFILE_STARTUP=1` to reproduce):
| User scenario | Time to first prompt input |
| ------------------------- | -------------------------- |
| No MCP | ~480 ms |
| 1 fast MCP | ~875 ms |
| 2 fast + 1 slow MCP | **~7.1 s** |
| 1 hung MCP server | **~10.5 s** |
(Measured on macOS arm64 / Node 24.15, n=30/fixture, p50.)
`Config.initialize()` now passes `{ skipDiscovery: true }` to
`createToolRegistry` by default and kicks off MCP discovery in a
fire-and-forget background path. As each server completes discover,
the cli's `AppContainer` debounces `setTools()` calls into one-frame
(16 ms) batches so the model sees the consolidated tool list shortly
after each server settles. Rollback: `QWEN_CODE_LEGACY_MCP_BLOCKING=1`.
- `packages/core/src/config/config.ts` — `Config.initialize` switches
to `skipDiscovery: true` + new `startMcpDiscoveryInBackground()`
(defensive against partially-stubbed `ToolRegistry` in tests). Adds
`MCPServerConfig.discoveryTimeoutMs` (last positional ctor param —
doesn't shift existing call sites). Tool-call timeout is untouched.
- `packages/core/src/tools/tool-registry.ts` — new
`getMcpClientManager()` getter so the background path can call the
incremental discover directly without going through `discoverMcpTools`
(which would wipe already-registered tools).
- `packages/core/src/tools/mcp-client-manager.ts` —
`discoverAllMcpToolsIncremental` now: emits `mcp-client-update`
after IN_PROGRESS transition, wraps each per-server discover in a
discovery-only timeout (stdio 30s, remote 5s), emits trailing
`mcp-client-update` after COMPLETED so UI subscribers see the
terminal state.
- `packages/cli/src/ui/AppContainer.tsx` — new `useEffect` (gated on
`isConfigInitialized`) subscribes to `mcp-client-update` and
16ms-batches `setTools()` calls. Same effect also defers
`finalizeStartupProfile` until MCP settles (or 35s hard cap), so
startup-perf profiles capture the full MCP timeline.
Activated only by `QWEN_CODE_PROFILE_STARTUP=1`; when unset every
profiler entry point short-circuits in a single null/flag check and
returns. Heisenberg overhead measured at -1.12% Δp50 between
profile-on vs profile-off (Welch p=0.092, n=30/config × 3 configs) —
within statistical noise.
- `packages/cli/src/utils/startupProfiler.ts` — extended with
`events` array (multi-fire), `recordStartupEvent`,
`setInteractiveMode`, `derivedPhases`, per-checkpoint heap snapshots,
`MAX_EVENTS` cap, and `QWEN_CODE_PROFILE_STARTUP_OUTER` / NO_HEAP
env opt-ins. + 7 new tests.
- `packages/core/src/utils/startupEventSink.ts` (new) — minimal
cross-package sink so `core` can emit profiler events without
reverse-depending on `cli`. No-op when no sink registered. + 4 tests.
- `packages/core/src/index.ts` — export `setStartupEventSink` /
`recordStartupEvent` / type aliases.
- `packages/cli/src/gemini.tsx` — registers the sink at `main()`
entry, adds `first_paint` checkpoint after Ink render, calls
`setInteractiveMode(true)` in the interactive branch.
- `packages/core/src/config/config.ts` — emits
`tool_registry_created`.
- `packages/core/src/core/client.ts` — emits `gemini_tools_updated`
at the end of `setTools()`.
- `packages/core/src/tools/mcp-client-manager.ts` — emits
`mcp_discovery_start`, `mcp_server_ready:<name>`,
`mcp_first_tool_registered`, `mcp_all_servers_settled`.
- `packages/cli/src/ui/AppContainer.tsx` — emits
`config_initialize_start`, `config_initialize_end`, `input_enabled`.
`Config.initialize()` now returns BEFORE MCP discovery completes.
Things to check:
- Any code path that assumed "after `config.initialize()`, all MCP
tools exist in the registry" — these will see only built-in tools
initially; new tools appear via `mcp-client-update` events.
- `MCPDiscoveryState.COMPLETED` is now set asynchronously instead of
synchronously after `initialize()` resolves.
- Model requests issued before MCP settles see only built-in tools;
subsequent requests see the full set as servers come online.
- Tests that assert MCP tool count immediately after
`config.initialize()` should wait for the `mcp-client-update` with
COMPLETED discoveryState instead.
- 313 impacted-area tests green (config / mcp-client-manager / client
/ startupProfiler 18 / startupEventSink 4).
- `tsc --noEmit` clean for `packages/core` and `packages/cli`.
- `eslint` clean on touched files.
- Manual: `QWEN_CODE_PROFILE_STARTUP=1 SANDBOX=1` interactive run
produces a JSON profile in `~/.qwen/startup-perf/` containing
`first_paint`, `config_initialize_start/end`, `input_enabled`,
MCP per-server events, and `gemini_tools_updated`. See PR
description's "How to validate" section.
Generated with AI
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(core): harden progressive MCP discovery against silent regressions
Addresses review feedback on PR #3994:
- Skip user-disabled servers in discoverAllMcpToolsIncremental. The new
incremental path used to iterate Object.entries(servers) without
consulting isMcpServerDisabled, so a server the user had explicitly
turned off would still get connected and its tools registered.
Mirrors the existing protection in discoverAllMcpTools.
- Disconnect the underlying client when runWithDiscoveryTimeout fires.
Without this, the inner discoverMcpToolsForServer kept running after
the timeout rejected the outer promise — if discover() eventually
succeeded it would register the late server's tools into the live
toolRegistry (a silent registration vector, especially exploitable
with a 0/negative discoveryTimeoutMs override).
- Clamp discoveryTimeoutMs to [100ms, 300_000ms]. 0/negative/Infinity
values previously passed through to setTimeout unvalidated and made
the silent-registration bug above trivially reachable.
- Classify the `tcp` (WebSocket) transport field as remote so hung WS
handshakes use the 5s default instead of the 30s stdio default.
- Defensive delete of serverDiscoveryPromises[name] in the per-server
catch so a doomed/orphan entry can't briefly short-circuit a
subsequent discoverMcpToolsForServer call.
Adds focused tests for each fix.
Generated with AI
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(cli): restore runtime.json sidecar and harden non-interactive MCP visibility
Addresses review feedback on PR #3994:
- Restore writeRuntimeStatus + markRuntimeStatusEnabled in
startInteractiveUI. The progressive-MCP diff inadvertently dropped
the runtime.json sidecar write from the interactive entry point,
leaving Config.refreshSessionId()'s session-swap refresh as dead
code and silently breaking external integrations (terminal
multiplexers, IDE integrations, status daemons) that map PID →
sessionId via runtime.json.
- Add Config.getFailedMcpServerNames() and surface a stderr warning
in --prompt / stream-json / ACP entry points when one or more MCP
servers failed during background discovery. Per-server errors are
caught inside discoverAllMcpToolsIncremental and never reached a
TTY otherwise, so a script using non-interactive mode with broken
MCP config would silently run with only built-in tools — a
regression vs the legacy synchronous path.
- Pass the parsed `settings` object through to
runNonInteractiveStreamJson. The new call site dropped the
argument, falling back to createMinimalSettings() and losing any
user-configured permission / approval / hook setup for stream-json
sessions. Added regression assertion to gemini.test.tsx.
- Move finalizeStartupProfile out of gemini.tsx's stream-json branch
and into Session.ensureConfigInitialized so it runs AFTER
config.initialize() / waitForMcpReady() in stream-json. Previously
the profile was finalized before any MCP / config_initialize_*
events were emitted, producing empty stream-json profiles.
- Gate setStartupEventSink registration on isStartupProfilerEnabled()
so core-side recordStartupEvent calls short-circuit at the first
null-check when profiling is disabled, instead of going through an
arrow wrapper and the profiler's own enabled gate.
- Tighten the type-unsafe ToolRegistry cast in
startMcpDiscoveryInBackground to preserve the typed return signature
so a rename of getMcpClientManager would be flagged at this call
site (kept the optional-chain guard for tests that stub
ToolRegistry as a plain object).
- Re-document first_paint as "render call returned" so consumers don't
confuse Ink's synchronous render() return with literal pixel paint.
Kept the checkpoint name for backward compatibility with collected
profiles.
Generated with AI
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(cli): restore resize repaint and pin gemini_tools_lag capture in AppContainer
Addresses review feedback on PR #3994:
- Restore the terminal-resize useEffect that calls
repaintStaticViewport() when terminalWidth changes. The progressive-
MCP diff removed previousTerminalWidthRef + the repaint useCallback
+ the resize useEffect, so tmux pane resizes and fullscreen toggles
leave the static region rendered at the old width — header content
visibly tears until something else triggers refreshStatic.
- Pin the gemini_tools_lag startup metric. The previous onMcpUpdate
handler called finalizeOnce() synchronously when discovery reached
COMPLETED, but the pending setTools() batch was still 16ms away.
setTools() emits `gemini_tools_updated` — when finalize ran first
the profile's `finalized` guard suppressed that event, so
gemini_tools_lag came out undefined in interactive mode. New
onMcpUpdate flushes setTools() NOW on COMPLETED and only finalizes
after the flush resolves, guaranteeing the event lands.
- Log setTools() batch-flush errors via debugLogger instead of
silently swallowing them. GeminiClient.setTools() has no try/catch
around warmAll() / getFunctionDeclarations() / getChat().setTools();
the previous `.catch(() => {})` would have hidden production
tool-registration regressions completely.
Generated with AI
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(core): correct MCP failure visibility and incremental cleanup
Addresses three review findings on PR #3994:
- McpClient.discover() now flips the client status to DISCONNECTED before
re-throwing. Previously, a server that connected successfully but whose
discoverPrompts / discoverTools then rejected (or that returned no
prompts and no tools) would remain CONNECTED in the global status
registry. Config.getFailedMcpServerNames() filters by
`status !== CONNECTED`, so such servers were silently omitted from the
non-interactive failure banner and the Footer's MCP health pill kept
counting them as healthy.
- discoverAllMcpToolsIncremental no longer records `outcome: 'ready'`
for servers whose connect/discover threw. The inner
discoverMcpToolsForServerInternal catches errors without re-throwing
(best-effort discovery semantics), so the try block resolved even for
failures — only the runWithDiscoveryTimeout path reached the catch.
Auth errors, server crashes, and missing-tools responses were therefore
recorded as success in the startup profile. We now consult the actual
server status (now correctly DISCONNECTED after the first fix) before
emitting `ready`, and emit `outcome: 'failed'` otherwise.
`mcp_first_tool_registered` is gated on the same check so a failed
server can't pollute that user-facing metric.
- discoverAllMcpToolsIncremental tears down enabled→disabled mid-session
transitions. When a previously-connected server is disabled (e.g. via
`/mcp disable foo` or by editing settings), the incremental path used
to just `continue` past it, leaving its client, tools, health check,
and global status entry in place. Now calls removeServer() for any
already-known client we encounter in the disabled branch.
Adds focused tests for each fix.
Generated with AI
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* docs(core): clarify ToolRegistry cast comment in startMcpDiscoveryInBackground
Addresses review feedback on PR #3994. The previous comment claimed the
call site uses "no defensive cast" but the code still casts via
`as ToolRegistry & { getMcpClientManager?: ... }`. Reword to explain
the cast's actual purpose: it exists only because some tests stub
ToolRegistry as a plain object, so we use optional chaining to avoid
crashing the init path when those tests run. Also note that the inner
shape now uses `ReturnType<ToolRegistry['getMcpClientManager']>` — a
future rename of the production method still surfaces as a type error
at this call site rather than silently falling through to the
`if (!manager)` branch.
Comment-only change; no behavior diff.
Generated with AI
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(core): close MCP timeout TOCTOU race and propagate disconnect status
Addresses two critical findings on PR #3994 round 6:
- runWithDiscoveryTimeout no longer uses fire-and-forget disconnect. The
prior `void client.disconnect()` returned before `transport.close()`
landed, leaving a window where an in-flight `discover()` could pump
`tools/list` through the transport and synchronously register tools
into the live registry BEFORE the close took effect. The earlier fix
comment described this as a "remote-exploitable silent-tool-registration
vector"; the await closes the timing window but doesn't help if tools
already landed, so we also drop them with `removeMcpToolsByServer()`
after the disconnect resolves. No-op when discover hadn't reached
registration yet.
- McpClient.disconnect() now writes DISCONNECTED to the global registry
directly. Previously, `isDisconnecting = true` was set BEFORE the
internal `updateStatus(DISCONNECTED)` call, and `updateStatus`'s guard
(designed to suppress LATE writes from a stale `connect()` catch)
silently swallowed the write. The global stayed CONNECTED forever for
timeout-disconnected servers, so `Config.getFailedMcpServerNames()`
(which filters `status !== CONNECTED`) omitted them from the
non-interactive failure banner and the Footer's MCP health pill kept
counting them as healthy. This invalidated the round-5
`getMCPServerStatus === CONNECTED` gate, which would always pass the
"ready" check for timed-out servers. The guard stays in place for its
original purpose; the legitimate disconnect→DISCONNECTED notification
now bypasses it by writing the registry directly.
Also adds the `config_initialize_start` / `_end` profiler checkpoints
to `Session.ensureConfigInitialized()` so stream-json startup profiles
include the same derived `config_initialize_dur` phase as the
non-stream-json branch in gemini.tsx (round 6 [Suggestion]).
Tests cover (a) the disconnect-and-cleanup path on timeout and (b) the
intentional-disconnect global registry propagation regression.
Generated with AI
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
* fix(mcp): surface failures + prevent health-check resurrection of timed-out servers
Round-7 review follow-ups:
- AppContainer (interactive): MCP startup failures now route through
debugLogger.warn on COMPLETED. Was silent — only debug logs / profile
events surfaced failures, so regular interactive users got no
indication their MCP servers failed. Mirrors the non-interactive
stderr warning, adjusted to debugLogger so it doesn't collide with
Ink's rendered output.
- acpAgent per-session: `QwenAgent.initializeConfig()` now emits the
same `Warning: MCP server(s) failed to start` stderr line as the
top-level `runAcpAgent` path. Previously per-session ACP configs
with failed MCP servers silently fell back to built-in tools.
- mcp-client-manager timeout handler: after disconnecting an
intentionally timed-out server, also drop it from `this.clients` and
stop any pending health-check timer. Without this the discovery
`finally` block would arm a health-check that detected DISCONNECTED
status and called `reconnectServer()` → `discoverMcpToolsForServer()`
directly — bypassing `runWithDiscoveryTimeout` entirely and silently
resurrecting the slow server. `startHealthCheck` also early-returns
for unknown servers so the trailing finally-block call is a no-op.
- startupEventSink: silent `catch {}` now logs via `debugLogger.error`
so a corrupted sink doesn't silently drop every subsequent event.
Quiet by default; visible under `QWEN_CODE_DEBUG=1`.
Tests:
- mcp-client-manager.test.ts: regression for the timeout → no-reconnect
invariant (clients map purged + health-check timer absent).
- acpAgent.test.ts: per-session newSession surfaces failures to stderr,
and stays safe when Config lacks `getFailedMcpServerNames`.
Declines (with reasoning in PR reply):
- [Critical] AppContainer batch-flush useEffect untested → re-flag of
the round-5 deferral that wenshao acknowledged at the time. Lower-
layer invariants (this PR's mcp-client-manager + mcp-client tests)
pin the dependent contracts. The component-test harness for timers +
event emitters in this file is non-trivial and out of scope; tracked
for a follow-up.
Generated with AI
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
---------
Co-authored-by: 秦奇 <gary.gq@alibaba-inc.com>
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
|
||
|
|
533daac316
|
feat(cli): wrap markdown links in OSC 8 so wrapped URLs stay clickable (#4037)
* feat(cli): wrap markdown links in OSC 8 so wrapped URLs stay clickable Long URLs the model emits inside `[label](url)` or as bare `https://...` get line-wrapped by the terminal, which prevents most emulators from detecting them as a single clickable region. OSC 8 hyperlinks decouple the link target from the visible label so the entire label remains one clickable target regardless of where it wraps. - Extract the existing OSC 8 helpers from AuthenticateStep into a shared packages/cli/src/ui/utils/osc8.ts util, plus a dependency-free capability detector that honors NO_COLOR / FORCE_COLOR=0 / CI / non-TTY stdout, with FORCE_HYPERLINK=1 and QWEN_DISABLE_HYPERLINKS=1 overrides for explicit opt-in / opt-out. - Wire InlineMarkdownRenderer to wrap markdown link labels and bare autolinks in an OSC 8 envelope when supported. Wrapping happens after the inline link token has been fully matched, so streamed partial chunks cannot split an envelope across flushes. - Fall back to the legacy `label (url)` rendering byte-for-byte when the host terminal does not advertise OSC 8 support. Closes #3954 * fix(cli): harden OSC 8 markdown wrapping after multi-round audit Address findings from a multi-round design and code audit of the OSC 8 hyperlink feature: Design fixes: - Keep the visible `(url)` suffix in supported terminals too — preserves copy-paste UX and lets users preview suspicious URLs before clicking. OSC 8 is now purely additive (byte-identical unsupported output, plus envelope on supported terminals). - Restrict OSC 8 wrapping to http/https/mailto/ftp/sftp/ssh schemes; javascript:/data:/file:/vbscript: fall through unwrapped so the user can read the target. Prompt-injection defense for LLM output. - Reject URLs with whitespace — every terminal treats whitespace in an OSC 8 target as truncation/rejection, which would turn the whole region into an un-clickable trap. - Block OSC 8 inside tmux/screen by default; require `FORCE_HYPERLINK=1` opt-in. The multiplexer hides the host terminal's capabilities, so emitting passthrough escapes on a host without OSC 8 prints garbage. - Version-gate `supportsHyperlinks()` (iTerm ≥3.1, vscode ≥1.72, WezTerm ≥20200620, VTE ≥0.50 with 0.50.0 segfault carve-out), block CI / TEAMCITY / win32 (modulo WT_SESSION/Kitty/Ghostty/DOMTERM), mirror `supports-hyperlinks` semantics. - Extend the link regex to allow one level of balanced parens in the URL group so `[wiki](https://en.wikipedia.org/wiki/Foo_(bar))` isn't truncated at the inner `)`. - Trim trailing sentence punctuation off the OSC 8 *target* for bare URLs (`.`, `,`, `;`, `:`, `!`, `?`, `'`, `"`, `` ` ``) and unbalanced trailing `)]}` so the clickable URL resolves to a real page. - Catch VTE 0.50.0 reported in packed form (`'5000'`) — the original string compare missed it and let the segfault through. Code fixes: - Consolidate `wrapForMultiplexer` with the pre-existing `packages/cli/src/utils/osc.ts` — no more duplicate helpers. - Drop the `supportsHyperlinks` memoization cache so runtime env changes (NO_COLOR / theme toggles) take effect immediately. - Extract `MD_LINK_PATTERN`, `MD_LINK_CAPTURE`, `shouldWrapMarkdownLink`, and `HYPERLINK_ENV_KEYS` into `osc8.ts` so the React and ANSI renderers stay in lockstep. - Hoist `supportsHyperlinks()` once per render (both renderers). - Apply the same OSC 8 treatment to `TableRenderer` so markdown links inside tables are clickable too. - Rewrite `trimTrailingUrlPunctuation` to O(n) by pre-counting opens. Tests cover: balanced parens in URL, dangerous-scheme rejection, whitespace-URL rejection, trailing-punctuation trimming, tmux blocking, version gating (iTerm/WezTerm/vscode/VTE incl. packed form), platform fallbacks, mid-stream chunk balance, byte-identical legacy fallback. * feat(cli): detect Alacritty / Konsole / Warp / JetBrains / mintty for OSC 8 Expand supportsHyperlinks() to recognize five more capable terminals that the original detector silently treated as unsupported: - Alacritty ≥ 0.11 via TERM=alacritty (the issue explicitly calls this one out) - Konsole ≥ 21.04 via KONSOLE_VERSION - WarpTerminal via TERM_PROGRAM=WarpTerminal - JetBrains JediTerm (IDE integrated terminals) via TERMINAL_EMULATOR - mintty (Git Bash on Windows, etc.) via TERM_PROGRAM=mintty Hyper stays auto-detection-off (FORCE_HYPERLINK=1 override) because plugin chains have a long history of breaking escape passthrough. Apple_Terminal stays off because it has no OSC 8 support at all. KONSOLE_VERSION and TERMINAL_EMULATOR added to HYPERLINK_ENV_KEYS so the test isolation list stays in sync. * chore(cli): polish OSC 8 detector after another audit round Address findings from the final multi-round audit pass: - Document `FORCE_HYPERLINK` and `QWEN_DISABLE_HYPERLINKS` in the user-facing env-vars table at docs/users/configuration/settings.md so the new opt-in / opt-out surface is discoverable without grepping source. - Detect Alacritty even when the alacritty terminfo entry isn't installed (a common Linux distro scenario where Alacritty falls back to TERM=xterm-256color). Fall back to ALACRITTY_LOG / ALACRITTY_WINDOW_ID / ALACRITTY_SOCKET — Alacritty sets at least one of these unconditionally since 0.12. - Trim a trailing `>` off the OSC 8 target so CommonMark autolinks (`<https://example.com>`) produce a clickable target that actually resolves instead of 404-ing because of the captured delimiter. - Add OSC 8 / hyperlink env isolation to TableRenderer.test.tsx so a developer running the suite from iTerm2 / WezTerm / Kitty can't leak escape bytes into table output. - Symmetric `isTTY` reset in osc8.test.ts `beforeEach` so the early describes (sanitizer, scheme, trim) don't inherit residual TTY state from a prior test. - Document the deliberate security property of keeping the visible `(url)` suffix in OSC 8 mode (user always reads the destination before clicking) in the SAFE_OSC8_SCHEMES comment. - Collapse the `wrapForMultiplexer` import + re-export to a single `export { wrapForMultiplexer }` after the local import. - Add ALACRITTY_* keys to HYPERLINK_ENV_KEYS so test isolation lists stay complete. Tests cover the new autolink `>` trim, the Alacritty env-var fallbacks, and NBSP / Unicode-whitespace URL rejection. * fix(cli): tighten OSC 8 gating per PR review Two fixes from chiga0's review on PR #4037: 1. Move the non-TTY check above `FORCE_HYPERLINK` so a user with `FORCE_HYPERLINK=1` in their shell profile still gets a clean pipe when they run `qwen | cat` or `qwen > out.txt`. The "non-TTY stdout must suppress escapes" acceptance criterion now holds even under forced enable. 2. Version-gate the Konsole detection at `>= 21.04`. KONSOLE_VERSION is set by every Konsole release including ones that pre-date OSC 8 support, so the existence check alone false-positives on Konsole 20.x. Parse the packed integer (21.04 → 210400) and let older releases fall through to the legacy fallback. Updates the docs row for FORCE_HYPERLINK to make the non-TTY caveat explicit. Splits the prior "FORCE_HYPERLINK + isTTY=false" test into two — one verifying force works on a TTY, one asserting it never escapes the non-TTY guard. Adds a Konsole < 21.04 regression test. * fix(cli): stop auto-detecting Warp Terminal as OSC 8 capable Warp's current rendering engine doesn't honor OSC 8 envelopes — the escape sequence is printed as visible garbage rather than recognized as a clickable hyperlink. Falling through to the legacy `label (url)` rendering avoids the regression on Warp. Users on a Warp build that ever ships OSC 8 support can opt in with `FORCE_HYPERLINK=1`; the case will be reinstated in the switch when Warp lands real support upstream. Test flipped from "enabled" to "not auto-detected, FORCE_HYPERLINK opts in" to lock the new behavior. * feat(cli): drop visible (url) suffix when OSC 8 wrapping is active In the originally shipped renderer, `[label](url)` was rendered as `label (url)` even when OSC 8 wrapped the region. With long URLs that's clutter for no benefit — capable terminals already expose the target via hover / status bar / right-click "copy link" without needing the URL in the visible stream. When `shouldWrapMarkdownLink(url, canHyperlink)` returns true, the React renderer and the ANSI table renderer now emit only the markdown label (link-colored), with the OSC 8 envelope pointing at the full URL. Empty labels (`[](url)`) fall back to using the URL as the visible label so the link stays discoverable. When the predicate returns false (unsupported terminal, unsafe scheme, whitespace URL) the legacy `label (url)` rendering is preserved byte-for-byte — the scheme allowlist still guarantees the user sees the destination before any click on a `javascript:` / `data:` / etc. link. Tests updated to assert label-only visible bytes in wrap mode and an empty-label fallback case added. Comment block in `osc8.ts` updated to reflect the new visibility contract. * fix(cli): strip C1 controls in OSC 8 sanitizer sanitizeForOsc() only removed C0 + DEL, so 8-bit ST (\x9c) and 8-bit OSC (\x9d) bytes could still survive inside an OSC 8 target. On terminals that honor C1 controls, those bytes act as the same sequence boundaries as their two-byte ESC counterparts, which defeats the escape-injection hardening this helper is meant to provide. Extend the regex to also strip \x80-\x9f and cover the case with a test. * fix(cli): harden OSC 8 link sanitization and tighten gating Three independent issues found while auditing the markdown OSC 8 path: 1. sanitizeForOsc() previously left Unicode bidi controls (U+200E/F, U+202A-E, U+2066-9) and line/paragraph separators (U+2028/9) intact. A model-emitted RLO in a link label visually reverses trailing bytes, spoofing the host the user thinks they're clicking — exactly the click-deception attack the scheme allowlist is meant to block, just moved from the URL into the visible label. Extend the regex to strip those bytes too. 2. The visible label rendered inside the OSC 8 envelope went straight to the terminal without sanitization, so even with (1) the spoof would still land. Wire sanitizeForOsc() over the linkText in both InlineMarkdownRenderer and TableRenderer's OSC 8 branches. The legacy `label (url)` branches stay untouched so today's unsupported-terminal output remains byte-identical. 3. AuthenticateStep emitted osc8Hyperlink(authUrl) unconditionally, leaking escape bytes into pipes / non-OSC-8 terminals — inconsistent with the suppression contract documented for the rest of the PR. Gate it on supportsHyperlinks() so it falls back to the bare URL. Test coverage added: - sanitizeForOsc bidi/line-separator strip - bidi spoof in the rendered markdown label - byte-equality fallback on unsupported terminals - TableRenderer markdown link → OSC 8 (positive, fallback, unsafe scheme, bidi-spoof) — the table renderer had zero OSC 8 coverage before this. * fix(cli): keep `(url)` visible when an OSC 8 label looks like a different URL Adversarial round-2 audit identified a label-as-URL deception attack: when the OSC 8 branch elides the `(url)` suffix and shows only the clickable label, a model-emitted `[https://google.com](https://attacker.com)` renders a "google.com" link that resolves to attacker.com. Pre-OSC-8 rendering kept `(url)` visible so the user could see the real target; hiding it makes the click-deception case land. Mitigation: a new `labelMayDeceive(label, url)` predicate. When the label contains a URL-shaped substring AND it doesn't equal the actual target, both renderers keep the legacy `(url)` suffix while still emitting the OSC 8 envelope — the link stays clickable, the user still sees where the click goes. Heuristic is permissive on purpose: false positives are harmless (redundant `(url)` on niche labels), false negatives let a real spoof through. Tests: positive (mismatched URL labels), negative (label == url, plain text labels), in both InlineMarkdownRenderer and TableRenderer. * fix(cli): catch bare-host label deception in OSC 8 wrapping Round-3 audit caught a false-negative in labelMayDeceive: the `://` substring check only flagged labels with a fully-qualified URL shape. The most natural markdown spoof — `[google.com](https://evil.com)` — uses a bare host as the label and slipped past, so the OSC 8 branch elided the `(url)` suffix and rendered a clickable "google.com" that resolved to evil.com. Add a third detection pattern: extract host-like tokens from the label (`name.tld` with an alphabetic 2+ char TLD), and flag the link when any of them doesn't equal the URL's parsed hostname. Plain labels like `docs` / `click here` don't match the regex, version strings like `1.2.3` are skipped (last segment is numeric), and `[google.com](https://google.com)` is honest rendering — none of these get flagged. ASCII-only matching means an IDN-homograph attack on a bare-host label (Cyrillic `о`) still escapes this layer; the fully-qualified form of the same attack is still caught by the existing `://` rule, which is the only form an LLM is realistically likely to emit. Tests cover: bare-host mismatch, punycode IDN target, same-host / different-path, label==target negative, plain-text labels, version strings. * fix(cli): handle mailto: target in labelMayDeceive Round-4 audit caught a false positive: `new URL('mailto:x@y').hostname` is empty, so targetHostname() returned undefined and the defensive `return true` branch fired any time a mailto label contained an email-shaped string. A perfectly honest `[support@example.com](mailto:support@example.com)` was being flagged as deceptive and getting a redundant `(url)` suffix on capable terminals. Special-case mailto: by pulling the domain from after the `@` in the URL pathname, matching what the user would compare against. A mismatched mailto (e.g. `[support@example.com](mailto:abuse@evil.com)`) still flags correctly. Also drop a dead `HOST_LIKE_RE.lastIndex = 0` reset — `.match()` doesn't consult lastIndex, so the line was a no-op. * fix(cli): catch IPv4-literal label deception in OSC 8 wrapping Round-5 audit found another bare-host bypass: a label like `[1.1.1.1](https://attacker.com)` (or any other dotted-quad such as `[192.168.1.1]` / `[8.8.8.8]`) escaped labelMayDeceive because the existing host regex anchors on a 2+ alphabetic TLD. The user would see a clickable "1.1.1.1" that resolves to attacker.com with no visible target. Add a separate dotted-quad pattern and combine it with the host-token list before comparing against the URL's hostname. False-positive surface is small (over-permissive on octet ranges is harmless — worst case is an extra `(url)` suffix on a label like `999.999.999.999`). Tests cover mismatched IPv4, IPv4 spelled inside surrounding text, and label-equals-target IPv4 (which must NOT flag). * fix(cli): sanitize URL when rendered as visible text in OSC 8 path Two PR review findings: 1. config-utils.ts dropped the `resolvePath(...)` call (and its import) that origin/main introduced in #4045 for tilde / relative `cwd` paths in channel configs. The auto-merge silently reverted it the same way it did `packages/channels/base/src/index.ts`. Restore main's content. 2. Anti-spoof sanitization was only applied to `linkText`, but the OSC 8 render path emits the URL as visible text in two places that bypassed it: - empty-label fallback `safeLabel || url` — `[](https://x/aevil)` would print the URL with RLO intact even though the OSC target was sanitized. - deceptive-label `(url)` suffix. Compute `safeUrl = sanitizeForOsc(url)` once in the OSC 8 branch and use it for both visible-URL renderings. The OSC target inside `osc8Open` keeps the raw URL (sanitization happens inside the helper anyway). Same fix mirrored in `TableRenderer.tsx`. The legacy `label (url)` branch on unsupported terminals stays untouched so its byte-identical-fallback contract holds. Test added: `[](https://example.com/aevil)` round-trips through the renderer with the RLO stripped from both the OSC target and the visible URL fallback. |