* ci: shard the Linux unit-test lane eight ways behind one build
The Linux Test job ran 45-59 minutes: a ten-minute prepare build, then the CLI and core suites back to back. A new test_build job runs the prepare build once and uploads its outputs; eight shards install without the build, unpack them and run --shard=N/8 of every Vitest suite. Test (ubuntu-latest, Node 22.x) becomes an aggregate that passes only when the build and every shard pass.
* ci: record ci.yml's growth from the test_build prelude
test_build carries the same pre-checkout cleanup, checkout and install prelude as the test shards; ci-platform-lanes.test.js pins the two copies identical.
* ci: record the Linux lane's two new jobs in the PR-stage budget
test_build and the test_ubuntu aggregate add two jobs; the declared timeouts drop from 305 to 295 minutes.
* ci: shard the web-shell E2E smoke four ways
The smoke lane ran 44-46 minutes on every recent PR, about 33 of them in the browser tests at two workers, and is the longest lane once the Linux unit tests are sharded. Each shard runs --shard=N/4 of the smoke; the transcript gate runs on the first. web-shell E2E Smoke (ubuntu-latest, Node 22.x) becomes an aggregate over the shards.
* ci: bound the unit shards' tree download and retry it once
A pool host stalled 17 minutes in download-artifact while the other shards took under a minute.
* ci: rebuild only the workspaces a change reaches
scripts/ci-build-cache.mjs hashes each workspace's tracked build inputs (tests excluded) with its workspace dependencies' hashes and the shared root inputs. test_build and the web-shell smoke shards restore the newest cached build and rebuild only workspaces whose hash changed. A push to main always builds from scratch and saves, so a pull request starts from a clean build of main.
* docs(ci): describe the incremental build cache
* ci: keep the build cache path the same on every pool host
actions/cache versions an entry by its path; under runner.temp the path differs per host, so a run could never restore another host's save.
* ci: save the ARM64 build cache from the smoke lane, and run the aggregates on the shards' runners
The smoke shards run on the ARM64 pool, which test_build may not, so the first shard saves the clean build it made when its restore found nothing. The two aggregate checks queued 9 and 13 minutes for a hosted runner after their shards finished; they now take the shards' runners.
* ci: bound the sharded test step and skip shards when the build fails
Address the first automated review round on the Linux sharding lane:
- Gate every build-consuming shard step on `test_build` success. `!cancelled()`
stays true when a needed job fails, so a failed build still started all eight
shards, each paying a full install before dying at the missing artifact and
reporting artifact plumbing as its failing step.
- Drop the test step cap to 45 minutes. The job cap is 60, so the old 110 could
never fire; a step timeout keeps the diagnostic steps below it alive while a
job timeout does not.
- Keep the built-tree artifact for a week so a late "re-run failed jobs" still
finds it, and correct the trigger comment that still named three post-merge
jobs when five now accept push.
Co-authored-by: Qwen-Coder <[email protected]>
* ci: keep disk telemetry for a failed build and correct the design doc
`test_build` installs with the disk sampler and then builds for up to its
whole timeout, but the sampler dies with the install step's trap and no
collector ran, so an ENOSPC build (or the OOM that took a shard host) kept
no evidence. Give it the same failure-gated dump and last-step upload as
`lint_and_static`, under its own artifact name.
The incremental-lint design still said the test job keeps normal prepare
behaviour; this lane now installs with `QWEN_SKIP_PREPARE=1` and unpacks
the tree built once by `test_build`. Correct both language versions.
Co-authored-by: Qwen-Coder <[email protected]>
* ci: share the built-tree definition and the build preflight, harden the guards
The archive step re-implemented `builtPaths()` from `scripts/ci-build-cache.mjs`,
so the tree the shards unpack had a second definition that could drift from the
one `pack` stores. A `paths` mode now prints that list for `tar -T -`, and a new
test pins the four artifact-name literals that tie the producer to the eight
consumers.
The cached branch of `build` also hand-reproduced a subset of `scripts/build.js`
and so skipped its ink-patch preflight: the same missing
`frame-controller.d.ts` self-healed on a cache miss and surfaced as ~50 tsc
errors inside ink's declarations on a hit. The preflight is now a function
reachable as `scripts/build.js --preflight` and runs before both branches.
The remaining review suggestions were all meta-test gaps: the standalone-runtime
expression and the `test_build`/`test` prelude were guarded by nothing that
compares them in order, `ci-build-cache.mjs`'s three CI modes were never
executed by a test, and the infra-classification filter's step name was not
joined to `ci.yml`. Each now has an assertion that goes red when the guard is
removed.
Co-authored-by: Qwen-Coder <[email protected]>
* ci: bound the build steps so the failure collectors can run
Round-2 review found four issues in the previous round's fixes and one gap
in the new build tests.
A job timeout cancels the job and skips the failure-gated collectors, so the
`test_build` steps that can block now carry caps below the job's 45 minutes:
the install, the build, the pack and the archive. The install caps are
identical across `test_build`, `test` and `lint_and_static` so the prelude
parity guard still compares the three copies field for field. A test pins
every blocking cap under the job ceiling.
The `--preflight` early exit was only asserted as a string, so it could be
renamed with nothing going red while the cache-hit path silently ran the
full build. A spawned case now copies `scripts/build.js` into the fixture
and asserts the flag exits without generate, a workspace build or the
schema step.
The CLI mode tests write extension-less `#!/bin/sh` stubs and join PATH with
':', which cmd.exe cannot resolve; the Windows lane collects that file and
downgrades its failure to a warning, so it would have carried a permanently
red block. The suite is excluded on win32 alongside the other bash-fixture
suites.
The `test_build`/`test` intersection grew to 16 with the disk collector, but
the floor stayed at 15, leaving exactly one shared step uncompared; the floor
now matches the membership. The cache-hit-with-changes branch — the code
that decides what is rebuilt and what is deleted — gains a case: a changed
workspace is purged and rebuilt by directory, and an untouched workspace
keeps what the cache restored.
ci.yml's recorded size baseline is updated to the current file so the next
PR gets the full growth allowance back.
Co-authored-by: Qwen-Coder <[email protected]>
* test(ci): keep cache fixture call logs outside the archived tree
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 易良 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
packages/cli compiles against ink frame-controller types that only
patches/ink+7.0.3.patch adds; pristine [email protected] exports none of them. That
patch reaches node_modules through the root postinstall, so an install that
skipped lifecycle scripts (--ignore-scripts, or ignore-scripts=true in the
user's npm/pnpm config) leaves pristine ink in place and the build fails with
~50 errors that all blame ink -- which sends a reporter to compare ink
versions on npm instead of to the missing patch. Because noEmitOnError is
unset, tsc still emitted a dist that runs with text selection broken.
scripts/build.js already heals a missing node_modules; heal a missing patch
the same way. frame-controller.d.ts is created by that patch and absent from
pristine [email protected], so its absence is the signal. If re-applying still does
not produce it, name the patch rather than letting tsc point at ink.
Fixes#14110
Co-authored-by: Qwen-Coder <[email protected]>
* refactor(release): Use pnpm for workspace publishing and versioning
* fix(ci): revert desktop-release install to npm ci for Windows compatibility
The pnpm migration added a bash conditional to check for pnpm-lock.yaml,
but the step did not specify shell: 'bash'. Windows runners default to
PowerShell, which cannot parse bash syntax, causing the build to fail
with a ParserError.
Since desktop-release always checks out the same commit and the root
lockfile is now pnpm-lock.yaml, the conditional is unnecessary. Revert
to the simple npm ci command that works on all platforms.
Fixes the Windows build failure in Desktop release v0.24.2.
* refactor(build): Schedule workspace builds with pnpm
* fix(ci): Preserve Windows release installation and version filters
---------
Co-authored-by: Qwen-Coder <[email protected]>
* ci(pnpm): install dependencies with pnpm in CI and release
CI tests the graph release ships only if both install it the same way, so
this moves both, keeping every `npm run` script and `npm publish` as they are.
- ci.yml (7), release.yml (3) and release-vscode-companion.yml (2) install
with `corepack pnpm install --frozen-lockfile`; release keeps
--ignore-scripts plus its explicit postinstall and generate steps.
- setup-node drops the npm cache and sets package-manager-cache: false,
which setup-node v5+ needs once package.json declares a pnpm
packageManager.
- A composite action caches the pnpm store on the three always-hosted jobs;
the ECS pool keeps its store on local disk.
- version.js no longer lets npm reify node_modules: --no-workspaces-update on
both `npm version` calls, and a package-lock-only refresh in step 9.
- The notices generator, prepare-package's sharp pin and the standalone
release's native package specs read the installed tree or pnpm-lock.yaml
instead of package-lock.json keys.
- New size baselines for the three workflows, which were already over them.
* chore(vscode): regenerate NOTICES from the pnpm-installed tree
Generated in CI (pnpm Worktree Smoke on ubuntu-latest) by the ported
generator. Same entry set as before except the five packages npm and pnpm
resolve differently: fdir 6.5.0, picomatch 4.0.5, mdurl 2.1.0,
@types/node 22.20.1 and mime-db 1.52.0 (form-data's pinned copy). No entry
lacks a license text or repository.
* fix(pnpm): resolve undeclared zod peers to the repo's zod, as npm does
The first CI run on this branch failed the export renderer's size budget:
1,930,015 bytes against 1,930,000, where the same commit built on npm's
tree comes to 1,858,186. Comparing both trees' esbuild metafiles and
prebuilt bundles put the whole difference in web-shell's transcript.js
(+100,903 bytes pre-minify), and the added code is zod 4 plus the
@modelcontextprotocol/ext-apps schemas; the sdk daemon bundle is identical.
web-shell bundles ext-apps, whose zod and MCP SDK are peers, and declares
no zod itself, so pnpm filled the peer with the highest locked zod (4.4.3)
while npm serves the hoisted 3.25.76. Declaring zod 3.25.76 as a root
devDependency makes pnpm resolve every such peer to it
(resolve-peers-from-workspace-root is on by default), which is npm's
hoisting behaviour. mobile-mcp keeps its own zod 4.4.3, as under npm; the
npm tree does not change.
* fix(pnpm): keep npm's root @types/node so root-level typechecks match
The no-AK integration gate typechecks integration-tests/, which takes
Node's types from the root node_modules. npm hoists @types/node 20.19.1
there, because acp-bridge and core pin it; pnpm, with no root declaration,
hoisted 22.20.1, whose spawnSync overloads type process-registry.ts's
stdout as string | NonSharedBuffer and fail TS2322. The same code passes on
every npm-installed PR.
Declaring 20.19.1 as a root devDependency puts npm's copy back where a
root-level tsconfig looks. The npm tree does not change.
* ci(pnpm): install with pnpm in the remaining workflows
The follow-up to switching CI and release: every other workflow that
installs the root workspace now uses the pinned pnpm with
--frozen-lockfile, so no job tests a graph that release does not ship.
- e2e, tui-parity, repo-hygiene, web-shell-visuals, serve-ab, sdk-java,
windows-runner-smoke, qwen-autofix, the SDK releases, finalize-release,
sync-release-to-oss, the root install in desktop-release and
cd-cua-driver, and the sandbox Dockerfile.
- setup-node drops the root npm cache (package-manager-cache: false); hosted
jobs restore the pnpm store through the shared composite action, and
qwen-autofix keeps af-012's rule that the persistent pool restores no
remote cache.
- serve-ab and web-shell-visuals install a separate base checkout that can
predate pnpm-lock.yaml, so those installs fall back to npm ci there.
- Out of scope, unchanged: packages with their own lockfile (cua-driver's
TypeScript SDK, desktop-shell, live-host, mobile-mcp), and the triage
lanes with npm-cache.yml and the npm audit gate, which move with the
package-lock.json retirement.
- New size baselines for the touched workflows; qwen-autofix stays under
the 470000-byte gate.
* fix(pnpm): link the workspace packages that root-level code imports
npm links every workspace package into the root node_modules, so
integration-tests/ and scripts/, which are not workspace packages
themselves, can import @qwen-code/* by name. pnpm links a workspace
package only where it is a declared dependency, and the root declared
none, so the no-AK integration gate could not find
@qwen-code/qwen-code-core.
The root now declares the seven packages that root-level code imports at
runtime as file: devDependencies: acp-bridge, channel-base, the CLI,
core, sdk, web-shell and web-templates. npm already links them, so its
tree does not change (letting npm re-resolve the lock reproduces the
same root entry); .pnpmfile.mjs rewrites them to workspace:*, which pnpm
links at the root.
* ci(pnpm): move triage, the store producer and the root audit to pnpm
- qwen-triage's verify and tmux-testing lanes install the PR with
`corepack pnpm install --frozen-lockfile` from a restored pnpm store.
The one retry clears node_modules first, because pnpm install, unlike
npm ci, keeps it.
- npm-cache.yml becomes pnpm-store.yml, keyed on pnpm-lock.yaml.
- security-checks audits the root workspace with `pnpm audit`, which reads
the lockfile, so the root install step goes. The vendored lockfiles keep
npm, and the retry recognises pnpm's endpoint error too.
- qwen-autofix drops the hosted-only store cache: its heavy jobs forbid
local `uses: './...'` actions, and the file sits at the size gate.
- cd-cua-driver: setup-node@v4 has no package-manager-cache input.
- package-assets fixtures install sharp rather than listing it in
package-lock.json, matching how prepare-package now resolves it.
- AGENTS.md, CONTRIBUTING.md and the npm workspace guide install with pnpm.
* feat(review): install pnpm repos in qwen review's build/test
qwen review installed dependencies only for a repo with package-lock.json
and reported a pnpm repo as unsupported, so reviews of qwen-code would
lose their build and test once its npm lockfile goes.
- lockfileInstaller() picks npm or pnpm from the committed lockfile. With
both, `packageManager: pnpm@...` chooses pnpm; anything else keeps npm.
- A pnpm repo installs with `corepack pnpm install --frozen-lockfile`
through the same disk, budget and sandbox path as `npm ci`, and counts
as installed once node_modules/.modules.yaml exists.
- Scripts still run through `npm run`, and the npm path is unchanged.
* ci(pnpm): retire the root package-lock.json
pnpm-lock.yaml is now the only root lockfile.
- check-lockfile keeps the pnpm integrity check and Playwright parity,
which now reads pnpm importers and snapshots. The npm-vs-pnpm agreement
and build-approval checks go: pnpm 11's strictDepBuilds and every CI
install's --frozen-lockfile enforce what they covered.
- pnpm-lock-freshness.yml goes; it regenerated pnpm-lock.yaml from
package-lock.json.
- Release: version.js drops its package-lock refresh, the release commit
stages pnpm-lock.yaml and the SDK release stages no lockfile, so neither
`git add` fails on the missing file. `npm version` in the SDK and
mobile-mcp releases passes --no-workspaces-update so it cannot reinstall
the root with npm.
- cd-mobile-mcp installs from the root pnpm lockfile. setup-node in
cd-mobile-mcp, qwen-code-pr-review and desktop-release no longer keys an
npm cache on the root lockfile.
- check-desktop-isolation reads pnpm importers; build.js, build_sandbox.js
and preflight install with pnpm.
- pnpm-lock.yaml, pnpm-workspace.yaml and .pnpmfile.mjs join the autofix
supply-chain class and repo-hygiene's deny list; pnpm-lock.yaml joins
autofix's generated-diff exclusions, sdk-java's path filter and the
platform-sensitivity manifests.
- .gitignore lists /package-lock.json so an npm install cannot commit it
back. Tests and docs follow.
* fix(standalone): read the node-pty versions from the pnpm lockfile
* chore(vscode-ide-companion): regenerate NOTICES.txt after the lockfile swap
* chore(vscode-ide-companion): regenerate NOTICES.txt from the pnpm dependency tree
The committed NOTICES.txt was generated from an npm install and does not
match the tree produced by the pnpm install the release pipeline now uses
(659 resolved dependencies, differing @types/node and mime-db versions).
Regenerating with the pinned pnpm install makes the freshness check
reproducible.
* fix(ci): drop the npm cache from the daily dependency audit
actions/setup-node's npm cache keys off the root package-lock.json, which this branch retires, so the scheduled job would fail at Set up Node before the audit ran. No pull_request run reaches this workflow to catch it. The root tree is never installed here either: pnpm audit reads pnpm-lock.yaml directly.
Matches the sibling workflows that already set package-manager-cache: false; scripts/tests/security-workflows.test.js now pins it.
* chore(ci): stop banking main-side drift in the workflow size ratchet
The ratchet exists to turn a workflow's growth into one reviewed line. This branch re-recorded entries for 17 workflows it never touches, several upward by 0.4-2.8 KB - drift that happened on main, banked into the manifest without review.
Restore those to their merge-base values, so .size-baseline changes only for the 22 workflows this branch actually edits. The entries were not needed to go green: ci.yml passes the PR's base commit, so a file that drifted on main and is otherwise untouched earns a warning, not a failure.
* fix(release): initialize standalone state before main
* test(browser-use): read Playwright pin from pnpm lock
* fix(ci): address pnpm migration review blockers
* fix(desktop): stop reading the retired root lockfile
---------
Co-authored-by: Qwen-Coder <[email protected]>
* feat(browser-use): add Playwright browser SDK
* docs(browser-use): document browser use architecture
* fix(browser-use): make browser input actions reliable
* feat(browser-use): preserve screenshot coordinate metadata
* fix(browser-use): recover stale sockets across VM realms
* fix(browser-use): bound locator action retries
* fix(browser-use): keep page input in the background
* fix(browser-use): reject ambiguous input arguments
* fix(browser-use): validate locator composition identity
* fix(browser-use): recover socket locks across VM realms
* fix(browser-use): preserve input results across navigation
* fix(browser-use): capture screenshots through bounded CDP frames
* fix(browser-use): separate input and navigation waits
* feat(browser-use): add Chrome native relay
* fix(chrome-extension): avoid foreground tabs and stale cursor markup
* fix(chrome-extension): require Chrome 125 for flat sessions
* feat(browser-use): add product integration
* test(browser-use): add managed Chrome smoke coverage
* feat(node-repl): expose structured image metadata
* test(browser-use): preserve complete smoke reports
* feat(browser-use): bundle skill and runtime with CLI
* fix(browser-use): install pinned Playwright in fresh workspaces
* feat(browser-use): require explicit skill opt-in
* feat(browser-use): make bundled skill available by default
Keep explicit skill disables authoritative, update documentation and tests, and use the latest Node REPL package in setup instructions.
* fix(ci): build browser-use before Live Host publish
Build the bundled browser runtime before core in the Live Host npm dependency chain, and cover that prerequisite order with a regression test.
* fix(browser-use): output screenshot metadata explicitly
* fix(node-repl): preserve image metadata outside prose budget
* fix(browser-use): address review round on workspace wiring and runtime correctness
- register the workspace in .pnpmfile.mjs, pnpm-lock.yaml, and the
unit-vitest-configs registry, with the shared-pool timeout ternary and
off-Linux unhandled-error exemption (fixes the red Install/Test checks)
- map Playwright's 'warning' console type to the contract's 'warn' level
- reject captures whose pixel dimensions contradict the css-pixels
coordinate contract instead of certifying rescaled images
- keep one unattachable derived tab from failing tabs.list while still
propagating a lost session
- clear the cached dialog when Chrome resolves it out of band or the page
navigates, guarded by dialog identity so a newer dialog survives
- synthesize a parseable Browser.getVersion (numeric Chrome major, host
platform token) so Playwright enables the right keyboard editing commands
- keep YAML-quoted snapshot keys and link props in interactive listings and
stop claiming subtrees that filtering removed
- always release the mouse button when a drag gesture fails
* fix(dev): build browser-use runtime before startup
* fix(browser-use): isolate cleanup and correct smoke checks
* fix(browser-use): resolve managed Chrome through Playwright
* fix(browser-use): harden native relay and tab lifecycle
* fix(browser-use): drain host output and persist restored tab state
* fix(browser-use): scope dialog handles and clean navigation waiters
* fix(browser-use): preserve input outcomes and release modifiers
* fix(browser-use): drain session teardown and release debugger attachments
* fix(browser-use): correct locator validation and evaluation
* fix(dev): reuse prebuilt Browser Use runtime
* fix(browser-use): address review round on locator, bridge, and screenshot correctness
Co-authored-by: Qwen-Coder <[email protected]>
* fix(browser-use): require installed extension before native host setup
* fix(browser-use): address review round on schema probe bound and regex validation
* fix(browser-use): start transport before Chrome preflight
* fix(browser-use): exclude staged runtime from code checks
* fix(core): declare Browser Use build dependency
* fix(browser-use): preserve successful navigation and dialog input
* fix(browser-use): harden input drain and tab registration cleanup
* fix(browser-use): keep sessions bound to one Chrome profile
* fix(browser-use): bound commands and validate evaluation JSON
* fix(browser-use): reuse unchanged Native Host registration
* fix(browser-use): wait for fresh extension installation
* fix(browser-use): address review round on screenshot origin, dialog scope, and bridge privacy
- screenshot: tolerate settle-probe failure (measure the ratio from the
captured pixels, re-capture on HiDPI), measure layout after the settle
wait, and reject screencast frames whose scroll offsets disagree with
the published origin
- session: clear the cached dialog only on main-frame navigation;
abort tab attachment when the tab is removed mid-attach
- errors: classify crashes and timeouts by Playwright's structured error
name instead of page-influenced message text
- locator.press: release chord modifiers when a later token is rejected;
cap locator.type at the 60k characters its per-character budget can
deliver inside the 120s ceiling
- snapshot: keep AI-mode [cursor=pointer] generic nodes in the
interactive listing
- bridge: derive the fallback socket directory as an env-independent
per-user 0700 subdirectory on all POSIX hosts and verify ownership
before binding
* fix(browser-use): close review-critical gaps in error mapping, budgets, and downloads
- errors: classify by Playwright error name first; text phrases match only
the start of the first message line so page-controlled text (log tails,
quoted markup, page-thrown values) cannot pick the reported code, and a
TimeoutError name wins over crash-shaped page text
- transport: cdp.send bridge requests default to 130s so operations up to
the 120s schema ceiling report their own deadline; other requests keep
the 30s default
- transport: the /tmp fallback socket directory is a per-user leaf directly
under the sticky root (no shared intermediate a first mover could own);
ensureSocketDirectory re-verifies the leaf after creation and walks
ancestors up to the sticky root, requiring each to be owned by this user
or root and not group/other-writable
- runtime: withModifiers no longer rewrites a completed action into a
failure when a modifier release fails; chord failure cleanup releases the
chord's own tokens (including non-modifiers) instead of four fixed names
- playwright: enable CDP download events on tab attach (Playwright's
noDefaults connect leaves them off, so waitForEvent('download') could
never resolve); locator.downloadMedia races the caller deadline, aborts
the in-page fetch at it, resolves media contained in a located wrapper
before an ancestor link, restricts URL schemes, and names CORS rejections
distinctly; locator.allTextContents waits for the first match within the
caller budget and still resolves [] when nothing attaches
- screenshot: full-page captures get a 16 Mi-pixel budget (1920x3000 pages
now succeed) and the encoded byte ceiling drops to the 4 MiB model image
limit so captures are not dropped at the model boundary
- snapshot: interactiveOnly promotes only a terminal [cursor=pointer]
attribute (page text quoting the marker no longer promotes the line), and
truncation skips over-long lines instead of discarding the rest
- schemas: reject empty string/regex matchers and exact:true combined with
a regex matcher (Playwright silently drops exact for regexes)
- tests: the SDK evaluate fixture now mirrors production serialization;
POSIX socket tests carry win32 gates; posix.join keeps the derived socket
path a pure function of uid and platform on every host
* fix(browser-use): close review criticals in error mapping, chords, downloads, and snapshots
- errors: classify Playwright's genuine strict-mode violation, which
crosses CDP as the raw exception description and reaches the client
behind an "Error: " layer ("locator.click: Error: strict mode
violation: ... resolved to N elements:"); requiring the element count
keeps a page-thrown lookalike from forging LOCATOR_NOT_UNIQUE
- runtime-helpers: on a failed chord press, release the tokens
Playwright actually derived ('+' separates only after a non-empty
token, so a standalone '+' is a literal key) rather than the caller's
array elements; an element embedding '+' previously released nothing
and left modifiers held. locator.press uses the same tokenizer
- locator.downloadMedia: resolve an ordered candidate list (element,
media descendants, anchor descendants, closest ancestor) and keep the
first candidate that exposes a URL, so a wrapping anchor no longer
beats the image it contains and a source srcset or an unloaded
video's source child can supply the URL
- snapshot: unwrap Playwright's single-quoted YAML key before the
[cursor=pointer] suffix test, so clickable nodes whose accessible
name forces key quoting stay in the interactive listing
- docs: align the Input completion contract with the shipped modifier
cleanup semantics (cleanup failures are discarded; only the action's
own error propagates) in both languages
* fix(browser-use): close round-13 review criticals in errors, srcset, evaluateAll, snapshots, and screenshot origin
* fix(browser-use): point the pnpm importer at a vitest snapshot that exists
Merging main brought in #11625, which regenerated pnpm-lock.yaml and
dropped the [email protected] snapshot keyed with @vitest/browser and
[email protected]. The packages/browser-use importer still referenced
that key, so every Install leg failed with
ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY. Re-key the importer to the snapshot
its sibling packages already use; nothing else in the lockfile changes.
* fix(browser-use): close round-14 criticals in error classification, dialog ordering and screenshot ratio
R13-2: the strict-mode branch of sanitizeOperationError was the only
text-phrase branch not gated on the evaluate channel, so a page-thrown
primitive "strict mode violation: ... resolved to 2 elements:" picked
LOCATOR_NOT_UNIQUE. On that channel only Playwright's "Error: "-wrapped
form classifies now; other channels keep the unwrapped form.
R14-1: Playwright hands a dialog over on a later turn than the bridge
reports its CDP events (a microtask in CRSession plus the in-process
dispatcher's setImmediate), so an open+close pair delivered in one chunk
left a phantom dialog that blocked the tab. Each tab now traces dialog
openings and closes in bridge order and drops a delivered dialog the
bridge already reported closed; a close with no traced opening (a dialog
open before the tab was attached) is never charged to a later dialog, and
the microtask clear stays for the delivered case.
R14-2: window.devicePixelRatio is page script, and a spoofed value became
an unbounded clip.scale while the pixel re-measure only ran when the
probe failed. The probed ratio is now trusted only within 0.25..8, and the
measure-and-recapture correction runs whenever the first fallback capture
disagrees with the requested CSS region, deriving the real ratio from
Chrome's own pixels (measured / (width * scale)).
Also resolve the temp root in the ensureSocketDirectory tests: the
ancestor sweep rejects symlinks, and macOS reaches os.tmpdir() through
/var -> /private/var, so the tests failed locally on macOS.
* fix(browser-use): tear down accepted peers on start failure and pin the transport's untested paths
The esbuild banner declared require/__filename/__dirname/process bindings
the bundle never uses, so any bundled module declaring one of them built
green but failed to load; drop it (and the unused .wasm loader) and import
dist/index.js after bundling so an unloadable bundle fails the build.
When start() fails after listen (chmod, handshake), a peer validated in
between kept server.close() waiting forever; destroy and clear the
accepted sockets first, mirroring stop(). net.Server has no
closeAllConnections(), so that is the whole fix.
Tests now cover the QWEN_BROWSER_USE_SOCKET_PATH override, a hello with a
mismatched protocol version or extension id, onConnectionChange on the
real transport, an in-flight request when the extension disconnects and
the configured request budget, the ok:false error-code mapping,
FrameDecoder split-frame reassembly and its length ceiling, the
start-failure teardown, and all five schema refine predicates.
* fix(browser-use): mirror the contract bounds in the SDK and state the documented limits
nth() now rejects indexes outside the contract's -10000..10000 before
dispatch, and all() fails closed when the plan already has 32 steps or
the match count exceeds what nth() can address, instead of handing back
locators that only fail on first use. Both evaluate script builders
normalise method-shorthand and class-method sources the way Playwright
does (compile-only vm.Script probe, then a function prefix), so those
well-typed callbacks no longer die as a page-side SyntaxError.
providerTab clamps title and url to the claimTab schema's 20000-char cap
so the documented openTabs() -> claimTab() round trip survives long URLs,
and orderOpenTabs() establishes the http(s)-only, newest-first listing
the model documentation promises. downloadMedia derives the file name
from the URL path only for http(s) sources and leaves blob:/data: names
to the browser.
The model-facing documentation now states the 1s read default, that
dom_cua.scroll's x/y are wheel deltas rather than coordinates, and that
a cross-origin resource without CORS headers cannot be downloaded from
the page origin; the design docs record that boundary as follow-up work.
Tests pin every one of these, plus buildLocator's frame, combinator,
filter and positional branches, the file-chooser SDK surface, and the
claimTab argument guards.
* fix(browser-use): keep background tab registration from moving the selection
registerTab selected every tab it registered, and two of its callers are
background paths (derivedTabTracked, syncDerivedTabs via tabs.list), so
a read-only tabs.list could move tabs.selected onto a popup. Selection is
now set only by newTab and claimTab from the info they return.
Also: tabs.get is allowed while a dialog is open, matching tabs.list and
tabs.selected, which already return the dialog-safe TabInfo; the
auxiliary-button click moves Playwright's tracked cursor before sending
the CDP button events so a later wheel lands where the click did; the
dead providerTabId lookup is removed; openTabs applies orderOpenTabs.
Tests: the runtime test file mocks node:timers so vi.useFakeTimers()
actually controls the input drain bound (the 250ms test drops to ~0ms),
and new cases pin the drain clearTimeout, the registration probe's
session detach, promptText pass-through, tabs.get under a dialog, the
openTabs/claimTab fail-closed guards and ordering, popup adoption from
derivedTabTracked, the abandoned navigation waiter's swallowed rejection,
the uploadFiles path guards, and the screencast fallback and byte budget
on the unconstrained capture path.
* test(browser-use): pin the element bindings the runtime gives evaluate scripts
The SDK emits scripts that read the free variables `element` and
`elements`, and the runtime binds them when it compiles the script inside
the page; no test ran either page-side callback, so swapping the binding
name on one side kept the suite green while every locator.evaluate would
throw a ReferenceError in production. Run the real callbacks with fake
elements so the contract is pinned from both ends.
* fix(browser-use): fail closed on page-controlled strict-mode text and prefer contained media over anchor hrefs
* fix(browser-use): bound page title reads and download a located anchor's file over its icon
* fix(browser-use): correct media downloads and frame composition
* fix(browser-use): bound locator.count and allTextContents by the caller deadline
* fix(browser-use): preserve native snapshots for DOM CUA
Co-authored-by: Qwen-Coder <[email protected]>
* fix(browser-use): classify a closed tab from the tab's own state
The pinned playwright-core client renders a closed target as a plain Error:
only TimeoutError sets `name`, so the `name === 'TargetClosedError'` branch
in sanitizeOperationError never fired, and because evaluate-channel text
fails closed by design, a tab that closed or crashed while a page command
ran was reported as OPERATION_FAILED instead of the documented STALE_TAB.
Decide tab-gone in the dispatcher from `tab.stale` and `page.isClosed()`,
which the page observers keep current, before the text classifier runs.
Drop the dead name branch and replace the test that fabricated the name
with one built the way the client builds the error, plus dispatch-level
cases for both signals that fail without the dispatcher check.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* fix(browser-use): restore the kernel realm process binding and land the round-5 review batch
Criticals from review round 5, each reproduced before fixing:
- The bundled skill imports the staged runtime inside the node_repl kernel,
whose untrusted vm context has no `process` global and denies the
`node:process` specifier. 3fc2dc3e10 removed the bundle banner that bound
`process` through createRequire, so the skill's first cell threw
`ReferenceError: process is not defined`; the build's own load check runs
in the main realm and could not see it. Restore the binding on the index
build and add a kernel-backed test that runs SKILL.md's first cell through
the real kernel and fails on the ReferenceError (R5-4).
- Bump @qwen-code/node-repl-mcp to 0.1.6: this PR changes its published
source (image metadata channel) and the package is excluded from the
repo-wide bump, so the release lane's integrity check would fail. Pin the
browser-use skill to that version, have the skill test assert the pin
equals the package version, and extend the cua-driver release gate to
cross-check the browser-use pin (R5-2, R3-5).
- Report an incompatible extension as EXTENSION_VERSION_MISMATCH so
browser discovery surfaces the update guidance instead of an empty list
after the connect budget (R5-5).
- Make tab grouping non-fatal in tabs.create, matching its siblings, so a
cosmetic grouping failure no longer closes the tab just created (R5-6).
Review suggestions verified still applying, with tests proven red under
mutation: typecheck the scripts directory; pin the Native Messaging chunk
boundary and envelope; return installedPaths from the installer; treat a
blank install-home override as unset; warn on a skipped foreign manifest;
refuse a foreign launcher with the refusals' missing red arms; keep the
preflight download waiter handled; settle the parked-profile test; name
the private-directory cause in the bridge start error; declare the finalize
status union once; reject unknown or closed kept tabs; pin the extension's
protocol constants to the SDK source; resolve the extension test root from
the module; drop the duplicated permission assertion; make the group
barrier real; read the overlay style rules; map a vanished tab to STALE_TAB
in the relay; clamp listed tab text to the schema bound; remove the
unreachable onDetach child-session branch; assert the raced tab in the
disconnect test; cover the history scheme filter and session-name reset;
and fix the extension-source and prerequisite wording in the docs.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* test(browser-use): let the SauceDemo smoke recognize equivalent skill usage
The model-driven smoke completed the task correctly on every run but its
transcript checks asserted one exact spelling: the literal runtime entry
path in the model's code, and one parent-scoped price selector with an
exact number of dollar values in the cell's output. A model that builds
the entry from the skill root across cells, scopes the price locator
differently, or echoes its chosen items after the read failed the smoke.
Key the import check on what every spelling shares: the built-in skill
root the CLI substitutes into SKILL.md, the entry file name and the setup
call. Match price reads on the price class, prefer a read that printed
exactly the expected count, take the leading set otherwise, and take the
last such read for the cart since the flow reads it after the inventory.
The smoke-checks test covers all three import spellings, a foreign runtime
and a missing setup call, and the parser's scoped, echoed and non-list
reads. Verified against a real Chromium 151 run: all six checks true.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* fix(browser-use): close six fail-open paths in the playwright adapter
Round-22 review found six Critical defects in the new package; each is
fixed at its root and pinned by a test that goes red without the fix:
- locator.evaluateAll opened a second full timeout window after the
attach wait had consumed the caller's budget; the wait and the read
now share one deadline, and a wait that consumed the budget settles
[] without evaluating.
- tab.goto passed any string to page.goto, so a file:// URL would have
handed local file contents to the tab's evaluate and snapshot reads;
goto is gated to http(s) before the navigation runs.
- Synthesized CDP error responses carried no code, so a reply orphaned
by a target crash tripped Playwright's internal assert and tore down
the whole transport; they now carry -32001, the orphan-swallow code.
- A dialog already open when a tab attaches is replayed by neither
Chrome nor Playwright, so the DIALOG_OPEN gate stayed blind while the
modal blocked the renderer; registration now probes the renderer and
gates the tab on an unanswered probe, with getJsDialog reporting it
under a stable handle whose accept/dismiss run over CDP.
- A dialog opening Playwright never delivered stayed in the trace
forever and swallowed the charge of every later dialog on the tab; a
closed, undelivered entry is retired once the dispatcher turn has
passed.
- snapshotRefLocator validated only the ref's shape, so a ref from a
pre-navigation snapshot could act on whichever element the new
document happened to hand the same string; refs are bound to the
snapshot that emitted them and cleared on main-frame navigation.
Co-Authored-By: Qwen-Coder <[email protected]>
* build: exempt the staged Browser Use skill runtime from the dependency-direction check
The browser-use package build stages the bundled skill's runtime, node_modules
included, under packages/core/src/skills/bundled/browser-use/runtime (git-ignored),
and the TUI dependency-direction gate fails on any node_modules inside a protected
root. Declare that staged, ignored root as a build artifact so the gate skips it
without a diagnostic; every other skipped-directory name still fails.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MWe8PKNMpsKdQruTWkvFFc
* build: leave the staged Browser Use runtime out of the dependency-direction walk entirely
The staged root is a build artifact, not source: skipping only its
node_modules while still parsing the SDK bundle next to it was inconsistent.
Do not walk anything under a declared staged root; every other node_modules
inside the protected roots remains a diagnostic.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MWe8PKNMpsKdQruTWkvFFc
* build(browser-use): stage the skill runtime only for the bundle and for dev mode
The package build used to copy the bundled skill runtime, node_modules
included, into packages/core/src, which every built tree then carried and
which the TUI dependency-direction gate rightly rejects. Follow the qc-helper
convention instead: the bundle step stages the runtime into dist/bundled for
the shipped CLI, and `npm run dev` stages the git-ignored development copy
next to the source SKILL.md, because only dev mode reads bundled skills from
the source tree. No build step writes into src any more, so the gate
exemption added earlier is dropped and the check script returns to main's
version. The kernel-realm test stages its own copy into a temporary skill
directory rather than depending on a build side effect.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MWe8PKNMpsKdQruTWkvFFc
* fix(browser-use): deliver bridge messages in arrival order and keep dev info flags fast
Three fixes from the round-3/4 verification and review round 7–8:
- Transport: a response only settles a promise, so its consumer ran on the
microtask queue while events from the same socket chunk were emitted
synchronously and overtook it. Playwright installs a page's renderer and
lifecycle listeners inside `Page.getFrameTree().then(...)`, so an
overtaking `Runtime.executionContextCreated` found no listener and a
claimed tab lost its main world for good (B1). Inbound messages now go
through one per-socket queue whose drain yields a macrotask after
settling a response, so every continuation runs before the next message;
chunks arriving meanwhile join the same queue. Regression:
`delivers a response ahead of the events that share its socket chunk`.
- Relay: `requireControllableTab` judged a popup by `tab.url`, which is
empty until the navigation commits, while the claim keyed on
`pendingUrl`; the runtime's immediate `tabs.get` therefore rejected the
tab the relay had just reported (R8-2). It now judges by
`pendingUrl || url`, like the claim. Regression:
`a popup known only by its pending URL stays controllable`.
- dev launcher: the dev-mode runtime staging skips `--version`/`--help`
(and `-v`/`-h`), restoring the fast path the existing tests pin (R7-1).
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MWe8PKNMpsKdQruTWkvFFc
* test(browser-use): make the smoke evidence and the persist-before-connect pin honest
Round 6–7 review findings on the verification tooling:
- The SauceDemo smoke decided "the staged runtime was loaded" from three
substring tests over all cells joined, so a run whose staged import threw
and fell back to a foreign entry still passed (R6-1). It now looks at the
import expressions per cell: a literal path under the staged runtime, or a
path assembled from the substituted skill root, in a cell that reaches the
setup export; a literal entry loaded from anywhere else disqualifies the
run.
- Price reads were attributed to the cart by count and read order, so an
inventory sorted low-to-high passed as a cart read and the fallback to the
first read never returned null (R6-2). Reads are now attributed by the
tab.url() confirmation of cart.html the prompt requires: inventory before
it, cart after it, and no cart read without it.
- The persist-before-connect invariant was asserted inside the mock's
postMessage, which the bridge calls under a bare catch, so the reordered
mutant stayed green (R7-2). The mock now records every hello with the
identity persisted at that moment and the test asserts the order outside
the bridge; the mutant is red.
- SKILL.md states the node-repl-mcp 0.1.6 requirement next to the
emitImage step the agent always reads, with how to detect and re-register
an older server (R6-3).
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MWe8PKNMpsKdQruTWkvFFc
---------
Co-authored-by: qwen-code-dev-bot <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Qwen-Coder <[email protected]>
Co-authored-by: qwen-code-dev-bot <[email protected]>
Co-authored-by: Shaojin Wen <[email protected]>
Co-authored-by: qwen-code-ci-bot <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
* feat(browser-use): add Playwright browser SDK
* docs(browser-use): document browser use architecture
* fix(browser-use): make browser input actions reliable
* feat(browser-use): preserve screenshot coordinate metadata
* fix(browser-use): recover stale sockets across VM realms
* fix(browser-use): bound locator action retries
* fix(browser-use): keep page input in the background
* fix(browser-use): reject ambiguous input arguments
* fix(browser-use): validate locator composition identity
* fix(browser-use): recover socket locks across VM realms
* fix(browser-use): preserve input results across navigation
* fix(browser-use): capture screenshots through bounded CDP frames
* fix(browser-use): separate input and navigation waits
* fix(browser-use): address review round on workspace wiring and runtime correctness
- register the workspace in .pnpmfile.mjs, pnpm-lock.yaml, and the
unit-vitest-configs registry, with the shared-pool timeout ternary and
off-Linux unhandled-error exemption (fixes the red Install/Test checks)
- map Playwright's 'warning' console type to the contract's 'warn' level
- reject captures whose pixel dimensions contradict the css-pixels
coordinate contract instead of certifying rescaled images
- keep one unattachable derived tab from failing tabs.list while still
propagating a lost session
- clear the cached dialog when Chrome resolves it out of band or the page
navigates, guarded by dialog identity so a newer dialog survives
- synthesize a parseable Browser.getVersion (numeric Chrome major, host
platform token) so Playwright enables the right keyboard editing commands
- keep YAML-quoted snapshot keys and link props in interactive listings and
stop claiming subtrees that filtering removed
- always release the mouse button when a drag gesture fails
* fix(browser-use): scope dialog handles and clean navigation waiters
* fix(browser-use): preserve input outcomes and release modifiers
* fix(browser-use): drain session teardown and release debugger attachments
* fix(browser-use): correct locator validation and evaluation
* fix(browser-use): address review round on locator, bridge, and screenshot correctness
Co-authored-by: Qwen-Coder <[email protected]>
* fix(browser-use): address review round on schema probe bound and regex validation
* fix(browser-use): preserve successful navigation and dialog input
* fix(browser-use): harden input drain and tab registration cleanup
* fix(browser-use): bound commands and validate evaluation JSON
* fix(browser-use): address review round on screenshot origin, dialog scope, and bridge privacy
- screenshot: tolerate settle-probe failure (measure the ratio from the
captured pixels, re-capture on HiDPI), measure layout after the settle
wait, and reject screencast frames whose scroll offsets disagree with
the published origin
- session: clear the cached dialog only on main-frame navigation;
abort tab attachment when the tab is removed mid-attach
- errors: classify crashes and timeouts by Playwright's structured error
name instead of page-influenced message text
- locator.press: release chord modifiers when a later token is rejected;
cap locator.type at the 60k characters its per-character budget can
deliver inside the 120s ceiling
- snapshot: keep AI-mode [cursor=pointer] generic nodes in the
interactive listing
- bridge: derive the fallback socket directory as an env-independent
per-user 0700 subdirectory on all POSIX hosts and verify ownership
before binding
* fix(browser-use): close review-critical gaps in error mapping, budgets, and downloads
- errors: classify by Playwright error name first; text phrases match only
the start of the first message line so page-controlled text (log tails,
quoted markup, page-thrown values) cannot pick the reported code, and a
TimeoutError name wins over crash-shaped page text
- transport: cdp.send bridge requests default to 130s so operations up to
the 120s schema ceiling report their own deadline; other requests keep
the 30s default
- transport: the /tmp fallback socket directory is a per-user leaf directly
under the sticky root (no shared intermediate a first mover could own);
ensureSocketDirectory re-verifies the leaf after creation and walks
ancestors up to the sticky root, requiring each to be owned by this user
or root and not group/other-writable
- runtime: withModifiers no longer rewrites a completed action into a
failure when a modifier release fails; chord failure cleanup releases the
chord's own tokens (including non-modifiers) instead of four fixed names
- playwright: enable CDP download events on tab attach (Playwright's
noDefaults connect leaves them off, so waitForEvent('download') could
never resolve); locator.downloadMedia races the caller deadline, aborts
the in-page fetch at it, resolves media contained in a located wrapper
before an ancestor link, restricts URL schemes, and names CORS rejections
distinctly; locator.allTextContents waits for the first match within the
caller budget and still resolves [] when nothing attaches
- screenshot: full-page captures get a 16 Mi-pixel budget (1920x3000 pages
now succeed) and the encoded byte ceiling drops to the 4 MiB model image
limit so captures are not dropped at the model boundary
- snapshot: interactiveOnly promotes only a terminal [cursor=pointer]
attribute (page text quoting the marker no longer promotes the line), and
truncation skips over-long lines instead of discarding the rest
- schemas: reject empty string/regex matchers and exact:true combined with
a regex matcher (Playwright silently drops exact for regexes)
- tests: the SDK evaluate fixture now mirrors production serialization;
POSIX socket tests carry win32 gates; posix.join keeps the derived socket
path a pure function of uid and platform on every host
* fix(browser-use): close review criticals in error mapping, chords, downloads, and snapshots
- errors: classify Playwright's genuine strict-mode violation, which
crosses CDP as the raw exception description and reaches the client
behind an "Error: " layer ("locator.click: Error: strict mode
violation: ... resolved to N elements:"); requiring the element count
keeps a page-thrown lookalike from forging LOCATOR_NOT_UNIQUE
- runtime-helpers: on a failed chord press, release the tokens
Playwright actually derived ('+' separates only after a non-empty
token, so a standalone '+' is a literal key) rather than the caller's
array elements; an element embedding '+' previously released nothing
and left modifiers held. locator.press uses the same tokenizer
- locator.downloadMedia: resolve an ordered candidate list (element,
media descendants, anchor descendants, closest ancestor) and keep the
first candidate that exposes a URL, so a wrapping anchor no longer
beats the image it contains and a source srcset or an unloaded
video's source child can supply the URL
- snapshot: unwrap Playwright's single-quoted YAML key before the
[cursor=pointer] suffix test, so clickable nodes whose accessible
name forces key quoting stay in the interactive listing
- docs: align the Input completion contract with the shipped modifier
cleanup semantics (cleanup failures are discarded; only the action's
own error propagates) in both languages
* fix(browser-use): close round-13 review criticals in errors, srcset, evaluateAll, snapshots, and screenshot origin
* fix(browser-use): point the pnpm importer at a vitest snapshot that exists
Merging main brought in #11625, which regenerated pnpm-lock.yaml and
dropped the [email protected] snapshot keyed with @vitest/browser and
[email protected]. The packages/browser-use importer still referenced
that key, so every Install leg failed with
ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY. Re-key the importer to the snapshot
its sibling packages already use; nothing else in the lockfile changes.
* fix(browser-use): close round-14 criticals in error classification, dialog ordering and screenshot ratio
R13-2: the strict-mode branch of sanitizeOperationError was the only
text-phrase branch not gated on the evaluate channel, so a page-thrown
primitive "strict mode violation: ... resolved to 2 elements:" picked
LOCATOR_NOT_UNIQUE. On that channel only Playwright's "Error: "-wrapped
form classifies now; other channels keep the unwrapped form.
R14-1: Playwright hands a dialog over on a later turn than the bridge
reports its CDP events (a microtask in CRSession plus the in-process
dispatcher's setImmediate), so an open+close pair delivered in one chunk
left a phantom dialog that blocked the tab. Each tab now traces dialog
openings and closes in bridge order and drops a delivered dialog the
bridge already reported closed; a close with no traced opening (a dialog
open before the tab was attached) is never charged to a later dialog, and
the microtask clear stays for the delivered case.
R14-2: window.devicePixelRatio is page script, and a spoofed value became
an unbounded clip.scale while the pixel re-measure only ran when the
probe failed. The probed ratio is now trusted only within 0.25..8, and the
measure-and-recapture correction runs whenever the first fallback capture
disagrees with the requested CSS region, deriving the real ratio from
Chrome's own pixels (measured / (width * scale)).
Also resolve the temp root in the ensureSocketDirectory tests: the
ancestor sweep rejects symlinks, and macOS reaches os.tmpdir() through
/var -> /private/var, so the tests failed locally on macOS.
* fix(browser-use): tear down accepted peers on start failure and pin the transport's untested paths
The esbuild banner declared require/__filename/__dirname/process bindings
the bundle never uses, so any bundled module declaring one of them built
green but failed to load; drop it (and the unused .wasm loader) and import
dist/index.js after bundling so an unloadable bundle fails the build.
When start() fails after listen (chmod, handshake), a peer validated in
between kept server.close() waiting forever; destroy and clear the
accepted sockets first, mirroring stop(). net.Server has no
closeAllConnections(), so that is the whole fix.
Tests now cover the QWEN_BROWSER_USE_SOCKET_PATH override, a hello with a
mismatched protocol version or extension id, onConnectionChange on the
real transport, an in-flight request when the extension disconnects and
the configured request budget, the ok:false error-code mapping,
FrameDecoder split-frame reassembly and its length ceiling, the
start-failure teardown, and all five schema refine predicates.
* fix(browser-use): mirror the contract bounds in the SDK and state the documented limits
nth() now rejects indexes outside the contract's -10000..10000 before
dispatch, and all() fails closed when the plan already has 32 steps or
the match count exceeds what nth() can address, instead of handing back
locators that only fail on first use. Both evaluate script builders
normalise method-shorthand and class-method sources the way Playwright
does (compile-only vm.Script probe, then a function prefix), so those
well-typed callbacks no longer die as a page-side SyntaxError.
providerTab clamps title and url to the claimTab schema's 20000-char cap
so the documented openTabs() -> claimTab() round trip survives long URLs,
and orderOpenTabs() establishes the http(s)-only, newest-first listing
the model documentation promises. downloadMedia derives the file name
from the URL path only for http(s) sources and leaves blob:/data: names
to the browser.
The model-facing documentation now states the 1s read default, that
dom_cua.scroll's x/y are wheel deltas rather than coordinates, and that
a cross-origin resource without CORS headers cannot be downloaded from
the page origin; the design docs record that boundary as follow-up work.
Tests pin every one of these, plus buildLocator's frame, combinator,
filter and positional branches, the file-chooser SDK surface, and the
claimTab argument guards.
* fix(browser-use): keep background tab registration from moving the selection
registerTab selected every tab it registered, and two of its callers are
background paths (derivedTabTracked, syncDerivedTabs via tabs.list), so
a read-only tabs.list could move tabs.selected onto a popup. Selection is
now set only by newTab and claimTab from the info they return.
Also: tabs.get is allowed while a dialog is open, matching tabs.list and
tabs.selected, which already return the dialog-safe TabInfo; the
auxiliary-button click moves Playwright's tracked cursor before sending
the CDP button events so a later wheel lands where the click did; the
dead providerTabId lookup is removed; openTabs applies orderOpenTabs.
Tests: the runtime test file mocks node:timers so vi.useFakeTimers()
actually controls the input drain bound (the 250ms test drops to ~0ms),
and new cases pin the drain clearTimeout, the registration probe's
session detach, promptText pass-through, tabs.get under a dialog, the
openTabs/claimTab fail-closed guards and ordering, popup adoption from
derivedTabTracked, the abandoned navigation waiter's swallowed rejection,
the uploadFiles path guards, and the screencast fallback and byte budget
on the unconstrained capture path.
* test(browser-use): pin the element bindings the runtime gives evaluate scripts
The SDK emits scripts that read the free variables `element` and
`elements`, and the runtime binds them when it compiles the script inside
the page; no test ran either page-side callback, so swapping the binding
name on one side kept the suite green while every locator.evaluate would
throw a ReferenceError in production. Run the real callbacks with fake
elements so the contract is pinned from both ends.
* fix(browser-use): fail closed on page-controlled strict-mode text and prefer contained media over anchor hrefs
* fix(browser-use): bound page title reads and download a located anchor's file over its icon
* fix(browser-use): correct media downloads and frame composition
* fix(browser-use): bound locator.count and allTextContents by the caller deadline
* fix(browser-use): preserve native snapshots for DOM CUA
Co-authored-by: Qwen-Coder <[email protected]>
* fix(browser-use): classify a closed tab from the tab's own state
The pinned playwright-core client renders a closed target as a plain Error:
only TimeoutError sets `name`, so the `name === 'TargetClosedError'` branch
in sanitizeOperationError never fired, and because evaluate-channel text
fails closed by design, a tab that closed or crashed while a page command
ran was reported as OPERATION_FAILED instead of the documented STALE_TAB.
Decide tab-gone in the dispatcher from `tab.stale` and `page.isClosed()`,
which the page observers keep current, before the text classifier runs.
Drop the dead name branch and replace the test that fabricated the name
with one built the way the client builds the error, plus dispatch-level
cases for both signals that fail without the dispatcher check.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* fix(browser-use): close six fail-open paths in the playwright adapter
Round-22 review found six Critical defects in the new package; each is
fixed at its root and pinned by a test that goes red without the fix:
- locator.evaluateAll opened a second full timeout window after the
attach wait had consumed the caller's budget; the wait and the read
now share one deadline, and a wait that consumed the budget settles
[] without evaluating.
- tab.goto passed any string to page.goto, so a file:// URL would have
handed local file contents to the tab's evaluate and snapshot reads;
goto is gated to http(s) before the navigation runs.
- Synthesized CDP error responses carried no code, so a reply orphaned
by a target crash tripped Playwright's internal assert and tore down
the whole transport; they now carry -32001, the orphan-swallow code.
- A dialog already open when a tab attaches is replayed by neither
Chrome nor Playwright, so the DIALOG_OPEN gate stayed blind while the
modal blocked the renderer; registration now probes the renderer and
gates the tab on an unanswered probe, with getJsDialog reporting it
under a stable handle whose accept/dismiss run over CDP.
- A dialog opening Playwright never delivered stayed in the trace
forever and swallowed the charge of every later dialog on the tab; a
closed, undelivered entry is retired once the dispatcher turn has
passed.
- snapshotRefLocator validated only the ref's shape, so a ref from a
pre-navigation snapshot could act on whichever element the new
document happened to hand the same string; refs are bound to the
snapshot that emitted them and cleared on main-frame navigation.
Co-Authored-By: Qwen-Coder <[email protected]>
---------
Co-authored-by: qwen-code-dev-bot <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Qwen-Coder <[email protected]>
Co-authored-by: Shaojin Wen <[email protected]>
Co-authored-by: qwen-code-ci-bot <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
* feat(transcript): add cross-host document export pipeline
Establish a shared transcript model and document-mode projection so Web
Shell, VS Code, and HTML export can consume the same stable conversation
semantics without changing interactive rendering.
- Preserve daemon and ACP segment identity across replay and normalization
- Add export-safe previews and a versioned transcript document builder
- Add document-mode Web Shell rendering with bounded Mermaid processing
- Lock direct-daemon and ACP behavior with contract fixtures
- Cover render and export equivalence in integration tests
* feat(transcript): wire real VS Code and HTML export consumers
Move transcript prevalidation onto real product paths while preserving
the legacy VS Code timeline as the default fallback.
- Add version-bound document HTML with strict CSP and schema checks
- Add opt-in ACP projection with stable source identity
- Reuse product export code across hosts and the integration runner
- Remove test-only production probes and consolidate shared validation
Note: Browser, host-action, VSIX, and packaging gates remain pending.
* build(deps): sync transcript workspace dependencies
Keep the npm lockfile aligned with the VS Code and HTML export package
manifests added by the transcript consumer migration.
- Lock the VS Code Web Shell workspace dependency
- Lock Web Templates SDK, Web Shell, and React build dependencies
* feat(vscode-ide-companion): reuse WebShell transcript UI behind experimental flag
Bridge ACP session/update notifications into the shared SDK daemon transcript reducer and render the result with the WebShell transcript component, gated on qwen-code.experimental.webShellTranscript (default off).
The WebShell renderer and its heavy transitive dependencies (echarts, mermaid, shiki, codemirror, katex) are lazily loaded via esbuild code splitting, so the default configuration keeps the ~700KB webview bundle unchanged.
* fix(vscode-ide-companion): grant wasm-unsafe-eval for shiki WASM when WebShell transcript enabled
* fix(transcript): harden export and identity paths
Resolve review findings across document export and the VS Code ACP
timeline while preserving default interactive and readonly semantics.
- Preserve stable text and non-text identity across live and replay
- Harden export projection, budgets, URL handling, CSP, and nonces
- Make document rendering complete, inert, and browser-validated
- Keep VS Code transcript scope, theme, copy, and flags reactive
- Restore fixture, schema, hash, and compatibility contract locks
Note: The overall gate remains failed pending VSIX, host-action, and
packaged-artifact evidence.
* feat(vscode-ide-companion): adopt WebShell transcript as default timeline
Drop the experimental flag and the legacy MessageList renderer. The companion timeline now always renders through the shared WebShell transcript component, fed by ACP session/update notifications via the SDK daemon transcript reducer (lazy loaded through esbuild code splitting).
The flag-gated wiring is removed: the qwen-code.experimental.webShellTranscript setting, the conditional CSP/body attribute in WebViewContent, and the legacy MessageList path in App.tsx (~850 lines). The webview CSP now grants wasm-unsafe-eval unconditionally for Shiki's Oniguruma WASM.
* fix(vscode-ide-companion): reset WebShell transcript state on session switch
The experimental useAcpTranscript hook only consumed transcriptUpdate
messages, so its reducer state survived session boundaries. When the
extension switched sessions it kept the webview mounted and replayed the
newly-selected session through ACP, causing the previous session's blocks
to merge with the new replay (e.g. user text "alpha" from session A leaked
into session B as "alphabeta").
Reset both the reducer state and the rendered blocks on the same
boundaries the legacy message flow uses: qwenSessionSwitched (sent before
the ACP replay of the selected session) and conversationCleared (new
session). Adds a regression test that replays two sessions with a switch
between them.
* fix(vscode-ide-companion): harden WebShell transcript session boundaries
- reset the transcript on `conversationLoaded` too, closing the same
cross-session leak the previous commit fixed for `qwenSessionSwitched`
and `conversationCleared` (agent reconnect posts only this boundary)
- track the active session id and drop late `transcriptUpdate` frames
whose `sessionId` no longer matches, so a previous session's trailing
frames cannot contaminate the next session's timeline
- seed the transcript from cached messages carried by
`qwenSessionSwitched` so offline restores and load-failure fallbacks
render their history instead of a blank timeline
- dispatch `assistant.done` on `streamEnd`/`sessionLoadComplete` so the
final assistant/thought block of a turn (or history replay) does not
stay `streaming: true` forever
* fix(transcript): harden identity and document export
Close the latest review findings across transcript identity, VS Code
rehydration, and the HTML export security boundary.
- Terminate discrete ACP segments and bind automatic turn provenance
- Reset VS Code transcript scopes across replay and reconnect lifecycles
- Align Markdown sanitization and envelope budgets with document rendering
- Run browser gates with Chromium and complete third-party notices
* fix(vscode-ide-companion): adopt live ACP session id after load-failure fallback
* fix(vscode-ide-companion): echo user prompt into WebShell transcript
* fix(vscode-ide-companion): keep WebShell transcript expanded and clear of the composer
* fix(vscode-ide-companion): surface local error and interrupt notices in the transcript area
* fix(vscode-ide-companion): restore file-link opening from the WebShell transcript
* fix(vscode-ide-companion): restore contributed copy commands for the WebShell transcript
* fix(vscode-ide-companion): add localOnly marker to TextMessage state type
* fix(vscode-ide-companion): restore /insight progress card and report link in the transcript UI
* fix(vscode-ide-companion): finalize in-flight tools on timeout and pin session-switch seeding guard
Map streamEnd reasons timeout/session_expired onto the reducer's error reason so abandoned mid-tool turns no longer spin forever (ceuI). Add qwenSessionSwitched cases with no messages field and an empty cache array; the no-messages case fails when the seeding guard is forced true, pinning its false side (ceuN).
* fix(vscode-ide-companion): remove unreachable editMessage backend and dead submit options
The user-message edit/rewind UI was dropped in the WebShell-transcript migration, leaving editTargetTurnIndex/onSubmitted options in useMessageSubmit and the full editMessage/rewind flow in SessionMessageHandler unreachable. Remove the dead options, the editMessage dispatch case, the rewind/snapshot flow with its recovery branches, and their tests (R1-8 direction b).
* fix(vscode-ide-companion): drop write-only loadingMessage bookkeeping
The waiting-message renderer was removed with the WebShell transcript migration and the user prompt is echoed into the timeline at send time (bd09e19d86), so the loadingMessage string was write-only dead state. Keep the isWaitingForResponse flag (submit gating / cancel) and pin its API surface (R1-19 direction b).
* fix(vscode-ide-companion): align waiting-flag pin test with the argument-less setter
* fix(transcript): simplify adapters and preserve segment boundaries
Reduce the shared transcript review surface while keeping the VS Code and
HTML Export consumers and their security gates intact.
- Merge VS Code feature state into the ACP transcript hook
- Collect source identity once and strip it at the compatibility boundary
- Remove test-only export adapters, gate reports, and duplicate helpers
- Keep shell output separated when stable producer segments change
- Mark third-party notices as generated review content
* fix(transcript): address cross-host review regressions
* fix(vscode-ide-companion): echo attached images into the transcript timeline
The prompt carries pasted/attached images as ACP resource_link blocks,
which the transcript reducer cannot render (no inline data), so user
images vanished from the timeline while the attach path stayed alive.
Read each saved prompt image back from disk and echo it alongside the
text echo as an inline user_message_chunk image part (the daemon-echo
content shape), which the shared reducer folds into the user block and
the WebShell renderer already displays. Unreadable images are skipped
without breaking the send.
* fix(vscode-ide-companion): track live VS Code theme for the transcript
webShellTheme was snapshotted once at mount via useMemo with an empty
dependency array, so switching the VS Code color theme left the
timeline on the stale theme (VS Code updates data-vscode-theme-kind on
<body> in place without reloading the webview). Hold the theme in state
and refresh it with a MutationObserver on the body theme attributes.
* fix(vscode-ide-companion): copy every transcript block kind and map ambiguous row keys
- Copy All Messages now includes tool, shell, user_shell, and status
blocks via getBlockCopyText, matching the pre-PR copyAllMessages
handler which included formatted tool calls (review 5001842059 S-1).
- findBlockByRowKey prefers an exact id match and otherwise the longest
matching block id, so one block id that dash-prefixes a sibling (e.g.
`a` vs `a-1`) can no longer capture the sibling's row key (S-4).
* fix(vscode-ide-companion): drop whitespace-only cached transcript rows
cachedMessageToNotification rejected empty strings but admitted
whitespace-only content, which the reducer turns into an empty block
when seeding history from cached rows. Reject content that trims to
nothing (review 5001842059 S-2).
* fix(vscode-ide-companion): ship missing third-party notices in NOTICES.txt
Extend generate-notices.js so the regenerated NOTICES.txt carries the
attribution texts it previously only pointed at or dropped:
- Append license files from a package's licenses/ directory (echarts'
Apache LICENSE references licenses/LICENSE-d3 for its embedded
d3-derived files; the BSD-3-Clause text is now shipped).
- Append a package's NOTICE file when present (Apache-2.0 §4(d)),
covering echarts' Apache Software Foundation attribution.
- Accept string-form package.json repository values (full URLs and
GitHub shorthand) instead of emitting "(No repository found)".
- Fall back to the standard MIT text (copyright holder from package.json
metadata) for MIT-declared packages that ship no license file.
* fix(vscode-ide-companion): show a recoverable error state when the transcript chunk fails to load
* test(vscode-ide-companion): gate the transcript blocks wiring into the WebShell renderer
* test(vscode-ide-companion): gate the transcriptUpdate forwarding from agent to webview
* docs(vscode): plan complete Web Shell cutover
* docs(webui): plan legacy package retirement
* docs(webui): link cutover prerequisite
* feat(vscode-ide-companion): reuse WebShell transcript UI behind experimental flag
Bridge ACP session/update notifications into the shared SDK daemon transcript reducer and render the result with the WebShell transcript component, gated on qwen-code.experimental.webShellTranscript (default off).
The WebShell renderer and its heavy transitive dependencies (echarts, mermaid, shiki, codemirror, katex) are lazily loaded via esbuild code splitting, so the default configuration keeps the ~700KB webview bundle unchanged.
* fix(vscode-ide-companion): grant wasm-unsafe-eval for shiki WASM when WebShell transcript enabled
* feat(vscode-ide-companion): adopt WebShell transcript as default timeline
Drop the experimental flag and the legacy MessageList renderer. The companion timeline now always renders through the shared WebShell transcript component, fed by ACP session/update notifications via the SDK daemon transcript reducer (lazy loaded through esbuild code splitting).
The flag-gated wiring is removed: the qwen-code.experimental.webShellTranscript setting, the conditional CSP/body attribute in WebViewContent, and the legacy MessageList path in App.tsx (~850 lines). The webview CSP now grants wasm-unsafe-eval unconditionally for Shiki's Oniguruma WASM.
* fix(vscode-ide-companion): reset WebShell transcript state on session switch
The experimental useAcpTranscript hook only consumed transcriptUpdate
messages, so its reducer state survived session boundaries. When the
extension switched sessions it kept the webview mounted and replayed the
newly-selected session through ACP, causing the previous session's blocks
to merge with the new replay (e.g. user text "alpha" from session A leaked
into session B as "alphabeta").
Reset both the reducer state and the rendered blocks on the same
boundaries the legacy message flow uses: qwenSessionSwitched (sent before
the ACP replay of the selected session) and conversationCleared (new
session). Adds a regression test that replays two sessions with a switch
between them.
* fix(vscode-ide-companion): harden WebShell transcript session boundaries
- reset the transcript on `conversationLoaded` too, closing the same
cross-session leak the previous commit fixed for `qwenSessionSwitched`
and `conversationCleared` (agent reconnect posts only this boundary)
- track the active session id and drop late `transcriptUpdate` frames
whose `sessionId` no longer matches, so a previous session's trailing
frames cannot contaminate the next session's timeline
- seed the transcript from cached messages carried by
`qwenSessionSwitched` so offline restores and load-failure fallbacks
render their history instead of a blank timeline
- dispatch `assistant.done` on `streamEnd`/`sessionLoadComplete` so the
final assistant/thought block of a turn (or history replay) does not
stay `streaming: true` forever
* fix(vscode-ide-companion): adopt live ACP session id after load-failure fallback
* fix(vscode-ide-companion): echo user prompt into WebShell transcript
* fix(vscode-ide-companion): keep WebShell transcript expanded and clear of the composer
* fix(vscode-ide-companion): surface local error and interrupt notices in the transcript area
* fix(vscode-ide-companion): restore file-link opening from the WebShell transcript
* fix(vscode-ide-companion): restore contributed copy commands for the WebShell transcript
* fix(vscode-ide-companion): add localOnly marker to TextMessage state type
* fix(vscode-ide-companion): restore /insight progress card and report link in the transcript UI
* fix(vscode-ide-companion): finalize in-flight tools on timeout and pin session-switch seeding guard
Map streamEnd reasons timeout/session_expired onto the reducer's error reason so abandoned mid-tool turns no longer spin forever (ceuI). Add qwenSessionSwitched cases with no messages field and an empty cache array; the no-messages case fails when the seeding guard is forced true, pinning its false side (ceuN).
* fix(vscode-ide-companion): remove unreachable editMessage backend and dead submit options
The user-message edit/rewind UI was dropped in the WebShell-transcript migration, leaving editTargetTurnIndex/onSubmitted options in useMessageSubmit and the full editMessage/rewind flow in SessionMessageHandler unreachable. Remove the dead options, the editMessage dispatch case, the rewind/snapshot flow with its recovery branches, and their tests (R1-8 direction b).
* fix(vscode-ide-companion): drop write-only loadingMessage bookkeeping
The waiting-message renderer was removed with the WebShell transcript migration and the user prompt is echoed into the timeline at send time (bd09e19d86), so the loadingMessage string was write-only dead state. Keep the isWaitingForResponse flag (submit gating / cancel) and pin its API surface (R1-19 direction b).
* fix(vscode-ide-companion): align waiting-flag pin test with the argument-less setter
* fix(vscode-ide-companion): echo attached images into the transcript timeline
The prompt carries pasted/attached images as ACP resource_link blocks,
which the transcript reducer cannot render (no inline data), so user
images vanished from the timeline while the attach path stayed alive.
Read each saved prompt image back from disk and echo it alongside the
text echo as an inline user_message_chunk image part (the daemon-echo
content shape), which the shared reducer folds into the user block and
the WebShell renderer already displays. Unreadable images are skipped
without breaking the send.
* fix(vscode-ide-companion): track live VS Code theme for the transcript
webShellTheme was snapshotted once at mount via useMemo with an empty
dependency array, so switching the VS Code color theme left the
timeline on the stale theme (VS Code updates data-vscode-theme-kind on
<body> in place without reloading the webview). Hold the theme in state
and refresh it with a MutationObserver on the body theme attributes.
* fix(vscode-ide-companion): copy every transcript block kind and map ambiguous row keys
- Copy All Messages now includes tool, shell, user_shell, and status
blocks via getBlockCopyText, matching the pre-PR copyAllMessages
handler which included formatted tool calls (review 5001842059 S-1).
- findBlockByRowKey prefers an exact id match and otherwise the longest
matching block id, so one block id that dash-prefixes a sibling (e.g.
`a` vs `a-1`) can no longer capture the sibling's row key (S-4).
* fix(vscode-ide-companion): drop whitespace-only cached transcript rows
cachedMessageToNotification rejected empty strings but admitted
whitespace-only content, which the reducer turns into an empty block
when seeding history from cached rows. Reject content that trims to
nothing (review 5001842059 S-2).
* fix(vscode-ide-companion): ship missing third-party notices in NOTICES.txt
Extend generate-notices.js so the regenerated NOTICES.txt carries the
attribution texts it previously only pointed at or dropped:
- Append license files from a package's licenses/ directory (echarts'
Apache LICENSE references licenses/LICENSE-d3 for its embedded
d3-derived files; the BSD-3-Clause text is now shipped).
- Append a package's NOTICE file when present (Apache-2.0 §4(d)),
covering echarts' Apache Software Foundation attribution.
- Accept string-form package.json repository values (full URLs and
GitHub shorthand) instead of emitting "(No repository found)".
- Fall back to the standard MIT text (copyright holder from package.json
metadata) for MIT-declared packages that ship no license file.
* fix(vscode-ide-companion): show a recoverable error state when the transcript chunk fails to load
* test(vscode-ide-companion): gate the transcript blocks wiring into the WebShell renderer
* test(vscode-ide-companion): gate the transcriptUpdate forwarding from agent to webview
* docs(vscode): plan complete Web Shell cutover
* fix(transcript): harden export sanitization and user identity
Close the latest review findings around document resource safety and
recorded-user replay consistency.
- Redact local home paths structurally without corrupting remote URLs
- Sanitize nested Markdown images inside otherwise safe links
- Advance merged segment provenance without duplicating separators
- Keep recorded-user stable IDs anchored to durable record identity
* refactor(web-shell): own daemon React bindings
* fix(webui): preserve package entry filenames
* refactor(vscode): complete WebShell UI cutover
* chore(vscode): refresh third-party notices
* fix(vscode): fill embedded chat viewport
* test(web-shell): disambiguate workspace visual locator
* docs: clarify webui retirement prerequisites
* fix(transcript): resolve export and CI blockers
* fix(vscode): match embedded chat layout to host
* fix(vscode): compact embedded chat styling
* test(ci): cover dual Playwright installs
* fix(vscode): align embedded chat density with VS Code
* fix(vscode): complete embedded composer integration
* refactor: retire legacy webui package
* chore: refresh lockfile after webui removal
* fix(vscode): restore user message editing after cutover
* refactor: narrow webui retirement to export and removal
* fix(vscode): complete WebShell feature parity
* test(vscode-ide-companion): repair host-wiring tests for the WebShell cutover
* refactor(vscode-ide-companion): replace webui build scanner with an ESLint boundary rule
The bespoke recursive source scanner reimplemented a dependency-boundary
check on every extension build. A scoped no-restricted-imports rule
enforces the same boundary on every lint run with less custom code; the
manifest dependency entry was already removed by the cutover.
* fix(web-shell): keep ChatEditor commands prop referentially stable (#9811)
The `additionalSlashCommands = []` destructure default allocated a fresh
array on every App render, invalidating the `commands` useMemo and breaking
ChatEditor memoization on every transcript-only re-render. Default to a
module-level constant instead, matching the existing EMPTY_* convention.
Also align the /skills completion expectation with the autoSubmit field the
completion source intentionally emits for leaf skill items.
* fix(vscode): distinguish the VS Code channel and localize its chrome
The companion now drives Web Shell against a shared `qwen serve` daemon,
so the CLI, the browser Web Shell, and this extension all create sessions
in the same workspace catalog. Web Shell recorded `'default'` for every
surface, leaving VS Code conversations indistinguishable from terminal and
browser ones — the panel's history listed sessions the user never opened
here, and nothing attributed a session back to the editor.
Give Web Shell a `sessionSourceType` prop (defaulting to today's
`'default'`) and have the companion stamp `'vscode'` on the sessions it
creates, then scope the history dropdown to that source. The host also
supplies a stable daemon `clientId`, which the bootstrap previously
declared but never sent.
Web Shell localizes its own surface from the `language` signal while the
companion's chrome was hardcoded English, so a zh-CN panel rendered a
Chinese transcript under an English header, history dropdown, onboarding
screen, and account dialog. Route that chrome through a small string table
driven by the same signal, including the host-only slash entries.
Also fix accessibility defects in the history dropdown: rename and delete
were revealed on hover alone and unreachable by keyboard, date headers sat
inside `role="listbox"` as invalid non-option children, arrow-key roving
stopped at group boundaries, `aria-modal` had no focus trap, and a primed
"Delete?" survived both search changes and the pointer leaving the row.
Formatting: `FileMessageHandler` and `SessionMessageHandler` were left
unformatted earlier in this branch and failed the Prettier gate.
* refactor(vscode): drop code orphaned by the WebShell cutover
The webview entry now renders EmbeddedApp against the daemon, which left
the ACP-era hook layer unreachable: nothing imports acpTranscriptAdapter,
useWebViewMessages, useAcpTranscript, useToolCalls, useSessionManagement,
useMessageHandling, useFileContext, useImage, or the permissionTypes added
by this branch. A reachability walk from webview/index.tsx reaches eight
modules; every reference to the rest comes from inside the orphaned set
itself, so it deletes as a closed unit.
EmbeddedWebShell goes with them. It was the host-driven entry point from
the earlier stage of this branch, superseded when EmbeddedApp moved to
WebShellWithProviders, and has had no consumer since — only its own DOM
test and a barrel export.
Also harden the daemon process lifecycle. `start()` returned the cached
runtime without comparing the workspace, so in a multi-root window the
second folder's chat silently reused a daemon bound to the first and
scoped every session, history page, and prompt to the wrong root. Bind the
daemon to its workspace and respawn on a change, keep a superseded child's
late exit from tearing down its successor, and report a post-startup exit
to the webview instead of leaving it fetching against a dead port.
* docs(vscode): describe the daemon architecture the cutover actually ships
The design doc still recorded the plan this branch started from: keep ACP
as the runtime boundary, add no daemon server or loopback port, and treat
"replacing ACP with daemon HTTP/SSE" as a non-goal. The final stage did
exactly that, so the document argued against the code beneath it.
Record the decision and its consequences instead — two processes per
workspace, a daemon shared with the CLI and browser Web Shell, the vscode
source type that keeps the panel's history its own, workspace rebinding in
multi-root windows, and the turn-driven host features that stopped firing.
* fix(vscode): repair round-2 review findings on the web-shell cutover (#9811)
- closeDiff now resolves workspace-relative paths the same way showDiff
does, so permission-cycle diffs opened from daemon-relative paths can
actually be matched and closed
- a superseded or disposed daemon child no longer reports its exit as a
crash of the live daemon
- authCancelled no longer hides an already-authenticated session behind
onboarding; only an unknown auth state settles to unauthenticated
- selection-only activeEditorChanged events no longer undo an explicit
active-file exclusion
- prepareSubmit dedupes mentions in both path spaces and matches typed
references on a whole-reference boundary
- permission diffs open only from the SDK's authoritative file_diff
preview (writes included, model-controlled toolCall mining removed)
- the webview HTML carries VS Code's locale so chrome strings localize
- discontinued qwen-oauth models are no longer re-applied through the
new-session initial-model route
* fix(vscode): repair round-3 critical findings on the web-shell cutover (#9811)
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell): import daemon-react-sdk from web-shell instead of webui
The cutover branch dropped the ./daemon-react-sdk export from @qwen-code/webui,
but the TerminalPanel merged in from main still imports it, breaking the
web-shell vite build (Missing "./daemon-react-sdk" specifier). Point the import
and its test mock at @qwen-code/web-shell/daemon-react-sdk, which re-exports the
same useWorkspace hook and matches every other web-shell call site.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(vscode): close WebShell UI regression gaps
Co-authored-by: Qwen-Coder <[email protected]>
* fix(vscode): initialize WebShell refs explicitly
Co-authored-by: Qwen-Coder <[email protected]>
* fix(vscode): narrow queued prompt edits
Co-authored-by: Qwen-Coder <[email protected]>
* fix(release): enumerate actual npm workspaces
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell): include hasOlderHistory in the render-item callback deps
The renderItem useCallback reads hasOlderHistory to gate the edit action
but omitted it from its dependency array, failing CI's
react-hooks/exhaustive-deps gate.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell): report each connection error once to stop the inline onError re-render loop (#10454)
* fix(web-shell): report each connection error once to stop the onError re-render loop
While a connection error persists (e.g. the daemon is unreachable), the
error-notification effect re-fires whenever the onError callback identity
changes. Hosts such as the VS Code embedded app pass an inline onError and
update their own state when it fires, so every notification triggers a host
re-render that hands the effect a fresh callback identity — re-notifying the
same persistent error forever (#10406).
Track the last reported connection.error value in a ref and notify only when
the value changes, resetting the tracker once the connection recovers. This
guards every inline-callback consumer, not just memoized hosts.
Fixes#10406
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell): only stamp the dedup ref once an onError handler exists
Stamping lastReportedConnectionErrorRef before delivery meant a host
that attaches onError after a persistent connection error appeared never
received it: the no-op delivery already marked the error as reported.
Guard on the handler first and add a regression test covering the
late-attach case (red when the guard is removed).
Co-authored-by: Qwen-Coder <[email protected]>
* docs(web-shell): document the onError dedup contract and fix comment wording
Describe the reported-once-per-distinct-error semantics, the reset on
recovery, and that replacing the handler mid-error does not re-deliver.
Reword the effect and test comments to describe the host class instead
of naming the VS Code embedded app, which passes a useCallback handler.
Co-authored-by: Qwen-Coder <[email protected]>
* test(vscode): mirror the web-shell value-dedup in the EmbeddedApp mock
The WebShellWithProviders mock re-notified on every onError identity
change, mirroring the loop App.tsx can no longer produce. Rewrite it to
report each distinct error value once (resetting on recovery), keep the
loop guard as a regression tripwire, exercise it with a changing
callback identity plus a post-delivery effect re-run, and refresh the
handleShellError comment that still cited the old loop as the
memoization reason.
Co-authored-by: Qwen-Coder <[email protected]>
* test(vscode): cast the captured onError prop for the mock wrapper
CapturedProps is an unknown index signature, so the destructured
onError needs the same cast the previous mock applied inline to stay
callable under tsc.
Co-authored-by: Qwen-Coder <[email protected]>
* test(vscode): bail the EmbeddedApp mock before stamping when no onError exists
The mirrored dedup effect stamped lastReportedError and counted a
notification even when no handler was attached, while App.tsx returns
before stamping on that path. Add the same early return so a handler
attached mid-error still receives the persistent error, and pin the
no-handler no-stamp behavior with a test that fails if the guard is
removed.
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell): remove duplicate history dependency
Co-authored-by: Qwen-Coder <[email protected]>
* fix(vscode): close remaining WebShell cutover regressions
Co-authored-by: Qwen-Coder <[email protected]>
* fix(vscode): keep permission diff handling host-scoped
Co-authored-by: Qwen-Coder <[email protected]>
* test(vscode): remove orphaned completion trigger test
Co-authored-by: Qwen-Coder <[email protected]>
* test(web-shell): update daemon SDK mock import
Co-authored-by: Qwen-Coder <[email protected]>
* fix(export): reject unsupported legacy JSONL
Co-authored-by: Qwen-Coder <[email protected]>
* docs(transcript): record the legacy HTML renderer deletion evidence
The contract prevalidation doc is this design's single normative source
(§0.1), so retiring the legacy renderer has to be written back into it.
Three places had drifted:
- §2.1's consumer table still said the HTML Export path "keeps legacy
compatibility for public calls without records". `toHtml` now requires
records and the legacy branch is gone.
- §14's completion gate said the legacy HTML renderer is removed only once
there is deletion evidence. New §12.4 records that evidence — no product
consumer left, signature tightened, fallback explicitly rejected rather
than silently degraded, and a `check:no-webui` guard against
reintroduction — and keeps the VS Code legacy timeline half of the gate
untouched.
- §10.7 promised credential removal without stating its scope. Spell out
that it is http(s) only, and that non-navigable schemes, bare flag
credentials and `code` / `inlineCode` nodes ship verbatim, so the
document boundary is not read as a general secret scanner.
Also comment the two export format signatures: `records` is required
because HTML projects from original records, and the other formatters
ignore the argument.
Docs and comments only; no build or test was run locally.
* fix(docs): correct web-shell SDK hook names, daemon dir table, followup wiring
- daemon-client-adapters/web-shell.md: use the names the barrel actually
exports (useActions/useConnection/usePendingPermissions/
useTranscriptBlocks) in the import example and minimal React shape
- daemon/14-cli-tui-adapter.md: rewrite the
packages/web-shell/client/daemon/ file table to the real layout
(session/DaemonSessionProvider.tsx; the transcript adapter now lives
in client/adapters/ and only exports extractPendingPermission)
- users/features/followup-suggestions.md: suggestion generation is
automatic server-side; Web Shell hosts need no trigger wiring
Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtngpuscjl
* fix(scripts): catch bare packages/webui references in check:no-webui
Widen the second forbidden pattern to /packages\/webui\b/g so
references followed by spaces, punctuation, or end-of-line are flagged
(CI step text, YAML list items, parenthesized mentions), while
lookalikes such as packages/webuix stay clean. Extract the detection
into containsForbiddenReference() and pin it with scripts/tests
fixtures, following the check-tui-dep-direction export convention.
The current tree still scans clean:
node scripts/check-no-webui-dependency.js exits 0.
Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtngpuscjl
* fix(docs): drop dead Adapter Matrix citation and stale Chromatic line
- 16-vscode-ide-adapter.md: 01-architecture.md has no "Adapter Matrix"
section (headings verified at HEAD); drop the dead citation tail and
keep the verified embedding claim (R1-11).
- terminal-capture/motivation.md: Chromatic retired with the webui
package; point the "complement" item at the Playwright-based Web Shell
visual tests already shown in this file's diagram (R1-12).
Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtntktgsk8
* fix(comments): correct stale webui-era notes in SDK test and followup state
- daemonUi.test.ts: the referenced previewMarkdown/rawOutput preservation
test does not exist in web-shell (transcriptAdapter.test.ts only covers
extractPendingPermission); rewrite the note to say the enrichment path
retired with the webui package instead of citing a nonexistent test
(R1-6). Wording avoids the retired package literal so check:no-webui
still passes.
- followupState.ts: no web-shell file imports this module (its daemon
followup hook keeps its own FollowupState/controller; the only
createFollowupController consumer is the CLI Ink hook); fix the module
purpose comment and the createFollowupController docblock accordingly
(R1-13).
Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtntktgsk8
* fix(export): load transcript renderer from unpkg (#11035)
* fix(export): load transcript renderer from CDN
* fix(export): harden CDN renderer loading
* fix(export): host transcript renderer on project OSS
* fix(export): serve npm renderer through unpkg
* fix(release): verify export renderer before VSIX packaging
* docs(daemon): retire the stale ACPAdapter and web-ui.md pointers
R1-2/R1-4 from the review round: the Consumers note still claimed the old
ACPAdapter host postMessage path "remains available" while this PR deletes
the only ACPAdapter, and the migration-status bullet still pointed at
web-ui.md after this PR renamed it to web-shell.md. Both lines now state
what ships: the postMessage path retired with packages/webui (webviews
embed Web Shell, matching 16-vscode-ide-adapter.md), and the adapter
design doc is web-shell.md.
Co-authored-by: Qwen-Coder <[email protected]>
* docs: avoid retired webui path reference
* fix: close WebUI retirement review gaps
---------
Co-authored-by: heyang.why <[email protected]>
Co-authored-by: Shaojin Wen <[email protected]>
Co-authored-by: qwen-code-dev-bot <[email protected]>
Co-authored-by: yiliang114 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(transcript): add cross-host document export pipeline
Establish a shared transcript model and document-mode projection so Web
Shell, VS Code, and HTML export can consume the same stable conversation
semantics without changing interactive rendering.
- Preserve daemon and ACP segment identity across replay and normalization
- Add export-safe previews and a versioned transcript document builder
- Add document-mode Web Shell rendering with bounded Mermaid processing
- Lock direct-daemon and ACP behavior with contract fixtures
- Cover render and export equivalence in integration tests
* feat(transcript): wire real VS Code and HTML export consumers
Move transcript prevalidation onto real product paths while preserving
the legacy VS Code timeline as the default fallback.
- Add version-bound document HTML with strict CSP and schema checks
- Add opt-in ACP projection with stable source identity
- Reuse product export code across hosts and the integration runner
- Remove test-only production probes and consolidate shared validation
Note: Browser, host-action, VSIX, and packaging gates remain pending.
* build(deps): sync transcript workspace dependencies
Keep the npm lockfile aligned with the VS Code and HTML export package
manifests added by the transcript consumer migration.
- Lock the VS Code Web Shell workspace dependency
- Lock Web Templates SDK, Web Shell, and React build dependencies
* fix(transcript): harden export and identity paths
Resolve review findings across document export and the VS Code ACP
timeline while preserving default interactive and readonly semantics.
- Preserve stable text and non-text identity across live and replay
- Harden export projection, budgets, URL handling, CSP, and nonces
- Make document rendering complete, inert, and browser-validated
- Keep VS Code transcript scope, theme, copy, and flags reactive
- Restore fixture, schema, hash, and compatibility contract locks
Note: The overall gate remains failed pending VSIX, host-action, and
packaged-artifact evidence.
* fix(transcript): harden identity and document export
Close the latest review findings across transcript identity, VS Code
rehydration, and the HTML export security boundary.
- Terminate discrete ACP segments and bind automatic turn provenance
- Reset VS Code transcript scopes across replay and reconnect lifecycles
- Align Markdown sanitization and envelope budgets with document rendering
- Run browser gates with Chromium and complete third-party notices
* fix(transcript): simplify adapters and preserve segment boundaries
Reduce the shared transcript review surface while keeping the VS Code and
HTML Export consumers and their security gates intact.
- Merge VS Code feature state into the ACP transcript hook
- Collect source identity once and strip it at the compatibility boundary
- Remove test-only export adapters, gate reports, and duplicate helpers
- Keep shell output separated when stable producer segments change
- Mark third-party notices as generated review content
* fix(transcript): address cross-host review regressions
* fix(transcript): harden export sanitization and user identity
Close the latest review findings around document resource safety and
recorded-user replay consistency.
- Redact local home paths structurally without corrupting remote URLs
- Sanitize nested Markdown images inside otherwise safe links
- Advance merged segment provenance without duplicating separators
- Keep recorded-user stable IDs anchored to durable record identity
* fix(web-shell): restore agent-only group predicate
* refactor(transcript): split HTML export from VS Code migration
Keep MR2A focused on the document export pipeline while preserving the legacy VS Code timeline.
- Retain VS Code /export html as a real document consumer
- Move live transcript adapters, identity wiring, and feature flag to MR2B
- Remove the direct Web Shell dependency and restore baseline notices
- Keep candidate identity evidence in integration-only helpers
- Document the MR1, MR2A, and MR2B delivery boundaries
* fix(web-shell): keep compact agent summaries separate
Preserve synthetic compact summary rows when parallel-agent grouping runs
after compact tool-group aggregation.
- Exclude summary rows from foreground agent-only grouping
- Exclude summary rows from background agent-only grouping
* fix(core): remove duplicate telemetry test mock
* refactor(sdk): share todo preview render fallback
* fix(web-shell): align document subtools with main
* fix(transcript): address HTML export review findings
* fix(transcript): address export review findings
* fix(transcript): close export boundary bypasses
Harden the document export boundary after the latest review found
mixed-path and Markdown parser/scanner gaps.
- Normalize dot segments and mixed separators before home redaction
- Align Markdown preflight with fences, HTML comments, and delimiters
- Remove the internal review report from the tracked repository
* fix(transcript): close export review findings
Close three Critical review findings in the document export and safe
transcript projection paths.
- Share percent-token decoding between home-path redaction and checks
- Reject parser/scanner divergence before Markdown parsing can stall
- Preserve todo entries carried by the document-safe projection
- Add regression witnesses for each reported failure mode
* fix(export): restore document parity and harden projections
Restore HTML export parity without weakening the sealed document
boundary.
- Reject recursively encoded and split home-path structures
- Keep synthesized todo identities unique from authored values
- Restore safe metadata, theme, and document-wide expansion controls
* fix(export): close home-path redaction entrances and restore safe-projection signals
- safePath: detect home segments at any depth (nested /usr/home, /export/home, UNC shares map to [home])
- redactor/validator: use a precise URL pattern (authority+path only) so URL-adjacent and URL-query home paths are no longer absorbed into the remote-URL span; allow quoted username segments
- exporter: dynamic-import the export API in main() with an ERR_MODULE_NOT_FOUND guard and a clear build-precondition message
- safe projection: propagate executionMode from block.background so foreground subagent launches stay separate and keep intervening thinking
* fix(export): close residual home-path leaks
Harden the sealed document boundary against path spellings that could
survive the existing surgical redaction pass.
- Detect residual home components independently after redaction
- Handle spaced usernames and URL-adjacent local paths
- Exempt validated raster thumbnails from visible-text scanning
* fix(export): handle Markdown fences across containers
Prevent document export from aborting or dropping valid code when
fenced Markdown uses non-LF endings or blockquote containers.
- Demote rich fences with CRLF and CR opening lines
- Track CommonMark blockquote ownership with bounded linear scanning
- Cover quoted, nested, HTML-container, and line-ending regressions
* fix(export): unify home-path grammar and keep cancelled safe results
Round 8 review found the export home-path boundary still open at two
entrances, and the document safe projection silently destroying a
cancelled sub-agent's terminal result.
- Derive the residual home-path detector from the redaction grammar
instead of hand-modelling it, and redact bare plus line-initial
relative home roots so ordinary text is no longer discarded wholesale
- Consume each remote URL as one token: verified remote paths pass
through byte-identical, while a token whose ownership stays ambiguous
after a delimiter or a malformed authority degrades as a whole
- Return typed omission signals from home redaction so encoded-content
and URL degradation always set truncated/complete with a diagnostic,
instead of inferring state from a marker string a transcript can forge
- Preserve a string terminal result when stamping the cancelled
background-agent marker, and project that cancellation to failed plus
wasCancelled only on the explicit safe projection path
Note: interactive and readonly callers keep the existing raw and status
compatibility, so a cancelled background agent still reconciles to
completed there.
* fix(export): strip URL credentials from exported command previews
`user_shell.command` and the `command` tool preview went into the document
through `budget.plainText`, which only applies home-path redaction and the byte
budget. A reachable `curl https://user:[email protected]/file?token=secret`
therefore carried both the URL userinfo and the secret query into the exported
JSON and the shareable HTML, against the contract that credentials never enter
the document.
Reuses the projector's own `normalizeNavigableUrl` — the same helper the typed
`web_fetch.url` and repository paths already go through, which clears
`username`, `password`, `search` and `hash` — rather than reaching for the
SDK's `sanitizeUrlsInText`, which is module-private in `daemon/ui/render.ts`
and would have needed a new public export. A command is free text that embeds a
URL rather than being one, so the new helper rewrites each embedded match and
reports `url_sanitized` / `url_rejected` through the existing diagnostics
counter.
Runs before `budget.plainText`: a URL truncated first may no longer match the
pattern, and the truncation boundary should be measured on the text that
actually ships.
Scope is http(s), matching `normalizeNavigableUrl`. A credential in a
non-navigable scheme (`ssh user:pw@host`) or a bare flag (`-pSECRET`) is not
covered; that needs argument-aware redaction, which this projector does not
attempt. The limit is stated on the helper so the contract is not read as
stronger than the code.
* test(web-shell): keep the render-mode provider across session-switch rerenders
Two of main's session-guard tests failed on this branch:
`ignores a stale polling response from the previous session` and
`ignores a workflow action that settles after switching sessions`, both with a
spy that must not fire being called once.
The component was not at fault. Its diff against main is only `documentMode`
guards, and `documentMode` is false throughout these tests, so the interactive
paths are main's unchanged. The cause is the shape of the React tree: this
branch's mount helper renders
`I18nProvider > TranscriptRenderModeProvider > TasksStatusMessage`, while those
tests simulate a session switch by calling `root.render` again with
`I18nProvider > TasksStatusMessage`. The element type at that position changes,
so React unmounts the subtree and mounts a fresh component instead of updating
it — which resets `expectedSessionIdRef` and re-runs the polling effect, and
the guard those tests exist to pin never gets the chance to suppress anything.
Wrapping the three bare `root.render` calls keeps the tree shape stable across
the rerender, with the same `interactive` value the helper defaults to, so the
component updates in place as the tests intend.
ToolGroup.test.tsx has the same bare-render shape in places but its tests pass —
those sites are fresh mounts, where a remount is not observable — so they are
left alone rather than churned.
* fix(web-shell): declare documentMode in the two workflow callback deps
`lint:ci` runs eslint with `--max-warnings 0`, so the two
`react-hooks/exhaustive-deps` warnings failed the job outright:
TasksStatusMessage.tsx
610:5 React Hook useCallback has a missing dependency: 'documentMode'
655:5 React Hook useCallback has a missing dependency: 'documentMode'
`handleWorkflowAction` and `handleWorkflowHistoryDelete` gained a
`if (documentMode || busy) return;` guard during the merge, but their dependency
arrays sat outside the conflict regions and so kept main's list. Adding the
dependency is also the correct fix rather than a lint appeasement: both
callbacks close over `documentMode` now, and a stale closure would let a
document render run an action it must not.
Swept the file afterwards for any other hook whose body reads `documentMode`
without declaring it; these two were the only ones.
* fix(export): validate URL boundaries and raster signatures
Close verified document admission gaps without changing live transcript
semantics or discarding legitimate remote path examples.
- Reject missing and encoded home-path authorities before URL repair
- Check raster MIME signatures in the producer and envelope validator
- Remove redundant separator repetition and pin bounded regressions
- Preserve normal remote URLs and record undecidable decoding as loss
Note: Signatures check format headers, not full image or secret safety.
* ci: record e2e.yml growth in the workflow size baseline
e2e.yml is now 30022 bytes: 3610 bytes of drift already merged into
main within the 4096-byte allowance, plus this PR's transcript
document browser gate (the dedicated gate step, the
chat-transcript-document exclusions, and the nested Playwright CLI
install). Bump the ratchet in this PR as the gate requests, so the
growth stays a reviewed line.
Co-authored-by: Qwen-Coder <[email protected]>
* test(web-shell): scope workflow history visual assertion
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: heyang.why <[email protected]>
Co-authored-by: 易良 <[email protected]>
Co-authored-by: jinjing.zzj <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
Co-authored-by: yiliang114 <[email protected]>
* feat(qwen-live): scaffold standalone live daemon package with ported host stack
New workspace package @qwen-code/qwen-live (M1+M2 of the Live split,
issue #10118). This commit adds the package skeleton and the verbatim
ports that need no behavioral changes:
- host/: Live Host protocol v6 types, LiveHostCoordinator, and the
discovery-file writer, ported from packages/cli/src/serve/live/
together with their test suites (51 tests green)
- realtime/socket.ts, realtime/sanitize.ts: the two helper symbols the
realtime client depends on, extracted from cli ui utils
- registered in scripts/build.js buildOrder and root vitest projects
* feat(qwen-live): generalize the realtime client tool surface
Port qwen-realtime-session.ts and adapt it for the orchestration model:
tools and instructions come from config, every declared tool dispatches
through onFunctionCall with the raw argument payload, and outputs are
receipt-style via submitFunctionOutput. The single-handoff machinery
(multiple_handoffs error, steering acknowledgement, open-call complete)
is removed; transport, response arbitration, pendingCalls timing,
barge-in, and defensive validation are unchanged from the port.
capturesTranscript marks handoff-style tools that capture the live
transcript tail at call time.
Test suite adapted: 27 tests green.
* feat(qwen-live): add the BackendAdaptor seam and the qwen serve adaptor
BackendAdaptor is the capability-bit-driven port between the live
orchestrator and a coding-agent backend. QwenCodeAdaptor drives a
running qwen serve daemon through the @qwen-code/sdk DaemonClient:
202-admission prompts, SSE event normalization (chunks and tool calls
live under session_update.data.update), reject-if-idle mid-turn
steering with a plain-prompt fallback, nested permission votes with
voter attribution, and attachment-backed image blocks. 23 unit tests
against an injected fake client.
* feat(qwen-live): orchestrator, tools, injector, permissions, and daemon entry
The M1+M2 core:
- seven receipt-style dispatch tools plus remain_silent, with a
dispatcher that answers every call (timeout fallback included) and
session_N/job_N/asset_N handle registries
- LiveSession wires Host audio, the realtime connection, tool handlers
(appshot via the Host capture channel, handoff with voice-context
packing and image attachments, busy-session steering), backend event
pumps, and a bounded graceful-stop drain
- Injector: safe-insertion window (VAD + response-in-flight + playback
estimate at 48 kB/s with a quiet gap), batch aggregation, per-job
progress throttling, barge-in drops progress, spoken/detail split
- PermissionBroker: allow_always stays a one-shot protocol vote backed
by a local TTL rule; remote resolutions retract queued asks
- LiveDaemon: Host WS endpoint (Bearer + Origin-reject), discovery
publish with fail-fast mutual exclusion and dead-owner handoff,
appshot channel marked ready (the in-process capture path needs no
separate verification), SIGINT/SIGTERM shutdown
- SessionLog: JSONL with synchronous rotation (rename-before-reopen)
116 new unit tests; package total 167 green.
* feat(qwen-live): end-to-end test suites against a real qwen serve daemon
Test stack: a real qwen serve (spawned CLI bundle, fake-openai model
endpoint), a scriptable fake DashScope realtime WebSocket server, the
qwen-live daemon as a child process, and a protocol-v6 FakeHost client
— every boundary is the real wire.
Scenarios (11 tests): discovery publish/remove and hello/welcome,
toggle brings up the realtime session (tool schema + instructions
asserted on session.update), two-way audio byte fidelity, the full
handoff loop against real serve with [COMPLETE] injection and spoken
summary, injection-window hold/batch semantics, permission ask/vote
relay, and busy-session steering tiers.
The suites caught a real bug the unit layer could not: per-session
calls must echo the daemon-issued clientId from the create/attach
response (a self-made id is rejected by the client registration guard
and broke handoff admission and vote attribution). QwenCodeAdaptor now
tracks and echoes the issued id per session.
* chore(release): keep @qwen-code/qwen-live versioned independently
Same treatment as sdk/mobile-mcp/node-repl: the incubating package
stays at its own 0.x version instead of lock-stepping with the CLI
release train. The verbatim guard in package-scripts.test.js is
updated alongside.
* fix(qwen-live): harden review findings across dispatcher, injector, and permission relay
Self-review fixes bundled after the adversarial pass:
- adaptor: classify snake_case permission option ids (proceed_once) —
the word-boundary regex never matched through "_", so an allow vote
silently degraded to a cancelled outcome and serve dropped the turn
- adaptor: detect the pending-prompt limit by error name as well as
status, and fall image-bearing steers back to a regular prompt
- dispatcher: a timed-out tool now answers with a pending receipt that
tells the model not to retry (the handler keeps running)
- injector: permission items flush ahead of the size-capped context
join; spoken lines merge whole-line greedily under the 280-char cap
- live-session: resubscribe the event pump with backoff until
session_closed; a rejected permission chain can no longer become an
unhandled rejection; receipts are clamped and never empty
- permission broker: a failed auto-approval falls back to the spoken
ask instead of losing the request
- daemon/config/index: appshot readiness is declared at construction,
numeric config ports parse, stray rejections are logged not fatal
- e2e harness: QWEN_LIVE_E2E_KEEP=1 keeps the temp dirs for post-mortem
* fix(qwen-live): address review round 1 — permission voting, shutdown, discovery reclaim, and hardening
Permission trust boundary:
- classify options by the wire's structured kind enum (allow_once/
allow_always/reject_*) instead of word regexes over snake_case ids,
and vote the least-escalating match — a spoken "allow" now lands on
proceed_once, never proceed_always_project
- respond_permission's note is no longer discarded: it is logged and
relayed to the backend session as a follow-up user instruction
- track own votes per session so byUs attribution works on adopted
sessions; narrow allow_always standing rules to the exact normalized
command instead of a two-token prefix
Lifecycle:
- daemon stop() no longer hangs when SIGINT lands before listen() or
when a Host redials during shutdown (stopping gate + client terminate)
- dead-owner discovery reclaim now follows the cli contract (no-op
commitOwner during handoff, republish after) — previously it could
never succeed and a crash left the daemon unable to start
- stop drain settles on the input-commit ack instead of burning the
full 30s budget; response.created during the drain no longer flips
the call back to speaking; a host-initiated start can no longer race
deactivate()
Robustness:
- a late ASR final for an already-consumed input item is ignored as
stale_input instead of dropping the call
- raise the Host frame cap to cover a conformant CJK accessibility
dump (64KiB frame cap contradicted the 32k-char field cap)
- bin entry works through npm's bin symlink (realpath + pathToFileURL)
- steered handoffs that join a running turn reuse the existing job
instead of orphaning it; over-long steers fall back to a queued
prompt; session_list unions created cwds, requests a full page, and
maps hasActivePrompt for untracked sessions; created-session labels
are applied via session metadata
- injector: jobless throttle keys use the full context, dedup is
symmetric, and barge-in drops clear the throttle stamp; sentence
shapers handle CJK punctuation and mid-token periods
- config loader: ENOENT-only swallow, BOM strip, ~ expansion, typed
port validation, source-accurate errors; session log close() is
terminal; transcript retention is capped
Tests and docs: new config/daemon/sanitize suites, win32 guards
restored on discovery mode assertions, protocol parity test now checks
both type copies, qwen-live e2e suites join the no-AK PR gate, fake
model gating in the inject e2e matches only the current turn and is
consumed on match, FakeHost answers capture requests, lockfile diff
reduced to qwen-live-only entries, README states the installer gap.
* test(qwen-live): pin injector size caps and steered-message delivery
- injector: 6000-char combined-context cap, whole-line spoken join at
the 280-char boundary, single-line ellipsis truncation
- steering e2e: assert the joined instruction actually reached the
model endpoint, not just the receipt wording
* fix(sdk): raise daemon browser bundle budget
Co-authored-by: Qwen-Coder <[email protected]>
* feat(qwen-live): scaffold standalone live daemon package with ported host stack
New workspace package @qwen-code/qwen-live (M1+M2 of the Live split,
issue #10118). This commit adds the package skeleton and the verbatim
ports that need no behavioral changes:
- host/: Live Host protocol v6 types, LiveHostCoordinator, and the
discovery-file writer, ported from packages/cli/src/serve/live/
together with their test suites (51 tests green)
- realtime/socket.ts, realtime/sanitize.ts: the two helper symbols the
realtime client depends on, extracted from cli ui utils
- registered in scripts/build.js buildOrder and root vitest projects
* feat(qwen-live): generalize the realtime client tool surface
Port qwen-realtime-session.ts and adapt it for the orchestration model:
tools and instructions come from config, every declared tool dispatches
through onFunctionCall with the raw argument payload, and outputs are
receipt-style via submitFunctionOutput. The single-handoff machinery
(multiple_handoffs error, steering acknowledgement, open-call complete)
is removed; transport, response arbitration, pendingCalls timing,
barge-in, and defensive validation are unchanged from the port.
capturesTranscript marks handoff-style tools that capture the live
transcript tail at call time.
Test suite adapted: 27 tests green.
* feat(qwen-live): add the BackendAdaptor seam and the qwen serve adaptor
BackendAdaptor is the capability-bit-driven port between the live
orchestrator and a coding-agent backend. QwenCodeAdaptor drives a
running qwen serve daemon through the @qwen-code/sdk DaemonClient:
202-admission prompts, SSE event normalization (chunks and tool calls
live under session_update.data.update), reject-if-idle mid-turn
steering with a plain-prompt fallback, nested permission votes with
voter attribution, and attachment-backed image blocks. 23 unit tests
against an injected fake client.
* feat(qwen-live): orchestrator, tools, injector, permissions, and daemon entry
The M1+M2 core:
- seven receipt-style dispatch tools plus remain_silent, with a
dispatcher that answers every call (timeout fallback included) and
session_N/job_N/asset_N handle registries
- LiveSession wires Host audio, the realtime connection, tool handlers
(appshot via the Host capture channel, handoff with voice-context
packing and image attachments, busy-session steering), backend event
pumps, and a bounded graceful-stop drain
- Injector: safe-insertion window (VAD + response-in-flight + playback
estimate at 48 kB/s with a quiet gap), batch aggregation, per-job
progress throttling, barge-in drops progress, spoken/detail split
- PermissionBroker: allow_always stays a one-shot protocol vote backed
by a local TTL rule; remote resolutions retract queued asks
- LiveDaemon: Host WS endpoint (Bearer + Origin-reject), discovery
publish with fail-fast mutual exclusion and dead-owner handoff,
appshot channel marked ready (the in-process capture path needs no
separate verification), SIGINT/SIGTERM shutdown
- SessionLog: JSONL with synchronous rotation (rename-before-reopen)
116 new unit tests; package total 167 green.
* feat(qwen-live): end-to-end test suites against a real qwen serve daemon
Test stack: a real qwen serve (spawned CLI bundle, fake-openai model
endpoint), a scriptable fake DashScope realtime WebSocket server, the
qwen-live daemon as a child process, and a protocol-v6 FakeHost client
— every boundary is the real wire.
Scenarios (11 tests): discovery publish/remove and hello/welcome,
toggle brings up the realtime session (tool schema + instructions
asserted on session.update), two-way audio byte fidelity, the full
handoff loop against real serve with [COMPLETE] injection and spoken
summary, injection-window hold/batch semantics, permission ask/vote
relay, and busy-session steering tiers.
The suites caught a real bug the unit layer could not: per-session
calls must echo the daemon-issued clientId from the create/attach
response (a self-made id is rejected by the client registration guard
and broke handoff admission and vote attribution). QwenCodeAdaptor now
tracks and echoes the issued id per session.
* chore(release): keep @qwen-code/qwen-live versioned independently
Same treatment as sdk/mobile-mcp/node-repl: the incubating package
stays at its own 0.x version instead of lock-stepping with the CLI
release train. The verbatim guard in package-scripts.test.js is
updated alongside.
* fix(qwen-live): harden review findings across dispatcher, injector, and permission relay
Self-review fixes bundled after the adversarial pass:
- adaptor: classify snake_case permission option ids (proceed_once) —
the word-boundary regex never matched through "_", so an allow vote
silently degraded to a cancelled outcome and serve dropped the turn
- adaptor: detect the pending-prompt limit by error name as well as
status, and fall image-bearing steers back to a regular prompt
- dispatcher: a timed-out tool now answers with a pending receipt that
tells the model not to retry (the handler keeps running)
- injector: permission items flush ahead of the size-capped context
join; spoken lines merge whole-line greedily under the 280-char cap
- live-session: resubscribe the event pump with backoff until
session_closed; a rejected permission chain can no longer become an
unhandled rejection; receipts are clamped and never empty
- permission broker: a failed auto-approval falls back to the spoken
ask instead of losing the request
- daemon/config/index: appshot readiness is declared at construction,
numeric config ports parse, stray rejections are logged not fatal
- e2e harness: QWEN_LIVE_E2E_KEEP=1 keeps the temp dirs for post-mortem
* fix(qwen-live): address review round 1 — permission voting, shutdown, discovery reclaim, and hardening
Permission trust boundary:
- classify options by the wire's structured kind enum (allow_once/
allow_always/reject_*) instead of word regexes over snake_case ids,
and vote the least-escalating match — a spoken "allow" now lands on
proceed_once, never proceed_always_project
- respond_permission's note is no longer discarded: it is logged and
relayed to the backend session as a follow-up user instruction
- track own votes per session so byUs attribution works on adopted
sessions; narrow allow_always standing rules to the exact normalized
command instead of a two-token prefix
Lifecycle:
- daemon stop() no longer hangs when SIGINT lands before listen() or
when a Host redials during shutdown (stopping gate + client terminate)
- dead-owner discovery reclaim now follows the cli contract (no-op
commitOwner during handoff, republish after) — previously it could
never succeed and a crash left the daemon unable to start
- stop drain settles on the input-commit ack instead of burning the
full 30s budget; response.created during the drain no longer flips
the call back to speaking; a host-initiated start can no longer race
deactivate()
Robustness:
- a late ASR final for an already-consumed input item is ignored as
stale_input instead of dropping the call
- raise the Host frame cap to cover a conformant CJK accessibility
dump (64KiB frame cap contradicted the 32k-char field cap)
- bin entry works through npm's bin symlink (realpath + pathToFileURL)
- steered handoffs that join a running turn reuse the existing job
instead of orphaning it; over-long steers fall back to a queued
prompt; session_list unions created cwds, requests a full page, and
maps hasActivePrompt for untracked sessions; created-session labels
are applied via session metadata
- injector: jobless throttle keys use the full context, dedup is
symmetric, and barge-in drops clear the throttle stamp; sentence
shapers handle CJK punctuation and mid-token periods
- config loader: ENOENT-only swallow, BOM strip, ~ expansion, typed
port validation, source-accurate errors; session log close() is
terminal; transcript retention is capped
Tests and docs: new config/daemon/sanitize suites, win32 guards
restored on discovery mode assertions, protocol parity test now checks
both type copies, qwen-live e2e suites join the no-AK PR gate, fake
model gating in the inject e2e matches only the current turn and is
consumed on match, FakeHost answers capture requests, lockfile diff
reduced to qwen-live-only entries, README states the installer gap.
* test(qwen-live): pin injector size caps and steered-message delivery
- injector: 6000-char combined-context cap, whole-line spoken join at
the 280-char boundary, single-line ellipsis truncation
- steering e2e: assert the joined instruction actually reached the
model endpoint, not just the receipt wording
* feat(qwen-live): port the Live Host installer — M1 gap closed
`live-host-installer.ts` moves verbatim from
packages/cli/src/serve/live/ (same OSS/GitHub dual-source manifest
fetch, sha256 + codesign + team-identifier verification, staging +
backup install with rollback, and the retryable status machine), with
its 11-test suite. The daemon gains the matching HTTP surface:
- GET /live/setup — installed Host state
- POST /live/setup/install — download + verify + install the latest
POST /live/setup/launch — open the installed app
All three sit behind the daemon's existing Bearer wall (a browser
context sending Origin is always refused, wrong token 401) — pinned by
a new daemon test; unknown paths stay 404 and GET /healthz answers
plain 200. Bootstrap no longer depends on the built-in qwen-code Live
integration having installed the Host first.
* fix(qwen-live): attach the appshot-timeout rejection handler before advancing fake timers
The timeout rejects synchronously inside advanceTimersByTimeAsync; a
handler attached only afterwards leaves an unhandled rejection for an
instant, which vitest counts as a run-level error (CI fails the
package with Errors: 1 even though all 250 tests pass). Attach the
expectation first, await it after the clock advances.
* test(qwen-live): sync the no-AK gate pin with the qwen-live suites
The no-ak-integration-ci pin (added upstream after our branch point)
asserts the gate's file list verbatim; add the four qwen-live suites
the gate has been running since they joined it.
* fix(qwen-live): address review round 2 — trust-boundary keys, backpressure, session lifecycle
Criticals (all probed and reproduced before fixing):
- broker titleKeyOf: split on the FIRST colon and keep the entire
remainder (commands routinely contain colons — a truncated key
auto-approved a different -m message), and stop case-folding
(/a vs /A are different paths on Linux). The whitespace-collapse
pin is preserved
- broker deny: an explicit spoken refusal now revokes the standing
rule that matched the same request — the silent auto-answer's
fallback path could otherwise be overridden by the invisible rule
on the next identical request
- adaptor activeJobRef: a busy-session fallback (image steer, over-
long text 400) no longer overwrites the running turn's ref with the
queued prompt's id — later steer receipts report the right job
- adaptor byUs attribution: the daemon's originator stamp is now
authoritative when present; ownVotes only covers anonymous
resolutions. Another client resolving during our vote round-trip no
longer reads as our own answer (R1-2 regression, fixed test-first)
- adaptor permission titles: control sequences stripped before the
title reaches speech or keys a standing rule (whole command kept —
no first-line cut, unlike the progress path)
- live-session pushAudio: the provider's backpressure signal is
propagated (the port source fails the call) and onAudioDropped is
wired to failCall — a socket over its buffer cap no longer silently
garbles the utterance; the deliberate true for stale/connecting
frames is untouched
- handles: closed sessions stop resolving entirely (registry-level),
and session_closed clears the call's default handle so a session-
less handoff rebuilds instead of retrying a dead target forever
- handles: read-site reconciliation — session_list and session_monitor
transition a session's stale non-terminal jobs to done when the
backend itself reports idle (a turn_complete emitted while no pump
was subscribed no longer reports a running active_job forever)
Suggestions on this PR's new surfaces:
- live-host.yml: packages/qwen-live/src/host/** joins the path filter
so the parity-test lane runs on qwen-live-only PRs instead of first
failing in the merge queue
- installer: the install route passes force=true (the recovery path
for a corrupted-but-present app, matching the CLI mirror), and
launch() gains the non-darwin guard in BOTH copies so the byte
parity pin stays green
- index: directory-form invocation (node packages/qwen-live) now
runs main() instead of exiting 0 silently
- realtime: the dead lastHandoffEntryCount machinery is removed
(truncate-and-reset replaced the cursor it pretended to track)
---------
Co-authored-by: Claude <[email protected]>
Co-authored-by: 易良 <[email protected]>
Co-authored-by: yiliang114 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(channels): add DingTalk Workspace channel
Add a DingTalk Workspace (DWS) channel package so a workspace can be
driven from DingTalk alongside the existing channels.
- packages/channels/dws: new workspace holding the DWS client, event
stream, environment resolution and channel implementation, with the
event-source fixtures used by its tests.
- cli: register DWS in the channel registry and its builtin list.
- web-shell: recognise the DWS platform in the channels UI.
- docs: document the channel and its configuration under
docs/users/features/channels.
- build/release: include the new workspace in the build, clean and
release-version scripts and the vitest project list.
The channel watches native DingTalk todos, routes document and todo
replies back to their originating conversation, bounds notification
retries, and keeps sender identity authoritative for direct messages.
* fix(dws): classify spawn-resource errnos as not sent, and test against base's source
Round 1 review, two Critical findings.
vitest.config.ts — the new package's config was the only channel config
without the `@qwen-code/channel-base` → source alias its five siblings carry,
so `cd packages/channels/dws && npx vitest run` (the workflow AGENTS.md
prescribes) depended on a prior `tsc --build` of base. Reproduced the
reviewer's witness in this worktree with base/dist moved aside: without the
alias vitest dies in `packageEntryFailure` and runs zero tests; with it,
63/63 pass. Even when dist exists it may lag base's source — it did here, by
four days.
dws-client.ts — `DWS_NOT_SENT_ERROR_CODES` listed only the path errnos, so a
`dws` process that never started because of fd or memory exhaustion
(`EMFILE`/`ENFILE`/`ENOMEM`/`EAGAIN` and family) was classified `unknown`.
The todo and document reply paths in dws-channel.ts swallow `unknown` as
"the originating task will not be rerun", so a user's final reply was dropped
permanently on one log line instead of being retried — and the retry is safe,
since the fingerprint is not persisted when delivery fails. The set now
carries the whole `uv_spawn` pre-exec family. Everything else the callback
reports — a non-zero exit (numeric `code`), a timeout kill (`code === null`),
`ABORT_ERR`, a `maxBuffer` overrun — happened with a child already running
and stays `unknown`, because a retry there could duplicate a delivery.
The classification moved into an exported `classifyDwsCommandFailure` so the
table can be driven directly: the resource errnos need real fd or memory
exhaustion to reproduce through a spawn, which no unit test can stage safely.
The existing missing-executable test still covers the wiring end to end.
Verified: packages/channels/dws — 191 passed (5 files). Mutation-verified:
reverting the errno set turns exactly the 12 added codes red (12 failed /
51 passed); dropping the vitest alias with base/dist absent turns the suite
from 63 passed into a collection failure. eslint and prettier clean. The one
tsc error on this branch (`displayText` missing from `Envelope`) is worktree
build skew — base/dist was built 2026-08-10, base/src changed 2026-08-14, and
the field is present in the source; it reproduces identically with these
changes stashed.
* fix(dws): stop a denied sender from consuming a document comment's dedup slot
Round-2 review, R2-4 (Critical).
`notificationKey` is `documentNotificationKey(documentId, commentKey)` — no
sender in it — so a `'denied'` outcome falling into the `else` branch marked
that (document, comment) pair processed for good. Every later notification for
the same comment, live or polled, then hit
`processedMessages.includes(notificationKey)` and returned silently, including
one from a sender who IS allowed. The cursor persists, so the drop survived
restarts.
Concretely, with `senderPolicy: 'allowlist'` and `allowedUsers: ['open-bob']`:
Alice (not allowlisted) @-mentions the bot in a document comment and is denied;
Bob then mentions the bot on the same comment thread — the ordinary
multi-reviewer document flow — and is dropped forever, with no dispatch, no
pairing and no log.
A denied notification is now parked with `rememberPendingDocumentNotification`
like a `'pairing'` one rather than consuming the slot. Replay already skips a
pending entry whose sender fails `gate.isAllowed`, so a denied sender does not
get retried in; and an allowed sender reaching the same comment clears the
entry on the way through.
The existing `applies sender access policy to document mention notifications`
cannot cover this — its denied and allowed notifications are on DIFFERENT
comments, so the shared key is never exercised. New test puts both on the same
comment. Mutation-checked: restoring the old condition reddens it with
`bridge.prompt` called 0 times against an expected 1, reproducing the review's
own witness.
Verification: `npm run build` and `tsc --noEmit` clean in packages/channels/dws;
eslint clean on both changed files; full package suite 192/192 (118 in
dws-channel.test.ts, 1 new).
* fix(dws): stop a poison message, a full pending queue, and an unreachable
replay from pinning the watermark (R2-1, R2-2, R2-4 queue)
Three ways history polling could stall forever, each measured:
**R2-2, poison message.** A message whose turn threw was never marked
processed, so the watermark never advanced and every poll re-ran it as a
full agent turn — one model call per iteration, no cap, no backoff —
while the pinned watermark grew the query window without bound and the
throw starved every newer message behind it. Pending-document replay
already had retry accounting; this path had none. Inbound failures are
now counted per message and persisted in the cursor: under budget the
error still propagates (redelivery retry and the concurrent-duplicate
contract depend on that, and their tests pin it), and once the budget is
spent the message is marked processed and dropped with a logged reason.
**Pending-queue cap.** `rememberPendingDocumentNotification` threw at
MAX_PROCESSED_ITEMS, and the throw aborted the direct-message loop
before the checkpoint, the watermark and `markProcessedMessage` — so
every later poll re-scanned a growing window and re-threw on the same
never-marked message, surviving restarts in the cursor. The queue's only
drain is an allowed sender later processing the same comment, so entries
parked for unapproved senders never leave: one unpaired member
@-mentioning the bot in 5,000 distinct comments broke document history
polling until manual cursor surgery. It now evicts the oldest instead,
which costs at most a pairing prompt nobody approved.
**R2-1, the replay the fixture could not recover.** The test fake
ignored its `startTime`/`endTime`, so it certified a recovery the
production arithmetic cannot perform. Fixed on both sides: the fake now
filters by its window like the real client (and `message()` defaults
`eventTime` to now, since real messages always carry one — six fixtures
were silently relying on epoch 0), and the stale-replay guard now pulls
`notificationWatermark` back to the parked notification's event time. It
parks document notifications UNMARKED on purpose, "for polling to
recover"; on a fresh cursor the watermark started at
`connectionStartedAt` and the window opened at `watermark − 5s` —
exactly the guard's own drop boundary — so everything it parked was
strictly outside every window that watermark would ever produce.
Every fix is mutation-verified: reverting the retry budget re-runs the
poison turn once per poll (8 polls, 8 turns), restoring the queue throw
reproduces the reviewer's stderr and the pinned watermark, and dropping
the watermark pull-back leaves the replayed notification unrecovered.
Suite 194/194 green; `tsc -p packages/channels/dws` clean.
R1-2 (self-identity degradation) is not in this commit — both fixes the
review proposes collide with behaviour this suite pins deliberately; see
the thread.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
* fix(dws): budget every inbound surface, and stop restarting a dead source (R4-1, R4-3)
R4-1: round 3 added an inbound failure budget, but wired it into one of the
three `handleInbound` call sites — the mention/live-IM path. The other two kept
the exact unbounded-retry mode the budget's own doc comment says it exists to
close.
- Document notifications (`processDocumentNotification`): a throw escapes
`pollOnce`'s sorted loop and is swallowed by the outer catch, so nothing is
marked processed and `notificationCheckpoint`/`notificationWatermark` — both
assigned after the loop — never advance. Every 5s poll re-ran the same full
agent turn, forever, starving every newer notification behind it.
- Native todos (`pollTodos`): the fingerprint is remembered only on success, so
a todo whose turn keeps throwing was re-fetched and re-run every poll,
forever.
`recordInboundFailure` now takes the drop action as a parameter, because "stop
re-running this" differs per surface: marking the key processed is right for a
message, a document notification carries its own `notificationKey` (and a
pending entry to clear), and a todo is re-fetched by fingerprint. The default
keeps the mention path byte-identical.
R4-3: `retryable: false` is terminal before ready — `retryLimit` returns 0 —
but `scheduleImRestart` never consulted it, and `startImSource` resets
`restartAttempts` to 0 every time a subscription becomes ready. The backoff
exponent therefore stayed at 0, so a permanently denied consumer (permission
revoked, subscription not allowed) was respawned at a constant ~3s forever —
one `dws event consume` child every 2-3s per affected source — while the
channel reported itself connected and delivered nothing for that source.
Post-ready now matches pre-ready: terminal, with a log line saying so.
Verification (`cd packages/channels/dws`):
- `npx vitest run` — 197 passed (was 194; three new tests).
- `npx tsc -p tsconfig.json --noEmit` — clean.
- Mutation checks, one per fix, each turning exactly its own test red and
leaving the other 122 green:
- drop the `retryable === false` guard -> `stops restarting a source that
died permanently after becoming ready` fails.
- drop the document-path budget -> `drops a document notification whose turn
keeps failing, and stops starving newer ones` fails (the newer
notification is never reached).
- drop the todo-path budget -> `drops a native todo whose turn keeps
failing` fails (8 turns instead of 5).
- eslint + prettier clean.
Not addressed in this commit: R4-2 (checkpoint drain overwriting the stale
replay pull-back), R4-4, R1-2, and R4-5..R4-8.
* fix(dws): stop an in-flight poll from clobbering the stale-replay pullback (R4-4)
`handleImMessage` leaves a replayed document notification UNMARKED on purpose,
for history polling to pick up, and pulls `notificationWatermark` back to the
replay's `eventTime` so a future window can reach it. `pollOnce` then wrote
`checkpoint.endTime` over that watermark unconditionally when its own window
finished — and `checkpoint.endTime` is always past the replay's `eventTime`.
The race is not hairline: `runLoop` polls immediately on connect and the IM
subscriptions start before the poll loop, so a startup replay arrives precisely
while poll #1's `listDirectMessages` is awaiting. One clobber puts the parked
replay outside every window the watermark will ever produce — no turn, no log,
no error, and it survives restarts because `saveCursor()` persists it.
`pollOnce` now records whether the watermark was pulled back while its
direct-message fetch was in flight, and on that path drops the window instead of
finishing it: neither the advance nor the paginated checkpoint resume is safe,
because the checkpoint was itself derived from the pre-pullback watermark. The
next poll re-derives a window from the pulled-back value.
Test: `keeps the stale-replay pullback when a poll was already in flight` emits
the replay from inside `listDirectMessages`. Mutation-checked — forcing the
guard false reddens it with `inbound` empty, matching the reviewer's witness
(`dispatched = 0`). It also asserts the second query window opens at or before
the replay's `eventTime`, so a fake that ignored its window could not certify it.
* fix(dws): stop three silent, permanent losses of a document mention (R6-1/R6-2/R6-3)
All three Criticals round 6 raised share a failure shape: a document comment is
consumed by something that had no right to consume it, the user gets no reply,
and nothing is logged. Each is fixed at the point that consumes the slot.
R6-1 — `handleImMessage` pullback (dws-channel.ts): R4-4 rescued a stale replay
by pulling the notification watermark back, but the flag `pollOnce` consults is
cleared at the top of every fetch, so it only ever covered a replay that landed
DURING one. A pullback arriving in the gap between two polls is reset before it
is read; a persisted multi-page `notificationCheckpoint` then resumes a window
that starts after the replay and finishes by writing `checkpoint.endTime` back
over the pulled-back watermark. The replay was left unmarked on purpose, so
after that no window ever reaches it again. The pullback branch now drops the
checkpoint as well, which makes the rescue durable regardless of when the
replay arrived; the in-flight flag still guards the during-a-fetch case.
R6-2 — in-flight awaiter (dws-channel.ts): a pending entry means the in-flight
turn PARKED the comment for a sender it would not serve, which says nothing
about the caller waiting behind it. Marking unconditionally consumed an ALLOWED
sender's mention outright — replay only re-drives a parked entry whose own
`senderId` passes the gate (the denied one never will), and the allowed
sender's marked message key is skipped by every later history poll. The awaiter
now marks only when the comment is genuinely processed, or when this caller is
no more entitled to it than the sender already parked. This is what the
denied-sender comment further down already claimed happened ("an allowed sender
reaching the same comment clears the entry on the way through") — the awaiter
was the path that never let them reach it.
R6-3 — failure-budget drop closure (dws-channel.ts): the closure marked the
sender-agnostic `notificationKey` (`document\0comment`, no sender), so five
failed turns — about 25s of transient model or bridge trouble, since each 5s
poll re-runs an unmarked notification — dropped every FUTURE mention of that
comment from anyone, permanently and across restarts. It now marks only the
failing message's own `key`, which is what stops the window re-running it, so
the R4-1 starvation this budget closes stays closed.
Tests (dws-channel.test.ts), each mutation-verified against the pre-fix code:
- `keeps a stale-replay pullback that arrives between two polls` — persists a
bounded checkpoint, emits the replay with no poll in flight, asserts the
checkpoint is released and the next window reaches back over the replay.
Reverting R6-1: `expected { startTime: … } to be undefined`.
- `lets an allowed sender through while a denied turn on the same comment is in
flight` — the concurrent counterpart to the existing R2-4 test, which lets
the denied turn finish first and so cannot reach the awaiter. Reverting R6-2:
the allowed sender's prompt is never called.
- `lets a later mention of a dropped comment retry with a fresh budget` — five
failing polls, then a different reviewer on the same comment after the
outage. Reverting R6-3: `expected [] to deeply equal [ ObjectContaining{…} ]`.
Verification: `npx vitest run` in packages/channels/dws — 201 passed (5 files);
`npx tsc --noEmit -p packages/channels/dws/tsconfig.json` clean; `npm run build`
in that package clean; eslint and prettier clean on both changed files.
R1-2 is untouched: it still needs a maintainer call on which pinned contract
gives, and is not something this commit should decide.
* fix(dws): resolve the sender gate before reading a mentioned document (R7-1)
`parseDocumentMentionNotification` reconstructs `(documentId, commentKey)`
from rendered message text, so a bare alidocs URL in an ordinary DM forges a
mention card the channel cannot tell apart from a genuine platform
notification. `processDocumentNotification` then called
`readDocumentContext` on that attacker-named document BEFORE `handleInbound`
resolved the sender gate, so under the documented default
`senderPolicy: 'pairing'` an unpaired stranger could force this profile to
perform an authenticated read of any document it can reach — a turn the
channel would never serve them.
Resolve `gate.isAllowed(message.senderId)` first and read only for a sender
this channel will actually answer. The envelope already carries a "Document
Markdown was unavailable" fallback, the `preflightInbound` document branch
still parks the mention exactly as before, and
`replayPendingDocumentNotifications` re-enters this path once the sender is
approved, so an approved turn still gets its document context — just after
the gate instead of before it.
BEHAVIOR FLIP: `replays a pairing-pending document mention after approval`
pinned `readDocument` being called once for the still-unpaired sender and
twice overall. That pinned expectation was the defect: it asserted an
authenticated read driven by a sender the gate had already refused. It now
expects zero reads before approval and one after. Verified by mutation —
reverting the guard turns both this test and the new forged-mention test red.
Still open on this class and NOT addressed here: the pairing-code write into
the attacker-named comment thread. Closing that needs either fail-closed
verification that `commentKey` is a real comment on `documentId` mentioning
this profile (no DWS CLI surface exposes it — `listMentionedMessages` covers
group IM, not document comments) or structured mention events, so it is a
maintainer contract call rather than a local fix.
Verification:
- packages/channels/dws: 202 passed (5 files), including the new
`does not read a forged document mention before the sender gate resolves`
- tsc --noEmit -p packages/channels/dws/tsconfig.json: clean
- eslint + prettier --check on both changed files: clean
* fix(dws): list the dws channel as a cli test build prerequisite
`channel-registry.ts` dynamically imports `@qwen-code/channel-dws`, whose
package.json resolves the bare specifier to `dist/index.js` and which
`packages/cli/vitest.config.ts` does not alias to source. It therefore
belongs in `DIST_PREREQUISITES['packages/cli']` alongside every other
builtin channel, so a cli test run on an unbuilt checkout reports the
actionable "run npm run build" message instead of a raw resolution error.
This is what the required `Test (ubuntu-latest, Node 22.x)` check caught
on 4bf040766c: scripts/tests/vitest-global-setup.test.js asserts the list
stays in sync with the registry, and dws was the one registry import
missing from it.
Verified: `npx vitest run scripts/tests/vitest-global-setup.test.js`
29 passed; reverting this one line reproduces the CI assertion exactly
("missing prerequisite entry for packages/channels/dws"), 1 failed | 28
passed. prettier --check and eslint clean.
* fix(dws): close current review blockers
* test(dws): pin fail-closed self identity gate
* fix(dws): preserve retryable inbound work
* fix(dws): preserve in-flight catch-up mentions
* fix(dws): align channel-base on the workspace version so npm ci resolves
`Dependency CVE audit` has failed every run with:
npm ci can only install packages when your package.json and
package-lock.json are in sync.
Missing: @qwen-code/[email protected] from lock file
The diagnosis of "stale base" was right, but the stale file is this PR's
own. `packages/channels/dws` was written when the workspace was at
0.21.11 and pins that version; every sibling channel — dingtalk, feishu,
github, gitlab, qqbot, telegram, wecom, weixin — now says 0.21.14, which
is what `packages/channels/base` actually publishes. A workspace package
cannot satisfy 0.21.11, so npm resolved `@qwen-code/channel-base` for dws
from the REGISTRY instead of linking the sibling, leaving a nested
`packages/channels/dws/node_modules/@qwen-code/channel-base` entry that
`npm ci` refuses. Merging current main cannot fix it: main is not where
the pin lives.
Bump dws to 0.21.14 for both its own version and its channel-base
dependency, matching every sibling, and regenerate the lockfile. The
nested registry entry is gone and dws now links the workspace like the
others. `npm ci --dry-run` completes, and dws typechecks and passes all
211 tests against the workspace channel-base rather than the published
0.21.11 it was resolving before.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VgTjRF91xANQh6SY9YGyCf
* fix(dws): replay failed direct messages, and close open review items
* fix(deps): bump tar to 7.5.22 to unblock CVE audit (#9394)
The 2026-08-21 advisory GHSA-r292-9mhp-454m flags tar <= 7.5.20 as
high severity, failing the Dependency CVE audit gate. Main already
moved to 7.5.22 in #9703, but that landed after this branch's last
merge of main. Bump the lockfile entry in-range (core/cli declare
^7.5.19) to match main, and regenerate the committed NOTICES.txt
artifact whose freshness is enforced by CI.
* fix(dws): unblock npm ci, add publish metadata, and keep todo fetch failures out of the turn budget (R13-1, R13-2, R14-1)
* fix(dws): dedup threaded pairing comments on a persisted marker instead of the rotating code (R15-1)
* fix(dws): clear the todo pairing marker when pairing resolves, not on turn success (R16-1)
* fix(dws): address current review blockers
* fix(dws): satisfy event fixture lint
---------
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: qqqys <[email protected]>
Co-authored-by: qwen-code-dev-bot <[email protected]>
* feat(core): add persistent Node REPL runtime
* fix(core): align Node REPL phase-one contract
* fix(core): align Node REPL module compatibility
* fix(core): remove unused Node REPL host broker
* refactor(node-repl)!: deliver as a standalone MCP server, revert core tools
Replaces the three built-in `packages/core` node_repl tools with a
self-contained MCP server package, `@qwen-code/node-repl-mcp`.
Why
---
Issue #9333 triage accepted the runtime only "for exploration" and gated it
on an open maintainer decision: built-in core tool vs MCP-server-first.
Reversing OpenAI Codex 0.149.0 settled the shape — it ships code mode as a
standalone host with an in-process fallback, and its real-Node `js_repl`
(not the restricted V8 `exec`) is the analogue this roadmap needs, because
stage 3 (#9335) imports cua-driver's N-API addons, which only real Node can
load. Delivering out-of-core also keeps a security-relevant subsystem out of
the maintainer-gated `packages/core` until its value is proven.
What changed
------------
- New `packages/node-repl`: the kernel, module loader, cell transform,
protocol and kernel manager, ported and now dependency-free (local
`debug-log`/`win-path`/`tokenizer` replace core utils; `output-adapter`
emits MCP content blocks in place of `result-converter`).
- Reverted every `packages/core` change, the ~11 packaging files that existed
only to ship the runtime assets into six distribution layouts, and the two
design/plan docs describing the core delivery.
- Deleted the trusted-package/sha256 layer: it was empty and unreachable in
production (`module-loader.mjs` 882 -> 483 lines).
- Wired the package into `scripts/build.js` and the root `vitest.config.ts`.
Net effect: `packages/core` is untouched relative to main; the tool is opt-in
via `mcpServers` instead of registered unconditionally for every user.
Correctness fixes made while porting
------------------------------------
- Stack line numbers were wrong and drifted with binding count (source line 4
reported as 87). The prelude is now one physical line and the cell compiles
with `lineOffset: -1`.
- Top-level `var` nested in blocks/try/switch/loops was silently dropped;
collection now walks the statement subtree, pruning at function boundaries.
Verified against real Node for 16 constructs.
- A binding named `nodeRepl` permanently broke the output channel; such cells
are now rejected. Ordinary globals stay shadowable, matching plain Node.
- Errors thrown by imported modules lost their class, `code` and stack.
- A throwing frame handler could discard buffered protocol frames.
- A hoisted `var` assigned before a throw is now kept, as Node does.
- Unhandled rejections settling after a cell no longer vanish.
- Live sandbox timers are capped, so one runaway loop cannot saturate the
session's event loop.
- Image MIME types are matched case-insensitively on both input paths.
- Binding sort no longer depends on host locale collation.
- The published bin lacked a shebang and mis-detected its entry point, and the
server plus its kernel leaked on every host disconnect.
Tests: 146 across 14 files, including a compiled N-API addon fixture, 100
consecutive cells, 10 concurrent isolated kernels, stack-line fidelity, and
hoisting semantics. Three smoke scripts cover the adapter, the MCP wire and
process lifecycle; the packed tarball was installed into a clean project and
driven end to end.
Refs #9333
* fix(node-repl): pin zod to the hoisted 3.x so the workspace build type-checks
`packages/node-repl` declared `zod ^4.1.13`, so `npm ci` installed a nested
zod 4.4.3 for it while `@modelcontextprotocol/sdk` resolved the hoisted
zod 3.25.76. Two zod type identities in one compilation made every
`registerTool` input schema unassignable (`Type 'ZodString' is not assignable
to type 'AnySchema'`), failing `npm run build` for this workspace — and with
it the install step of every CI job that builds workspaces.
The SDK accepts `^3.25 || ^4.0`, so pin the hoisted 3.x line and drop the
now-stale nested lockfile entry. One deduped zod, no behaviour change.
This only reproduced with a lockfile-driven install; the local tree had no
nested copy, which is why the build passed locally and failed in CI.
* fix(lint): lint package .mjs node scripts with the node env
The eslint "scripts we run with node" override matched
`packages/*/scripts/**/*.js` but not `.mjs`, nor a package-root `build.mjs`.
`packages/node-repl` is `type: module`, so its `build.mjs` and `scripts/*.mjs`
were linted as browser code and `eslint .` failed with `'process' is not
defined` / `'console' is not defined` / `'setTimeout' is not defined`.
The pre-commit hook only lints `*.{js,jsx,ts,tsx}`, so `.mjs` files are not
checked locally — this only surfaced in the root CI lint step.
Add `packages/*/scripts/**/*.mjs` and `packages/*/build.mjs` to the override,
matching the existing `.js` entries. Generic, additive, no behaviour change.
* fix(node-repl): address round-3 review findings (resolution, error identity, image bound)
Triaged the bot's round-3 critical findings against the ported code and fixed
the three that were genuine defects here; each has a regression test.
- R3-5 (resolution): a symlinked `<cwd>/node_modules` — the norm under pnpm,
monorepo hoisting and shared CI caches — was silently dropped, so the
documented zero-config `await import('pkg')` failed with "cannot resolve from
0 module roots" while plain Node resolved it. The implicit cwd root was
applying a re-link self-comparison that only makes sense for registered roots
(which carry a registration-time canonical baseline). Follow the symlink for
the implicit root, but skip it entirely when the cwd node_modules is itself a
registered root, so the registered root's revocation guard is not undermined.
- R3-3 (error identity): an error thrown by a host builtin inside imported code
(e.g. `fs.readFileSync` → ENOENT) was rewrapped message-only, dropping
`code`/`errno`/`syscall`/`cause`/`stack` — so `catch (e) { if (e.code ===
'ENOENT') }`, a ubiquitous Node idiom, silently took the wrong branch. Carry
those fields onto the realm-wrapped error.
- R3-6 (image bound): image-frame `mimeType` was unbounded — only `data.length`
counted against the raw image budget — so a malformed/forged frame could
retain a huge string that also got interpolated into a notice and tokenized.
Bound the MIME at frame ingestion (a real image MIME is a few dozen chars).
- R3-4 is by design (the runtime is not a security boundary), but the tool
description recommended `createRequire` without noting it is not subject to
the process denial or module-root containment the import path enforces; the
description now says so.
- R3-1 / R3-2 (the `.mjs` lint failure) were already fixed in an earlier commit.
Suite: 148 tests (added symlinked-cwd resolution and host-builtin error-code
regressions). The symlink fix initially defeated the registered-root revocation
test; the registered-root deferral above resolves both.
* docs(node-repl): note top-level function/class re-declaration needs a fresh name
Round-3 review R3-12/R3-33: re-declaring an existing top-level function or class
in a later cell is a link-time SyntaxError (they persist as `let`, which the
prelude re-declares), whereas a plain Node REPL accepts it. A correct fix needs
declaration-kind tracking the manager does not carry today; until then the tool
description's rerun guidance ('prefer var') is corrected, since a function cannot
be made rerunnable via var.
---------
Co-authored-by: Claude <[email protected]>
* fix(devx): fail with actionable message when unit-test build prerequisites are missing (#9149)
Package-local unit tests in packages/cli import workspace packages
(acp-bridge, sdk, web-templates, channels/*) through their built dist/
output plus the generated git-commit.ts. In a fresh worktree that shares
the main checkout's node_modules, or after a deep clean, those artifacts
do not exist and vitest fails during collection with resolution errors
that blame the wrong thing.
Add a vitest globalSetup guard that checks the prerequisites up front and
exits with a message naming every missing piece and the command that fixes
it (npm run build). Document the prerequisite in the AGENTS.md unit-testing
section.
* fix(devx): address R1 review findings on the unit-test prerequisite guard
- normalize win32 path separators so the guard works on Windows (R1-1)
- use Copyright 2026 Qwen Team header (R1-2)
- drop over-included packages/sdk-typescript; every sdk import in the cli
test graph is an aliased /daemon* subpath (R1-3)
- add a sync assertion test: every builtin channel dynamically imported by
channel-registry.ts must stay listed in DIST_PREREQUISITES (R1-4)
- cover the vitest-invoked entry point via exported checkAndReport (R1-6)
- mirror real manifest shapes (exports.default / import variants) in the
test fixtures (R1-7)
- report missing/unreadable package manifests through the normal exit path
instead of crashing with a raw stack trace (R1-8)
- derive the package key from vitest-s resolved project root, so
vitest run --root packages/cli from elsewhere is covered (R1-9)
- probe every exports entry targeting dist/, not only the . entry, so
missing unaliased subpath builds are reported too (R2-1)
* fix(devx): extend the unit-test prerequisite guard to packages/core
Issue #9149's scope names packages/cli AND packages/core, but the guard
only covered cli: eight core test files (providers/__tests__/presets/*,
provider-config.test.ts) import the bare '@qwen-code/qwen-code-core'
specifier, which resolves through the package's own exports to
dist/index.js — on a fresh checkout 'cd packages/core && npx vitest run
src/path/to/file.test.ts' (the AGENTS.md-documented command) still died
with the opaque 'Failed to resolve entry for package' error.
- Add 'packages/core': ['packages/core'] to DIST_PREREQUISITES
- Wire the same globalSetup guard into packages/core/vitest.config.ts
- Skip wildcard pattern exports entries ('./dist/*') in distEntryFiles:
core's manifest carries them and they name no individual file —
probing them literally would block core test runs even fully built
- Generalize the fixture builder to every DIST/GENERATED_PREREQUISITES
entry, add coverage for the core dist requirement and the wildcard
skip, and move the 'no known prerequisites' example off packages/core
- Note the core self-import in AGENTS.md
Probe-verified both arms at this commit: dist moved aside -> the guard
prints the actionable message and stops the run; dist restored -> the
test file passes (11/11).
* fix(devx): harden the prerequisite probe and its drift tests
- Probe manifest 'main' entries spelled without a leading './': all
guarded manifests use "main": "dist/index.js", which the old
startsWith('./dist/') predicate never matched, so the documented main
probe silently collected nothing. Normalize before the prefix check.
- Tolerate digits in builtin channel names in the sync test's registry
regex ('channel-[a-z0-9-]+'), or a future channel with a digit in its
npm name escapes the drift check.
- Add the reverse sync assertion: every listed packages/channels/*
prerequisite must map back to a channel-registry import (channel-base
excepted as the channels' build dependency), so removing a builtin
channel cannot leave a stale entry that hard-blocks cli test runs
with a misleading 'fresh checkout' message.
- Cover the main-entry probe with a fixture test.
* fix(devx): fail loud on stale probes, align key derivation under symlinks
Round-3 review findings on the prerequisite guard:
- R3-1: a listed package whose manifest enumerates zero ./dist/ targets
(require-only or nested-condition entries) passed the probe silently —
report 'exposes no dist/ entry files to check (guard probe may be
stale)' instead, so a stale probe cannot resurrect the raw resolution
error this guard exists to replace.
- R3-3: when SOME dist entry files exist, the missing one is no longer
diagnosed as 'has not been built' + a plain npm-run-build prescription
(a successful build can legitimately leave a stale exports entry); the
message now says the build output is incomplete or exports points at a
file the build does not emit, and to check the package's exports
entries when rebuilding does not help.
- Key derivation now realpaths both cwd and root (with a fallback to the
raw path): repoRoot descends from import.meta.url, which Node resolves
through symlinks, while vitest resolves root with a plain path.resolve
— comparing them raw let a symlinked ancestor silently disable the
guard.
- R3-2: the channel drift-check character class now tolerates digits,
underscores and dots per npm naming rules.
- R3-4: renamed the test that claimed win32-separator coverage it never
exercised; its body is the degenerate repo-root silent-yield path and
the comment now says so.
- R1-6 (partial): added default-export coverage — project.config.root
extraction and the process.cwd() fallback, asserting no exit in a
built repo. The exit-1 arm of the default export stays untested: it
needs a root-injectable seam the entry point deliberately does not
have; checkAndReport's return-1 and message remain covered directly.
Tests: 21/21; mutation probes confirm the zero-enumeration and symlink
tests catch their regressions.
* fix(devx): hermetic guard tests, alias-aware probe, explicit gitlab build
- drive the default-export tests against a hermetic fixture checkout via
QWEN_VITEST_GUARD_ROOT (in-process and subprocess), so they hold on an
unbuilt worktree instead of depending on the real repository state
- skip dist targets the consumer aliases to TypeScript source when probing,
so a missing-but-aliased dist file no longer blocks runs that would pass
- make the remedy message context-aware: the git-commit hint appears only
when a generated file is missing, and a stale-probe line gets its own note
- add packages/channels/gitlab to buildOrder: it is a cli channel-registry
builtin like its siblings and used to build only transitively
- add drift tests pinning the globalSetup wiring in both vitest configs
* fix(devx): ignore commented vitest aliases
* fix(devx): anchor the vitest globalSetup guard to the config file
R1-1: a relative globalSetup path is resolved against vitest's root (the
process cwd without --root), not the config file's directory, so the
prerequisite guard only loaded when vitest happened to run from inside the
package. `npx vitest run --config packages/<pkg>/vitest.config.ts` from the
repository root died with "Cannot find module .../vitest-global-setup.js"
before any test — the cause-hiding failure class this guard replaces.
Resolve it with path.resolve(__dirname, ...) in both packages/cli and
packages/core configs, and update the wiring-sync assertion (now robust to
prettier line-wrapping; flip-verified red when reverted to a bare string).
---------
Co-authored-by: yiliang114 <[email protected]>
* feat(channels): add GitHub polling adapter with notification-as-wakeup architecture
Introduce a GitHub channel adapter that monitors notifications and
responds to @mentions on issues/PRs by posting comments. Uses
last_read_at as a per-thread watermark for comment enumeration,
replacing the unreliable latest_comment_url approach.
Foundation changes to ChannelBase:
- sendThreadMessage for thread-targeted delivery (IM adapters unchanged)
- Envelope.metadata appended to prompt after command parsing
- chat_thread session scope (channel:chatId:threadId) prevents
cross-repo session collision
- polling-helpers: testBotMention/stripBotMention (separate detection
from stripping, no whitespace collapsing), cursor persistence,
abortableSleep
GitHub adapter design:
- Notifications as wake-up signals only (unread filtering)
- listComments enumeration with last_read_at watermark
- Bot self-comment filtering, case-insensitive mention regex
- In-memory recentlyProcessed set for mark-read failure dedup
- First-contact: new issue body @bot triggers processing
- Error comment + cursor advance on handleInbound failure
- pollInterval minimum 60s, exponential backoff 2s-30s
* refactor(channels): extract PollingChannelBase from polling-helpers
Replace the loose polling-helpers module with a PollingChannelBase<Cursor>
abstract class that encapsulates the poll loop, cursor persistence (JSON,
atomic write), exponential backoff, and start/stop lifecycle. Subclasses
implement only pollOnce() and createInitialCursor().
- Delete polling-helpers.ts (cursor fns + abortableSleep moved into base)
- Move mention utilities (testBotMention/stripBotMention) to github pkg
- GithubAdapter now extends PollingChannelBase<{ lastProcessedAt }>
* fix(channels): remove Gitea/GitLab mention from sendThreadMessage JSDoc
* fix(channels): match /pulls/N in notification subject URL
GitHub PR notifications use /repos/{owner}/{repo}/pulls/{N} in
subject.url, not /issues/{N}. The regex only matched /issues/,
causing PR notifications to be skipped and marked read.
Also sets threadId to 'pr:N' for PRs (was always 'issue:N').
* test(channels): add PR body first-contact unit test
Verify that PR notifications with @mention in the body (not a comment)
correctly trigger the first-contact path: extractFromSubjectUrl matches
/pulls/N, listComments returns empty, tryFirstContactBody fetches the
PR body and dispatches to handleInbound with threadId 'pr:N'.
* feat(channels): read pollInterval from channel config in PollingChannelBase
Move pollInterval config reading from GithubAdapter to the base class.
The user's configured pollInterval in settings.json is now respected
directly without a minimum enforcement. Defaults to 60000ms when not
configured.
* fix(channels): prepend metadata before prompt text
Agent sees issue/PR context (type, title, URL) before the user's
request, improving comprehension. Metadata is still appended after
slash-command parsing so commands are not affected.
* refactor(channels): route all ChannelBase delivery through sendThreadMessage
Replace all internal sendMessage calls with sendThreadMessage, passing
envelope.threadId (or target.threadId / undefined) so polling adapters
can deliver to the correct thread. IM adapters are unaffected — the
default sendThreadMessage falls through to sendMessage.
* docs(channels): document sendThreadMessage delivery architecture
* fix(channels): address review findings
- Cap recentlyProcessed Set at 10k entries to prevent unbounded growth
- Validate cursor JSON shape (non-null object) in loadCursorFromDisk
- sendThreadMessage falls through to sendMessage when threadId is
undefined instead of silently dropping
- Remove duplicate pollInterval from GithubConfig (now in ChannelConfig)
- Fix chat_thread routing key trailing colon when threadId is undefined
* docs(channels): fix metadata JSDoc — prepended, not appended
* fix(channels): use recentlyProcessed dedup for first-contact body
Replace the fragile createdAt-vs-cursor check in tryFirstContactBody
with the recentlyProcessed set. The cursor advances globally based on
notification updated_at — when a different notification with a later
updated_at is processed first, the cursor can advance past the issue's
created_at, causing the first-contact check to incorrectly skip the
issue body (forget reply bug, found in E2E TC-2b).
* refactor(channels): two-layer dedup for GitHub adapter
Layer 1: global cursor filters notifications by updated_at (sorted
ascending, old first). Layer 2: server-side last_read_at filters
comments by created_at (sorted ascending).
- Delete recentlyProcessed Set (no longer needed)
- Sort notifications by updated_at ascending before processing
- Sort comments by created_at ascending before processing
- Pass latest comment created_at to markThreadAsRead as last_read_at
* fix(channels): address review findings on GitHub adapter
Blockers:
- sessionScope: add defaultSessionScope to ChannelPlugin, apply in
parseChannelConfig so router and adapter agree on 'chat_thread'
- channel-registry.test.ts: add 'github' to expected type list
Should-fix:
- Replace per-thread markThreadAsRead (PATCH) with bulk
markNotificationsAsRead (PUT /notifications + last_read_at).
API errors stop the batch without marking failed notifications
read; handleInbound errors still advance (error comment posted).
- connect() throws on bot identity failure instead of failing open
- metadata appended after promptText (inside sender attribution)
- isSharedSessionTarget includes 'chat_thread' scope
Nits:
- startPollLoop re-entrancy guard
- clean-package-build-artifacts.js includes github
- index.ts re-exports GithubChannel
* fix(channels): use max updated_at of all fetched notifications as last_read_at
Prevents re-fetching the same notifications in the next poll cycle.
The bulk PUT /notifications marks all fetched notifications as read
up to the max updated_at, regardless of per-notification success.
* fix(channels): address review round 2 findings
- #12: loadCursorFromDisk rejects arrays
- #13: pollInterval validates positive finite number
- #19: first-contact gate uses dispatchedMention flag (not newComments.length)
- #25: stripBotMention no longer trims (preserves indentation)
- #27: remove adapter-level requireMention, unify on GroupGate
- #31: add chat_thread SessionRouter routing key tests
- #33: clear metadata on collect-mode synthetic envelope
- #35: fix PollingChannelBase.test import path
- #36: add @octokit/rest to 15-channel-adapters.md dependencies
* docs(channels): document known limitations for GitHub adapter
- First start skips existing unread notifications (cursor = now)
- Requires classic PAT (fine-grained PATs lack notifications API)
- PR review comments not enumerated (issue comments only)
* fix(channels): address review round 3 findings
- #9: buildMetadata derives web URL from baseUrl (GHE support)
- #12: sendThreadMessage throws on invalid threadId format
- #19: mention lookbehind matches cc:@bot and "@bot" patterns
- #23: cursor file name uses sha256 hash to prevent collision
- #26: test verifies cursor persistence to disk
- #31: postErrorComment double-failure logs to stderr
- #45: tests use mkdtempSync isolation instead of real QWEN_HOME
* fix(channels): pass threadId through pairing flow + sendResponseMessage test
- #13+16: onPairingRequired receives envelope.threadId and passes it
to sendThreadMessage, so pairing codes are delivered on threaded
channels (GitHub) instead of throwing
- #6: add test verifying sendResponseMessage resolves threadId from
router.getTarget and passes it to sendThreadMessage
* fix(channels): pass proxy to Octokit for daemon-worker environments
- #44: read this.proxy from ChannelBaseOptions and pass
HttpsProxyAgent to Octokit request.agent, matching the
Telegram adapter pattern
* fix(channels): address review findings — immutable senderId, comment time window, validateCursor, retry wrapper
- senderId uses immutable user.id; allowedUsers resolved to IDs at connect
- Comment filter upper bound: updated_at <= maxUpdatedAt (batch window)
- Per-notification errors use continue (best-effort), not break
- validateCursor() virtual hook for subclass cursor shape validation
- sendThreadMessage/postErrorComment wrapped in githubApi() retry
- webOrigin handles default api.github.com → github.com
- Docs: classic PAT only, markNotificationsAsRead, dedup claims removed
- Tests: threadId priority, metadata consumption, defaultSessionScope,
QWEN_HOME isolation, persistent mock rejection
Co-authored-by: Qwen-Coder <[email protected]>
* fix(channels): mark notifications read before processing to prevent duplicate replies
Bot's own replies bump notification updated_at past the pre-captured
maxUpdatedAt, so markNotificationsAsRead(maxUpdatedAt) failed to mark
them read — the next poll re-fetched the same comments and replied
again.
Move markNotificationsAsRead + cursor advance before the processing
loop (best-effort delivery). This is safe because bot's own comments
do not flip notifications back to unread. Update docs to reflect the
new poll cycle order and best-effort semantics.
* fix(channels): update sender gate after allowedUser ID resolution and harden tests
Co-authored-by: Qwen-Coder <[email protected]>
* fix(channels): cursor-based comment window to prevent duplicate replies
PUT /notifications is async (202) with a last_read_at cutoff — the
bot's reply bumps updated_at past the cutoff before the server
processes the mark, so the notification is never marked read and gets
re-fetched on the next poll, causing duplicate replies.
Use the cursor value before advancement as an exclusive lower bound
for the comment enumeration window: (windowSince, maxUpdatedAt].
Comments already eligible in a previous poll are excluded regardless
of whether the mark succeeded. Zero new persistent state.
* fix(channels): cursor-based comment window to prevent duplicate replies
PUT /notifications is async (202) with a last_read_at cutoff — the
bot's reply bumps updated_at past the cutoff before the server
processes the mark, so the notification is never marked read and gets
re-fetched on the next poll, causing duplicate replies.
Use the cursor value before advancement as an exclusive lower bound
for the comment enumeration window, with per-notification last_read_at
as the preferred lower bound when available (server-side per-thread
watermark). Comments already eligible in a previous poll are excluded
regardless of whether the mark succeeded. Zero new persistent state.
* fix(channels): address review findings — null guard, cursor validation, metadata dedup, abortable sleep, docs
- Guard against null notification.subject.url in pollOnce
- Validate lastProcessedAt is a parseable date in validateCursor
- Add metadata: undefined to second collect-mode drain path
- Refactor abortableSleep as protected method on PollingChannelBase
- Fix docs: requireMention is nested under groups.*
- Add tests: chat_thread shared session, dispatchedBodies eviction,
cursor enumeration window, last_read_at in mention tests
* docs(channels): sync docs with implementation — cursor shape, error handling, GitHub adapter tables, first-contact
- Design doc: update Cursor to { lastProcessedAt, dispatchedBodies? }, add
validateCursor date check, abortableSleep protected method, break-on-error
semantics, subject.url null guard
- Developer docs: add GitHub to adapter table and adapter matrix
- User guide: add first-contact step to How It Works, clarify mark-before-process
* fix(channels): address review round 2 — error dedup, abortable retry, backoff reset, window test
- Record dispatchedBody on first-contact handleInbound failure to prevent
duplicate error comments when mark-read async hasn't taken effect
- Use abortableSleep instead of raw setTimeout in githubApi retry so
disconnect() can interrupt rate-limit cooldowns
- Reset consecutiveErrors in startPollLoop so stop/restart cycles don't
inherit stale elevated backoff
- Add test for cursor window client-side lower-bound exclusion filter
* fix(channels): address review round 3 — cursor validation, error dedup, sender gate, bot-self body
- validateCursor: normalize falsy non-array dispatchedBodies (false/0/""/null)
to [] instead of passing them through to .includes() which throws TypeError
- Set dispatchedMention after postErrorComment to prevent first-contact from
posting a duplicate error comment on the same thread
- Only set dispatchedMention when the sender passes the sender gate, so a
disallowed commenter's mention no longer suppresses a valid first-contact
body from an allowed issue author
- Skip bot-authored issue bodies in tryFirstContactBody to prevent
self-response loops under open sender policy
* fix(channels): address review suggestions — test coverage, cursor filename, assertion precision
- Pairing flow: add threadId pass-through regression test
- pollInterval: add table-driven edge cases (0, -1, NaN, Infinity, string)
- Add null-URL notification followed by valid notification batch test
- Fix comment window test to assert paginate call 3 (listComments) not call 2
- Truncate cursor filename encoded prefix to 200 chars (filesystem 255 limit)
- Assert mark-read uses batch maxUpdatedAt, not just { read: true }
- Assert real GitHub plugin declares defaultSessionScope chat_thread
- Add invocationCallOrder assertion for mark-before-process ordering
* fix(channels): address review round 4 — allowedUsers throw on resolve failure, crash table fix, mark-read failure test
* fix(channels): address review round 5 — created_at filter, retry-after NaN guard, retry/sendThreadMessage tests, docs fixes
* fix(channels): address ci-bot review 4778587403 — reconnect idempotency, github type enumerations, retry/webOrigin tests
* chore(channels): align channel-github version to 0.21.0 after upstream merge
* chore(channels): update package-lock.json for channel-github 0.21.0
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: Shaojin Wen <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
Co-authored-by: OrbitZore <[email protected]>
* feat(chrome-qwen-bridge): 🔥 init chrome qwen code bridge
* chore(chrome-qwen-bridge): connect
* chore(chrome-qwen-bridge): connect & them
* chore(chrome-qwen-bridge): connect & them
* chore(chrome-qwen-bridge): wip use chat ui
* chore(chrome-qwen-bridge): wip use chat ui
* wip
* refactor(chrome-extension): rename chrome-qwen-bridge package to chrome-extension
* feat(chrome-extension): enhance network monitoring with webRequest API
Replace the existing network monitoring implementation with a more comprehensive solution that combines both webRequest and debugger APIs for broader coverage. The new implementation:
- Uses chrome.webRequest.onBeforeRequest to capture all outgoing requests
- Uses chrome.webRequest.onCompleted to capture completed responses
- Uses chrome.webRequest.onErrorOccurred to capture failed requests
- Retains debugger API integration for detailed network information
- Implements memory management with maximum 1000 logs per tab
- Adds proper initialization and cleanup for each tab
- Ensures graceful handling of debugger attachment failures
- Provides more reliable network activity capture across all tabs
This enhancement significantly improves the reliability and coverage of network monitoring functionality in the Chrome extension.
* refactor(chrome-extension): reorganize directory structure for better maintainability
This commit reorganizes the entire Chrome extension package structure for improved maintainability and clarity:
- Move all source files to `src/` directory (background, content, sidepanel)
- Move build configurations to `config/` directory
- Move documentation to `docs/` directory with proper categorization
- Move all script files to `scripts/` directory
- Move native-host specific files to appropriate subdirectories (`src`, `scripts`, `config`)
- Update package.json scripts to reflect new file locations
- Add comprehensive documentation files (debugging, development, architecture, API reference)
- Maintain all functionality while improving project organization
The reorganization separates source code from build output, centralizes documentation, and creates a clear separation of concerns making the project more maintainable and easier for developers to navigate.
* feat(chrome-extension): enhance native host communication and network logging
- Add troubleshooting documentation for native host setup issues
- Improve native host logging to home directory with fallback to tmp
- Enhance network logging in service worker with response body capture
- Update scripts to properly reference host.js from correct path
- Increase timeout for MCP session creation and long prompts from 3 to 5 minutes
- Add getConsoleLogs functionality to sidepanel for content script capture
- Improve browser-mcp-server network logs aggregation by request ID
- Update icon assets and improve manifest configuration
refactor(chrome-extension): consolidate host.js entry point and improve path resolution
- Create unified host.js entry point that delegates to src/host.js
- Improve path resolution for host scripts in installer and runner scripts
- Add proper path existence checks for browser-mcp-server.js
- Support running from different directory structures
style(chrome-extension): improve TypeScript type safety and error handling
- Add proper type definitions for message handling in side panel
- Add null checks and error handling for message parsing
- Improve React component callback implementations
* refactor(chrome-extension): redesign build workflow
* fix(chrome-extension): resolve ESLint errors in native host, service worker, and content script
- Fix 'Unexpected lexical declaration in case block' by wrapping switch cases in blocks
- Fix 'Unexpected constant truthiness on the left-hand side of a || expression' by using conditional patterns
- Fix unused variable errors by properly using catch error parameters or adding logging
- Fix 'document' and 'window' not defined errors in service worker with proper global declarations
- Add eslint-disable comments where appropriate for globals used in specific contexts
* feat(chrome-extension): enhance native host with browser MCP tools and event streaming
- Add new browser MCP tools: browser_click, browser_click_text, browser_run_js, browser_fill_form_auto
- Implement SSE (Server-Sent Events) for improved event streaming instead of long-polling
- Add daemon script for running the bridge host in background
- Enhance documentation with MCP notes and updated README
- Add multiple executable binaries to package.json: chrome-browser-mcp, qwen-bridge-host
- Improve error handling and event processing in the native host
- Add debouncing mechanism for stream end events in service worker
- Update timeout for MCP discovery to accommodate slower startup
Co-authored-by: Claude Opus 4.5 <[email protected]>
* fix(chrome-extension): use trusted cwd for MCP tool discovery
The root cause of MCP tools not being recognized by Qwen CLI was that
the cwd (current working directory) was defaulting to '/' (root directory).
In Qwen CLI's MCP discovery logic, there's a security check:
if (!cliConfig.isTrustedFolder()) {
return; // Skip MCP tool discovery
}
The root directory '/' is not a trusted folder, so MCP tools were
silently not being discovered at all.
Changes:
- host.js: Default to $HOME instead of process.cwd() for start_qwen
- service-worker.js: Remove '/' fallback, let host.js handle default
This ensures browser MCP tools (browser_read_page, browser_click, etc.)
are properly discovered and available to the model.
* fix(core): validate MCP entry script existence before connection
Add pre-flight check to verify that stdio-based MCP server entry scripts
exist on disk before attempting connection. This prevents silent failures
and provides clear error messages for misconfigured MCP servers.
* fix(chrome-extension): enhance native host path resolution and port config
- Add QWEN_BROWSER_MCP_SERVER_PATH env override for custom installations
- Expand candidate search paths for browser-mcp-server.js discovery
- Add detailed logging when MCP server script is not found
- Support BRIDGE_PORT env variable for HTTP API server configuration
* fix(chrome-extension): improve browser MCP server reliability and debugging
- Add comprehensive debug logging for bridge health checks and host spawn
- Support BROWSER_MCP_NO_SPAWN env to disable automatic host.js spawning
- Handle bridge unavailability gracefully with clear error messages
- Add raw JSON mode fallback for clients without Content-Length framing
- Capture and log host.js stdout/stderr instead of inheriting stdio
- Add pre-flight bridge check at startup for better diagnostics
- Handle each bridge call failure with proper error responses
* chore(chrome-extension): add debug wrapper script for MCP server
Add cbmcp-wrapper.sh to help diagnose MCP server invocation issues.
The wrapper logs invocation details and stderr to /tmp/cbmcp.log,
making it easier to debug when Qwen CLI spawns the MCP server.
* docs(chrome-extension): add MCP/Bridge troubleshooting guide
Document common failure scenarios when MCP bridge shows as Disconnected:
- EPERM errors when spawning host.js cannot bind to port
- Content-Length framing issues during MCP handshake
- Step-by-step troubleshooting with flow diagrams
- Manual bridge setup with BROWSER_MCP_NO_SPAWN workaround
* build(chrome-extension): 浏览器插件 mcp 构建优化
* docs(chrome-extension): update docs
* fix(chrome-extension): 解决CDP响应体获取和权限请求处理问题
* feat(mcp-chrome-integration): add MCP Chrome browser extension integration
Add complete Chrome extension with native messaging host for MCP integration:
- Chrome extension with sidepanel UI, service worker, and content script
- Native server with agent engines (Claude/Codex), session management, and tool bridge
- Shared packages for types, tools, and node specifications
- Documentation and build scripts
Co-Authored-By: Claude Opus 4.5 <[email protected]>
* chore(mcp-chrome-integration): refactor
* feat(chrome-extension): 切换到HTTP后端代理并更新构建配置
* refactor(mcp-chrome-integration): build
* wip
* wip chrome extension
* chore: ignore .worktrees
* docs: plan sidepanel component removal
* refactor(sidepanel): remove local components
* feat(chrome-extension): add native messaging ACP client and protocol support
- Add ACP client for native messaging communication
- Add file handler for local file access via native host
- Add protocol definitions for ACP communication
- Archive old documentation files
- Update integration status and protocol documentation
* fix(chrome-extension): use GenericToolCall from @qwen-code/webui
- Replace non-existent local ToolCallCard import with GenericToolCall
- Import from @qwen-code/webui package instead of local path
- Fix component props to match GenericToolCall interface
- Remove unused ToolCallData import
* refactor(mcp-chrome-integration): split large files and fix ESLint errors
- Split tools.ts (1554 lines) into 8 schema files by functionality
- Split native-messaging.ts (1533 lines) into 6 modules
- Split doctor.ts (1099 lines) into 8 modules
- Split content-script.ts (1055 lines) into 5 modules
- Add Qwen Team license headers to all new files
- Remove unused tool names (SEARCH_TABS_CONTENT, SEND_COMMAND_TO_INJECT_SCRIPT, USERSCRIPT, RECORD_REPLAY)
- Fix ESLint errors: no-require-imports, no-explicit-any, no-unused-vars, prefer-const
- Add archive/ directory to eslint ignore patterns
* 调试 MCP 工具成功
* refactor: revert unnecessary formatting changes and clean up MCP chrome-integration
- Revert Node version requirement from >=22 to >=20
- Revert code formatting changes (import statements and indentation)
- Archive obsolete chrome-extension implementation
- Clean up outdated documentation and scripts
- Reorganize MCP chrome-integration docs
* docs(mcp-chrome): 新增核心文档和更新 README
- 新增 02-features-and-architecture.md (27个工具完整参考)
- 新增 03-design-and-implementation.md (与 hangwin/mcp-chrome 对比)
- 新增 04-test-cases.md (35个测试用例)
- 更新 01-installation-guide.md (Extension ID 固定方案)
- 重写 README.md (对齐新文档结构)
* refactor(chrome-extension): 简化 sidepanel 并移除未使用代码
- 删除未使用的 Onboarding 组件
- 删除冗余样式文件 (App.css, timeline.css)
- 删除未使用的工具函数 (diffStats, diffUtils, sessionGrouping, tempFileManager, webviewUtils)
- 新增 MCP 工具状态横幅显示
- 隐藏不需要的 UI 按钮 (slash command, attach, edit mode)
- 移除未使用的变量 (clearToolCalls)
- 更新 manifest.json 和 native-messaging-host
* chore: regenerate lockfile for mcp-chrome-integration workspace
npm install reconciles the lock with the merged package.json: adds the
new packages/mcp-chrome-integration/app/* workspace subtree (371 deps).
No existing main dependencies were removed.
* chore(chrome-integration): drop dead logger + unused pino deps
native-server/src/util/logger.ts was 100% commented-out dead code (even
a hardcoded /Users/hang/... path) with zero importers; pino/pino-pretty
were declared but never imported (logging is console.error to stderr,
correct for a native-messaging host). Remove the file and both deps.
* feat(chrome-integration): WIP serve-backed agent client (Phase 1 backbone)
Replace the hand-rolled ACP client by driving `qwen serve` (main's
maintained HTTP daemon) through the SDK's DaemonClient. New
serve-agent/client.ts spawns `qwen serve --no-web` where the host used to
spawn `qwen --acp`, then uses DaemonClient (REST + SSE) for session
create / prompt / cancel / permission / streaming. Same public surface as
AcpClient so the native host can swap in place.
Compiles + typechecks against the real SDK API. NOT yet wired into
native-messaging-host.ts — wiring is gated on two items that need runtime
validation in a real Chrome + qwen env:
- OAuth: host's onAuthenticateUpdate (in-extension authUri) maps to
serve's server-side device-flow events — needs design.
- permission requestId becomes string (was number) — host's
permissionRequests map + handler need to follow.
acp/ kept in place until the serve path is validated. Packaging follow-up:
@qwen-code/sdk (→ core) as a dep of the standalone host is fine in the
monorepo but needs a publish-time story (bundle or resolve from the
co-installed qwen).
* feat(browser-ext): daemon-direct connection foundation (Phase 1, #5626)
First brick of the daemon-direct architecture from #5626: the extension
talks straight to a local `qwen serve` HTTP daemon instead of a native
messaging host.
- daemon/config.ts: resolve { baseUrl, token } — default loopback
http://127.0.0.1:4170 (auth-free), overridable via chrome.storage.local.
- daemon/discovery.ts: GET /health probe so the side panel can show a
"start qwen serve" hint instead of a broken chat when no daemon is up.
Both typecheck clean. (Pre-existing tsc errors live only in the orphaned
legacy sidepanel hooks — useWebViewMessages/useToolCalls etc. — which the
DaemonSessionProvider migration removes next.)
* docs(browser-ext): daemon-direct architecture spec (Phase 1+2, #5626)
Concrete implementation spec: Phase 1 (side panel as daemon client, no
daemon changes) and Phase 2 (browser tools as a client-hosted MCP server
over the daemon WS). Phase 2 reuses the existing SdkControlClientTransport /
SdkControlServerTransport pattern but moves the wire from the SDK subprocess
control plane onto qwen serve's WebSocket — a new public daemon-contract
surface, gated behind a capability flag (the open question in #5626).
Includes the daemon-lifecycle options for #5626 Q3.
* feat(browser-ext): Phase 1 — side panel as a daemon-direct client (#5626)
Side panel chat now talks straight to a local `qwen serve` HTTP daemon via
@qwen-code/webui's DaemonSessionProvider, replacing the native-messaging
relay (background/ + content/ untouched; nativeMessaging perm kept for now).
- SidePanelRoot.tsx: health gate — checkDaemonHealth(getDaemonConfig());
shows a "run qwen serve" hint + Retry when unreachable, else mounts
DaemonSessionProvider around App.
- App.tsx: rewritten daemon-driven — transcript/streaming/permissions/
lifecycle from the webui daemon hooks (useTranscriptBlocks, useStreamingState,
usePromptStatus, usePendingPermissions, useConnection, useActions); reuses
the existing webui presentational components + ChromePlatformProvider.
- sidepanel/daemon/{transcriptItems,permission}.ts: adapters from daemon
transcript/permission shapes to the existing UI components.
- Deleted the dead legacy native-messaging chat hooks/types.
Verified: sidepanel/daemon tsc clean; `npm run build` (esbuild) passes,
emits the side-panel bundle with the daemon wiring. (Pre-existing tsc errors
remain only in background/ + content/, out of scope until Phase 2.)
Daemon contract accepted live against the worktree `qwen serve`: /health,
/capabilities (advertises session_create/prompt/events/workspace_mcp),
POST /session runs end-to-end to the model-auth gate.
* feat(browser-ext): Phase 2 — browser tools over the daemon WS (#5626)
Reverse tool channel: a WS client (the extension) hosts an MCP server (its
browser tools) that the daemon's agent can call, carrying mcp_message
JSON-RPC frames over the daemon WS — reusing the SdkControlClientTransport /
SDK-MCP-server control-plane pattern. Gated behind capability flag
`client_mcp_over_ws` (opt-in; the public-contract piece flagged in #5626).
Daemon (core + cli/serve):
- core/tools/client-mcp-registrar.ts: ClientMcpRegistrar — id-correlation,
pending/timeout, notifications fire-and-forget, exposes the
sendSdkMcpMessage(server,msg) callback McpClientManager consumes.
- cli/serve/acp-http/client-mcp-ws.ts: ClientMcpWsConnection — handles
mcp_register/mcp_message/mcp_unregister frames; pushes mcp_message down the
WS; disposes on close. Hookup to the live agent McpClientManager is a
ClientMcpServerProvider injection point (returns structured `not_wired`
until the child↔parent reverse-IPC lands — see below).
- capability `client_mcp_over_ws` threaded through serve options/capabilities.
Extension (chrome-extension/background):
- browser-tools-server.ts: minimal hand-rolled MCP JSON-RPC
(initialize/tools/list/tools/call) reusing the existing tool-catalog +
router + executors (MVP 6 read-first tools); WS client to the daemon /acp
with mcp_register + reconnect. Wired into the service worker behind a
health probe; native messaging left intact.
Self-accepted (no LLM needed): 10/10 tests pass — a headless ws client
registers + answers the MCP handshake over mcp_message and the daemon
lists+CALLS the client-hosted chrome_read_page tool end-to-end over a real
socket. Builds: core + cli + extension esbuild all green; tsc clean.
NOT yet wired (out of scope here; needs acp-bridge + acpAgent reverse IPC):
the parent-process WS ↔ ACP-child McpClientManager hookup — the daemon's WS
lives in the parent serve process but sendSdkMcpMessage binds in the ACP
child. Single injection at the mountAcpHttp call site once that IPC exists.
* feat(serve): wire client-MCP-over-WS to the ACP child agent (#5626)
Closes the Phase 2 gap: a client-hosted (extension) MCP server's tool calls
now reach the agent's McpClientManager in the ACP CHILD, routed back to the
parent's ClientMcpRegistrar and out over the daemon WS. Opt-in via
QWEN_SERVE_CLIENT_MCP_OVER_WS=1 (the contract is still settling — dormant by
default; this is the public-daemon-contract piece flagged in #5626).
Contract additions:
- ACP ext-method `qwen/control/client_mcp/message` (child→parent, called UP):
{server,payload} → {payload}; notifications resolve with a synthetic ack.
- runtime-MCP config flag `__clientMcpOverWs`: parent stamps it on the SDK-type
add config; child KEEPS type:'sdk' (instead of stripping) so it binds an
SdkControlClientTransport instead of the SDK subprocess control plane.
- BridgeOptions.clientMcpSender seam + ServeAppDeps.clientMcpSenderRegistry.
Round-trip: mcp_register(WS) → serve registers the connection's
ClientMcpRegistrar.sendSdkMcpMessage in a process ClientMcpSenderRegistry +
bridge.addRuntimeMcpServer(type:'sdk',__clientMcpOverWs) → child adds the
SDK server + runs initialize/tools/list, each frame child→parent via
client_mcp/message → BridgeClient looks up the sender → registrar pushes
mcp_message down the WS → extension answers → child discovers the tools.
Self-accepted LIVE (no LLM): integration-tests/cli/qwen-serve-client-mcp.test.ts
spawns a REAL qwen serve + REAL qwen --acp child under a mock OpenAI server,
a headless ws client registers + answers the MCP handshake, and the child
discovers the client-hosted chrome_read_page tool over the genuine
child→parent→WS channel (GET /workspace/mcp/chrome-tools/tools lists it).
Verified passing locally (24.6s). +5 bridge round-trip tests; 324 acp-bridge,
the 10 prior Phase-2, acpAgent 133, server+acp-http 675 all pass; builds clean.
Not exercised here: a real LLM turn driving tools/call (needs creds), and a
real Chrome extension as the WS client (headless ws stands in).
* fix(serve): session-scope runtime MCP servers so client tool calls resolve (#5626)
The reverse tool channel registered the client-hosted MCP server only on the
bootstrap/workspace Config, so discovery worked but a prompt — which runs
against an independent per-session Config from newSessionConfig→loadCliConfig
— couldn't resolve the tool ("not found in registry"), and the reverse WS
channel was never reached. Spec (docs/05) intends per-session scope.
Fix (minimal, additive, guarded; normal settings-based MCP servers unaffected):
- core/config.ts: add Config.getRuntimeMcpServers() (shallow copy of the
private runtimeMcpServers map).
- acpAgent.ts newSessionConfig: copy the bootstrap Config's runtime MCP
servers into a newly-created session Config before initialize() so its
discovery binds that session's sendSdkMcpMessage (register-before-session).
- acpAgent.ts workspaceMcpRuntimeAdd/Remove: fan the add/remove out to every
active session's McpClientManager (register-after-session), best-effort.
Test: the fake model now emits the fully-qualified registered name
mcp__chrome-tools__chrome_read_page (what a real model is handed); the
reverse channel still forwards the bare tool name to the client server.
Verified LIVE (no LLM, no creds): integration test now drives the FULL loop —
model→agent→session-registry resolution→reverse client_mcp/message over the
daemon WS→headless ws client returns CallToolResult→agent consumes it (tool
completed)→turn_complete. 2/2 integration tests pass (confirmed locally).
Regression: config 248, acpAgent 133, mcp-client-manager 101, client-mcp-ws 5
pass; builds clean. (server.test.ts has 2 pre-existing Web-Shell flakes,
identical on the unmodified baseline.)
Still needs a real Chrome extension (vs the headless ws stand-in) + a real
model turn for true browser behavior; the protocol round-trip is proven.
* chore(browser-ext): remove the dead Native Messaging stack (#5626)
Daemon-direct made Native Messaging obsolete — the extension talks to
`qwen serve` directly (chat over HTTP+SSE, browser tools over the daemon WS),
so the entire native-host stack is dead weight. Deletes ~15.5k lines:
- packages/mcp-chrome-integration/app/native-server/ — the whole native host
(MCP servers, ACP client, Fastify server, doctor/register/report/postinstall,
the superseded serve-agent backbone).
- extension background transport: native-messaging.ts, native-connection.ts,
native-message-handler.ts, native-messaging-types.ts, ui-request-router.ts
(+ its test). The still-used executor types (BrowserToolArgs / RawNetworkRequest
/ WebSocketSession / NetworkCaptureState) move to background/browser-tool-types.ts.
- service-worker rewired to daemon-direct only (drops the NativeMessaging
init + the onMessage→routeUiRequest relay; keeps the browser-tools server start).
- esbuild.background.config.js drops the deleted native-messaging entry point.
- manifest.json drops the `nativeMessaging` permission.
- package.json scripts drop every native-server/native-host reference; dev-watch
no longer spawns the native host.
- obsolete native-messaging docs (01-04) + scripts (diagnose/install/update) removed;
README rewritten for daemon-direct.
Extension esbuild build green; tsc errors dropped (84 -> 69, all pre-existing
node:test/content typings). Daemon-side (cli/serve/core) untouched.
* chore(browser-ext): drop orphaned content-fetch-patch.ts (#5626)
* fix(serve): let browser extensions open the daemon WS reverse channel
The daemon-direct Chrome extension (#5626) connects to qwen serve's /acp
WebSocket to register its browser tools as a client-hosted MCP server.
Three gaps blocked the real-browser path. A node WS client in the
integration tests carries no browser Origin and completes the ACP
handshake, so none of these surfaced until a real Chrome connected:
- The WS CSRF check hard-coded loopback origins, so the extension's
chrome-extension://<id> Origin was rejected with 403. Wire the
existing --allow-origin allowlist into the WS upgrade check
(acp-http/index.ts, server.ts) with the same match semantics as the
REST allowOriginCors.
- parseAllowOriginPatterns rejected chrome-extension:// because its
URL.origin is the opaque "null". Rebuild the canonical origin from
scheme+host for opaque-origin schemes (auth.ts), with tests.
- The extension skipped the ACP initialize handshake and sent
mcp_register directly, tripping the daemon's 30s initialize timeout.
Send ACP initialize first and register only after the ack
(browser-tools-server.ts).
Also allow console.* in the extension package (no stdio in the MV3
runtime) via the eslint no-console allowlist.
Verified end-to-end against a real Chrome: the daemon agent calls
mcp__chrome-tools__chrome_read_page and reads the live active tab.
* docs(browser-ext): Plan C (CDP tunnel) feasibility + implementation design
Assess routing chrome-devtools-mcp's ready-made DevTools toolset through the
extension's chrome.debugger to drive the user's real browser, instead of
re-implementing each tool in the extension (Plan A). Records, with source
verification against [email protected] + [email protected]:
- the createCDPSession wall (why zero-change reuse fails — Target.attachToTarget
is "Not allowed" for chrome.debugger; cdp-mcp throws in McpContext.from);
- the patch-package fork shape (pin 1.4.0 + a ~2-site patch, not vendor/submodule);
- the daemon /cdp browser-level CDP emulation + sessionId routing design;
- minimal browser-level command set, reusable prior art (playwright-mcp
--extension), phased steps, risks, and the Plan A fallback.
Refs #5626.
* feat(serve): add CDP browser-level emulator for Plan C tunnel (#5626)
First component of the Plan C "CDP tunnel": a synthesis layer that fakes the
browser-level CDP topology so an external puppeteer client (chrome-devtools-mcp)
can connect over a future /cdp endpoint while page-domain commands are forwarded
to the one real tab via the extension's chrome.debugger.
Implements the exact contract a Phase 0 spike proved necessary: a tab->page
two-level target tree + recursive Target.setAutoAttach (browser attaches the tab
session; the tab session attaches the page session), with page-session commands
routed to forwardToTab and tab events re-tagged with the page session id. The
spike connected real puppeteer to a pure synthesis layer and ran
page.evaluate(() => 1 + 1) === 2. 7 unit tests cover the handshake + routing.
Refs #5626.
* feat(serve): add CDP tunnel reverse-link, /cdp glue, and bridge registry (#5626)
Plan C Phase 1 daemon core. The reverse-link forwards page-domain CDP
commands to the extension over cdp_command/cdp_result frames (id-correlated,
timeout) and re-tags cdp_event onto the page session; cdp-ws wires a per-
puppeteer-connection emulator to the reverse-link bound to the single active
extension bridge in a process-scoped registry. The emulator gains setTabInfo
so the synthetic targetInfo reflects the real tab after cdp_attach.
* feat(serve): wire /cdp upgrade branch and cdpTunnelOverWs flag (#5626)
Adds the /cdp WebSocket upgrade branch to acp-http (reusing the loopback /
host-allowlist / auth / CSRF checks) and routes inbound cdp_* frames on the
extension's /acp socket to the bound reverse-link. The extension connection
registers as the active CDP bridge eagerly at ACP initialize so a /cdp
puppeteer client can bind immediately (avoids the attach chicken-and-egg).
Feature flag cdpTunnelOverWs is wired exactly like clientMcpOverWs
(env QWEN_SERVE_CDP_TUNNEL_OVER_WS=1, capability cdp_tunnel_over_ws),
DEFAULT OFF — existing behaviour is unchanged when off.
* feat(browser-ext): add CDP bridge over the reverse /acp socket (#5626)
The extension answers cdp_attach by attaching chrome.debugger to the active
tab and cdp_command via chrome.debugger.sendCommand, replying cdp_result;
chrome.debugger.onEvent -> cdp_event, onDetach -> cdp_detach. Reuses the
existing browser-tools-server /acp socket (routes cdp_* frames; tears the
bridge down on socket close) and mutually excludes with the
chrome_network_debugger_* tools (one debugger per tab).
* build(deps): pin chrome-devtools-mcp 1.4.0 + puppeteer-core 25.2.0, patch McpContext (#5626)
Pins the two CDP-tunnel client deps (exact, to keep the version-specific
patch and puppeteer's hardcoded ExtensionTransport topology stable) and adds
patches/chrome-devtools-mcp+1.4.0.patch. The patch wraps McpContext.#init's
devtoolsUniverseManager.init / serviceWorkerConsoleCollector.init in try/catch
so the createCDPSession wall (Target.attachToTarget -> -32000 over
chrome.debugger) no longer crashes the server on startup; only performance_* /
service-worker console degrade. Applied via the existing postinstall
patch-package hook (same form as patches/ink+7.0.3.patch).
* test(serve): add Plan C /cdp end-to-end acceptance harness (#5626)
Node script that starts the real daemon with the flag on, connects a mock
extension over /acp (ACP initialize + mcp_register, answering cdp_command with
page-domain CDP), then puppeteer.connect to /cdp and asserts
page.evaluate(() => 1 + 1) === 2 through the real daemon + emulator +
reverse-link. Allowlists the harness dir in eslint's node-script globals.
* fix(serve): gate CDP page commands behind attach completion (#5626)
Real-Chrome testing surfaced an ordering race the mock acceptance missed: the
extension's chrome.debugger.attach is async (it pops the debugger banner), but
forwardToTab forwarded page-domain commands immediately, so a fast puppeteer
Network.enable reached the extension before attachedTabId was set and failed
"CDP tunnel not attached to a tab". The mock extension acked attach
synchronously, which hid the race.
Add an attach gate in CdpReverseLink: forwardToTab awaits the in-flight
cdp_attach to settle (success or failure) before forwarding. Verified
end-to-end against REAL Chrome — puppeteer read the live active tab (a GitHub
PR page) through the tunnel: pages=1, real url/title/body returned.
Refs #5626.
* refactor(chrome-extension): delete Plan A side panel, content scripts, and reverse tool channel
Tears out the superseded Plan A surface so the extension can become a pure
CDP-tunnel pipe (chat moves to the daemon web UI, browser tooling runs as
chrome-devtools-mcp over the /cdp tunnel):
- src/sidepanel/ (side-panel chat UI)
- src/content/ (content scripts; the CDP tunnel drives DOM/Input via
chrome.debugger, no injection needed)
- background reverse tool channel: browser-tools-server, browser-network-tools,
network-capture-utils, browser-tool-executors, tool-catalog, tool-router,
mcp-tool-result, browser-tool-types, and their tests
- public/sidepanel/sidepanel.html static asset
Refs #5626
* refactor(chrome-extension): rewrite service worker as minimal daemon CDP client
The service worker is now the entire extension logic: probe the daemon /health,
open the /acp WebSocket, send the ACP initialize handshake (the daemon closes
the socket on a 30s init timeout otherwise and binds this connection as the CDP
bridge at that point), then route cdp_* frames into the CDP bridge with capped
backoff reconnect. No more reverse MCP tool server (chrome-tools is gone).
cdp-bridge: drop the browser-network-tools import and the network-capture
mutual-exclusion branch in handleAttach (the network tools are deleted, nothing
to exclude); remove the now-unused isCdpTunnelAttached export.
Refs #5626
* build(chrome-extension): trim manifest, build config, and deps to the CDP pipe
manifest: drop content_scripts, side_panel, and the sidePanel/webRequest/cookies/
scripting/webNavigation permissions; keep only debugger/tabs/activeTab/storage
plus background, key, host_permissions, icons, and action.
build: background esbuild now has a single service-worker entry point (content
script gone); delete the UI esbuild/postcss/tailwind configs and drop the UI
build step + build:ui scripts; sync-extension no longer special-cases the gone
sidepanel assets; dev-watch no longer spawns the UI watcher.
deps: remove the side-panel-only deps (@qwen-code/webui, react, react-dom,
markdown-it, and the @types + the postcss/tailwind/autoprefixer CSS toolchain).
Refs #5626
* chore(chrome-extension): drop dead externally_connectable hook (#5626)
* test(serve): add real-Chrome /cdp local verification script (#5626)
* test(serve): add cdp-mcp-over-tunnel layer-C smoke check
* fix(extension): keep the CDP tunnel alive with chrome.alarms
MV3 service workers idle out after ~30s, so the tunnel silently dropped
whenever no puppeteer client was driving it and the user had to keep the
Service Worker DevTools open to hold the worker awake. Register a 30s
chrome.alarms keepalive: the recurring onAlarm dispatch holds the idle
timer off, and each wake of a terminated worker re-runs the top level to
reconnect.
* feat(serve): auto-register chrome-devtools-mcp over the CDP tunnel
Plan C (#5626) last mile: when `qwen serve` runs with the CDP-tunnel flag,
the agent should be able to drive the user's real browser. Rather than
hand-writing browser tools, auto-register the (patched) chrome-devtools-mcp
as a session MCP server pointed at this daemon's /cdp endpoint, so its 29
ready-made DevTools tools flow through the tunnel.
- run-qwen-serve: forward QWEN_SERVE_CDP_TUNNEL_OVER_WS + _PORT into the
spawned ACP child via childEnvOverrides (same path as the MCP budget env).
- acpAgent: buildCdpTunnelMcpServer() injects the server into the
top-precedence sessionMcpServers tier when the flag + port are present and
the package resolves; trust left unset so tools default to 'ask' (no silent
auto-approval of browser control); best-effort skip otherwise.
No settings.json edit and no hand-written tools required.
* fix(serve): gate CDP bridge registration to the extension (#5626)
Auto-registering every /acp initialize as the CDP bridge was last-writer-
wins. Once an ACP agent connects over the same /acp endpoint (web UI, Zed),
it would capture the bridge and receive cdp_* frames it can't answer,
stealing the tunnel from the extension. Gate registration on
clientInfo.name === 'qwen-cdp-bridge'; the extension (and the acceptance
mock) now identify themselves that way, while agent clients are left alone.
* feat(extension): open the web UI when the toolbar icon is clicked
The extension has no UI of its own (pure CDP-tunnel pipe; chat lives in the
daemon web UI), so clicking the toolbar icon did nothing after the side panel
was removed. Wire action.onClicked to open the daemon baseUrl in a new tab so
the icon is a useful entry point instead of a dead click.
* feat: host the web UI in a Chrome side panel (#5626)
The extension is a pure CDP-tunnel pipe with no UI of its own, so after the
side panel chat was removed the toolbar icon did nothing. Bring the side panel
back as a thin host that iframes the daemon web UI (chat + tools), so the
sidebar is the everyday entry point and reuses the web UI's pages/components
instead of shipping a second UI in the extension.
- extension: side_panel + sidePanel permission; sidepanel.html/js frames the
daemon baseUrl; toolbar icon opens the panel (openPanelOnActionClick).
- daemon: the Web Shell sent frame-ancestors 'none' + X-Frame-Options: DENY,
which blocked the iframe. Allow framing only for chrome-extension origins
explicitly passed via --allow-origin; everything else still gets DENY.
* fix: prefer chrome-devtools over computer-use under the CDP tunnel + keep MV3 worker alive during attach (#5626)
Two issues surfaced driving the real agent:
1. The agent picked the OS-level computer-use tool (cua-driver) for browser
tasks instead of the injected chrome-devtools-mcp — heavyweight screenshot/
click loop that pegged a CPU and stalled turns. Disable computerUse when the
CDP tunnel flag is on so browser automation goes through the tunnel.
2. The extension's MV3 service worker idled out *between* CDP commands (the
agent pauses to think), detaching chrome.debugger and hanging the next
command. Add a sub-30s keepalive while attached; the 30s alarm only covered
idle reconnects, not in-flight attachments.
* chore(extension): stop tracking .extension-key.pem (signing private key)
The extension signing private key was committed and pushed — anyone with repo
access could impersonate the extension. Stop tracking it and gitignore *.pem.
Load-unpacked debugging needs only the public "key" in manifest.json, so this
doesn't affect dev on any machine; the .pem is kept locally for packaging.
* refactor(chrome-extension): flatten to packages/chrome-extension
Drop the mcp-chrome-integration wrapper + dead native-server (daemon-direct
no longer uses native messaging). The extension is now a top-level workspace
at packages/chrome-extension. Updated root workspaces, eslint globs, doc-path
comments, and the two node scripts' global directives. cli + extension builds
and eslint verified green.
* test(serve): assert cdp_tunnel_over_ws in the capability registry
The cdp_tunnel_over_ws capability was added to SERVE_CAPABILITY_REGISTRY +
CONDITIONAL_SERVE_FEATURES but the test's EXPECTED_REGISTERED_FEATURES and the
conditional drift-insurance branch weren't updated, failing 3 registry tests.
Add it to the expected list (after client_mcp_over_ws, matching registry order)
and add its assertion branch (predicate accepts/rejects the cdpTunnelOverWsEnabled
toggle).
* fix(serve): address review comments on CDP tunnel + client-MCP wiring (#5777)
- guard post-async ws.send() with readyState OPEN (daemon crash on extension
disconnect, sendClientMcpAck + cdp endpoint sends)
- make client-mcp-sender-registry delete() ownership-aware (cross-connection
server-name collision)
- type the __clientMcpOverWs runtime config flag carrier
- document the CDP tunnel trust model (loopback + bridge-gated dumb pipe)
* chore(cdp-tunnel): set copyright year to 2026 on files created this year
The Plan C / #5626 files were authored in 2026 but carried a 2025 header.
service-worker.ts (created last year under #1432) keeps 2025.
* feat(chrome-ext): add side-panel onboarding gate + fix packaging
The side panel framed the daemon Web Shell unconditionally and showed a
static "Connecting…" line. When no daemon was reachable, or the daemon
wasn't started with --allow-origin (so frame-ancestors blocks the iframe),
the user was stuck on "Connecting…" with no guidance, and discovery.ts's
health check was never wired in.
Wire a health/capabilities gate into the panel:
- probe GET /health, then GET /capabilities
- down → "Start qwen serve" + the exact command
- up but no `allow_origin` feat → "Allow this extension" + the command
- ready → frame the Web Shell
The command is built from chrome.runtime.id at runtime, so it always names
this extension's real origin (dev-unpacked or published) — no need to know
or hardcode the id, and no publish-first chicken-and-egg. The pure decision
helpers live in onboarding-logic.js.
Also:
- fix `npm run package` so manifest.json sits at the zip root (the old
`zip ... extension/` nested it under extension/, which the Chrome Web
Store rejects)
- gitignore that packaging zip; add a package README
Part of #5626. PR #5777.
* docs(cdp-tunnel): trim over-long Plan C comments (ponytail)
Comment-only: compress multi-paragraph design rationale to intent, keep the
non-obvious why (trust model, bridge gate, attach ordering) + ponytail
ceilings. ~-91 lines, no code touched, build + tests green.
* fix(serve): address second-round review comments on the CDP tunnel (#5777)
- close the bound /cdp puppeteer socket on extension disconnect (was hanging
~170s on CDP timeout) via an onExtensionGone hook
- reject a 2nd concurrent /cdp client instead of silently clobbering routeInbound
- narrow extension host_permissions from <all_urls> to localhost (chrome.debugger
needs no host perm; only the /health fetch needs localhost)
- log safeWsSend drops under serve debug mode so a dead tunnel is diagnosable
* feat(chrome-ext): polish side-panel welcome into a terminal console
Replace the bare welcome with a console that matches the product (a CLI
daemon): the command is the hero, typed at a `$` prompt with a blinking
cursor inside a titled terminal card. Warm-charcoal / electric-lime,
light + dark aware (prefers-color-scheme), staggered load-in, a pulsing
"listening" status, and a reduced-motion guard. No web fonts / no inline
JS (the extension CSP allows neither).
No behavior change: same /health + /capabilities gate and the
chrome.runtime.id-derived command. Mechanics tidied alongside the markup:
visibility toggles a .hidden class (CSS owns the flex layout), the copy
button updates a label span, and the command is prefilled synchronously
so first paint isn't an empty prompt.
PR #5777.
* feat(chrome-ext): click-to-copy command + centered copy button
Make the onboarding command easier to grab: the whole command row is now
click-to-copy (keyboard-reachable, Enter/Space), and a centered "Copy
command" button sits at the foot of the terminal card. Both flash a
check-mark "Copied" confirmation; the small top-bar button is gone.
No gate-logic change. PR #5777.
* test(serve): cover CDP-tunnel + client-MCP regression guards
Add the four focused unit tests flagged in review for load-bearing
reverse-channel paths that had no coverage:
- ClientMcpSenderRegistry: ownership-scoped delete — a disconnecting
connection must not remove an entry a peer re-registered under the
same name.
- CdpTunnelRegistry: register/supersede/unregister lifecycle, inbound
routing delegation, onExtensionGone-on-disconnect, and the
stale-unregister guard that must not evict a newer active bridge.
- CdpReverseLink: a forwarded command rejects when its per-command
timer expires (not just on bulk dispose).
- safeWsSend: drops (no send, no throw) on a CLOSED/CLOSING socket.
safeWsSend is extracted from acp-http/index.ts into its own module so
it's unit-testable in isolation; behavior unchanged.
PR #5777.
* fix(serve): address bot code-review findings on the CDP tunnel (#5777)
- cdp-bridge: tear down listeners before re-attach (was double-registering →
duplicate cdp_event frames corrupting puppeteer)
- emulator: return a CDP error for an unknown session instead of fake success
- registry: notify the superseded bridge so the old /cdp closes (single-puppeteer)
- deps: move chrome-devtools-mcp + puppeteer-core to optionalDependencies (~26MB)
- tests: entry-script validation, deliverClientMcpMessage error branches,
registry supersede
* fix(chrome-ext): revert side panel to welcome when the daemon stops
Once the panel framed the Web Shell it stopped probing, so if the daemon
later went away the iframe was left showing Chrome's localhost
connection-refused page with no way back. Keep probing after framing and,
after a short tolerance (2 misses, ~5s, so a transient blip doesn't nuke a
live chat), clear the iframe src and show the welcome screen again.
PR #5777.
* fix(chrome-ext,serve): address review comments on the CDP tunnel
- service-worker: redact the bearer token from the connect log, and guard
connect() against a still-CONNECTING socket so a rapid reconnect can't
orphan an in-flight handshake.
- acpAgent: don't clobber a user-configured `chrome-devtools` MCP server
with the tunnel auto-wire.
- cdp-reverse-link: log dropped/unexpected inbound frames via an optional
diagnostic sink instead of swallowing them silently.
- name the cross-package `qwen-cdp-bridge` client-name constant on both
sides instead of repeating the bare string.
PR #5777.
* refactor(chrome-ext): inline onboarding helpers, drop dead pollTimer
onboarding-logic.js was a 65-line file (mostly JSDoc) for three trivial
helpers and a constant, split out "for testability" that was never used.
Fold them into sidepanel.js (decideState collapses into probeState's
return; resolveBaseUrl/allowOriginCommand become a one-liner each) and
delete the file + its import.
Also drop `pollTimer`: the welcome-fallback change made it write-only (the
only clearInterval was removed), which trips no-unused-vars.
PR #5777.
* fix(serve,chrome-ext): more CDP-tunnel review fixes
- sidepanel: pass the bearer token through the Web Shell URL fragment so a
token-gated daemon doesn't 401 every framed request.
- server: throw if deps.bridge is injected without deps.clientMcpSenderRegistry
(the bridge is already wired to its own sender; a fresh one would be orphaned).
- cdp-browser-emulator: surface unhandled browser-level CDP commands via an
optional log sink (keep the empty-result ack, with a TODO).
- cdp-bridge: only treat "already attached" as ours when attachedTabId === tabId
(a foreign DevTools owner now errors), and detach the previous tab on switch
so Chrome drops its debug banner.
- build.js: add packages/chrome-extension to the build order so root build
exercises the extension bundle.
PR #5777.
* fix(serve,chrome-ext): harden CDP-tunnel + client-MCP reverse channel
- client-mcp-ws: cap registered servers per connection (max 10) and re-check
`disposed` after the provider round-trip so a WS close mid-register can't
leave a zombie server; add registrar serverCount().
- acp-http: rate-limit client-MCP frames (mcp_register/unregister at the
mutation tier, mcp_message at read) and cap concurrent fire-and-forget
register/unregister dispatch (max 8) to stop DoS amplification.
- cdp tunnel: on /cdp puppeteer disconnect send a `cdp_release` frame so the
extension detaches chrome.debugger instead of leaving the tab's debug banner
up until /acp dies.
- acpAgent: skip chrome-devtools auto-registration (with a diagnostic) when the
/cdp tunnel requires bearer auth — the ACP child can't authenticate to it.
PR #5777.
* fix(chrome-ext,serve): address second-round CDP-tunnel review
- service-worker: only the *active* socket's close tears down the bridge — a
stale daemon-forced close must not detach the new connection's debugger.
- daemon config + sidepanel: fail closed on a non-loopback baseUrl so a tampered
chrome.storage value can't exfiltrate the bearer token off-host (background
fetch/WS bypass host_permissions).
- sidepanel: reentrancy guard on tick() so overlapping slow probes don't burn
the framed-miss tolerance and flash the welcome screen mid-chat.
- cdp-bridge: reentrancy guard on handleAttach so overlapping cdp_attach frames
can't interleave teardown and corrupt attachedTabId.
- add cdp-ws.test.ts: regression cover for no-bridge reject, second-client
reject, onExtensionGone fail-fast, cdp_release on dispose, and the
superseded-bridge cleanup guard.
PR #5777.
* fix(serve,webui): address third-round CDP-tunnel review
- safe-ws-send: wrap the debug-mode writeStderrLine in try/catch so a broken
stderr (EPIPE on a piped/closed log) can't break the "never throw on a dead
socket" contract production callers rely on.
- ChromeToolCall: index-access rawInput['name'] to satisfy
noPropertyAccessFromIndexSignature.
PR #5777.
* fix(serve,chrome-ext): address #5777 review round 4
- acp-http: send mcp_error back on an unexpected client-MCP handler rejection
(register/unregister callers otherwise hang); log when the inflight cap rejects.
- cdp-ws: log the happy-path cdp_release dispatch for oncall tracing.
- run-qwen-serve/acpAgent: don't pass a bogus "0" CDP-tunnel port for ephemeral
--port 0, and emit a stderr diagnostic when the tunnel is disabled for a
missing/invalid port instead of failing silently.
- cdp-bridge: handle a cdp_release that races an in-flight handleAttach so a late
attach can't leave a debugger attachment with no live /cdp client.
- service-worker: close the WS on an ACP initialize error so the daemon doesn't
keep holding a non-functional CDP bridge.
* fix(serve,chrome-ext): address pr-review findings (#5777)
- client-mcp-sender-registry: gate the child-side runtime-server teardown on
ownership too (Config.removeRuntimeMcpServer is not owner-scoped), so a
disconnecting connection can't kill a server a later connection re-registered
under the same name. (P2)
- service-worker: carry the bearer token via the `qwen-bearer.*` WS subprotocol
(matching the web-shell + daemon decoder) instead of a `?token=` query the
daemon never reads, so a token-gated daemon no longer 401-reconnect-loops. (P3)
- run-qwen-serve: advertise client_mcp_over_ws / cdp_tunnel_over_ws in the
bootstrap /capabilities too, matching the runtime path. (P3)
* chore(webui): remove unused ChromeToolCall component (#5777)
ChromeToolCall was added in a debugging commit but is never wired into the
tool-call routing (getToolCallComponent) — there's no `chrome` tool kind and
the only references were barrel re-exports. Dead code; remove it.
* fix(serve,chrome-ext): address #5777 review round 5 (diagnostics)
- service-worker: log the WS close code/reason so failure modes aren't
indistinguishable (e.g. the daemon's 1011 "no extension connected").
- acpAgent: containment-check the resolved chrome-devtools-mcp bin path so a
malformed `bin` field can't escape the package dir.
- cdp-tunnel-registry: log when a new extension bridge supersedes a stale one.
* fix(chrome-ext,serve): address #5777 review round 6
- cdp-bridge: ack the attach (as an error) before tearing down on a
release-during-attach, so the daemon's reverse link doesn't hang ~170s
waiting for a cdp_attached that never arrives.
- acp-http: rename isFireAndForget -> dispatchOffQueue + clarify the comment;
register/unregister are dispatched off-queue but still expect a response ack,
so the name no longer reads as "no response."
* fix(serve,cli): address #5777 review round 7
- config: warn (stderr) when QWEN_SERVE_CDP_TUNNEL_OVER_WS overrides an explicit
tools.computerUse.enabled=true, so the effective config isn't a silent surprise.
- client-mcp-ws: document the intentional idempotency of handleUnregister.
- cdp-reverse-link: add tests for the attach gate — forwardToTab parks behind an
in-flight attach, the cdp_attach timer rejects, and the gate opens on timeout
so commands don't hang.
* fix(serve,core): address #5777 review round 8
- mcp-client: only treat the first stdio arg as a local entry script when
it is clearly a filesystem path. A bare includes('/') also matched scoped
npm package names (npx @scope/pkg), wrongly resolving them under the
workspace and throwing before the runner ran. Adds a regression test.
- client-mcp-sender-registry: reject shadowedSettings so a browser-hosted
WS client cannot shadow a user-configured MCP server name; roll back the
child-side add.
- cdp-ws: close the puppeteer socket when /cdp attach fails so dispose()
clears cdpBound/routeInbound, instead of a stuck tunnel until restart.
* fix(serve,chrome-ext): address #5777 review follow-ups
* fix(serve): satisfy CDP inbound frame guard typing
* fix(serve): address CDP tunnel review feedback
---------
Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: qwen-code-dev-bot <[email protected]>
Co-authored-by: Shaojin Wen <[email protected]>
* feat(voice): voice dictation with native capture, streaming, and biasing
Add voice dictation for the prompt input:
- /voice [hold|tap|off|status] command + general.voice.{enabled,mode,language,protocol} settings; push-to-talk via Space, /model --voice to pick the model
- Native microphone capture (@qwen-code/audio-capture, miniaudio N-API) with arecord/SoX fallback, silence auto-stop, cold-start warm-up, and macOS permission query
- Batch transcription via DashScope Qwen-ASR (OpenAI-compatible chat/completions + input_audio) with language + keyterm biasing and an echo guard
- Live streaming over the DashScope realtime WebSocket (fun-asr-realtime / paraformer-realtime-v2) with interim text and an input-level waveform, behind voice.protocol=dashscope-realtime
- Rich VoiceIndicator UI (state, level meter, live partial transcript)
- Cross-platform prebuilds via prebuildify + node-gyp-build and a CI matrix
Co-authored-by: Qwen-Coder <[email protected]>
* feat(cli): route voice ASR by model
* feat(cli): polish voice realtime parity
* ci: fix voice workflow checks
* fix(cli): address voice review blockers
* fix(cli): harden voice transcription failures
* fix(cli): address voice PR review blockers
* fix(cli): harden voice review follow-ups
* fix(voice): handle realtime review blockers
* fix(cli): add voice command i18n keys
* fix(cli): address voice review blockers
* fix(cli): address voice review follow-ups
* fix(voice): harden review edge cases
* fix(voice): address release and realtime review blockers
* fix(voice): address realtime suggestion followups
* fix(voice): handle realtime review followups
* fix(voice): address realtime review blockers
* fix(voice): address review feedback
* fix(voice): address recorder review feedback
* docs(voice): document ssrf guard boundary
* fix(voice): address review feedback
* fix(voice): preserve warm recorder session safety
* fix(voice): address stream review suggestions
* fix(voice): address multi-round review findings
Realtime/streaming:
- Salvage an already-committed transcript when the WebSocket closes right
after finish() instead of rejecting the whole dictation
(qwenAsrRealtimeSession, voiceStreamSession) + regression tests.
useVoiceInput state machine:
- Single-shot finalize guard so a tap-stop racing the silence auto-stop can't
double-stop the recorder and surface a spurious failure.
- Reset mountedRef on (re)mount so StrictMode (DEBUG) can't freeze the voice UI.
- Widen the hold-mode first-press release window above common key-repeat delays.
Model selection:
- Reject ids with no ASR transport at /model --voice and in the model dialog via
a new isSelectableVoiceModel; move resolveVoiceTransport into voiceModel so the
record-time config resolver stays transport-agnostic (+ tests).
macOS mic permission:
- Surface the not-determined state in voice warmup so the first dictation isn't
silently lost behind the TCC dialog.
Native packaging:
- Make the audio-capture native install non-fatal (falls back to SoX/arecord) so
a voice-only build failure can't break npm ci.
- Download audio-capture prebuilds before building standalone release archives.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(voice): address review blockers
* fix(voice): update batch recording audio level
* fix(voice): tap-mode transcript loss, stream leaks, and dead keyterm cleanup
- Tap-mode dictation submitted a stale empty buffer.text, wiping the just-
inserted transcript and sending nothing: thread the resulting prompt text
through onSubmit(text) instead of reading buffer.text back synchronously
after the async insert (useVoiceInput, InputPrompt).
- Streaming finalize leaked the WebSocket session when recorder.drain() threw:
abort the session before propagating the error.
- voiceStreamSession: reject the connect promise when 'task-finished' arrives
before 'task-started' instead of hanging forever in 'transcribing'.
- Remove dead keyterm enrichment (project/branch/recent-file paths were
unreachable after the privacy fix) and the now-inert CJK echo guard, plus the
tests that asserted that removed behavior; fix the misleading "OpenAI prompt
field" comment.
- Add the missing 'Voice Model' and macOS mic-permission i18n keys to
en/zh/zh-TW (they were falling back to English; check-i18n doesn't flag keys
absent from en).
Co-authored-by: Qwen-Coder <[email protected]>
* fix(voice): reject partial stream transcripts
* fix(cli): let dialogs consume voice keys first
* fix(voice): reject incomplete qwen realtime transcripts
* fix(voice): handle stream review blockers
* fix(voice): salvage qwen realtime transcript on close
* fix(voice): sanitize streamed transcript text
* test(audio): run audio capture tests in CI
* fix(voice): address review blockers
* fix(voice): report stream close while recording
* fix(voice): reduce keyterm echo false positives
* fix(voice): handle realtime close diagnostics
* fix(voice): address realtime review blockers
* fix(lint): allow legacy voice filenames
* chore(cli): rename voice files to kebab-case
---------
Co-authored-by: Qwen-Coder <[email protected]>
* feat(channel): add QQ Bot channel adapter
Add @qwen-code/channel-qqbot package implementing QQ Bot WebSocket
Gateway connection via the official QQ Bot API.
Supports:
- WebSocket Gateway (HELLO/IDENTIFY/HEARTBEAT/DISPATCH/RECONNECT)
- C2C single chat (C2C_MESSAGE_CREATE)
- Group @mention (GROUP_AT_MESSAGE_CREATE) — code path exists, unverified
- Streaming output via msg_id + msg_seq multi-block sending
- Auto-reconnect with exponential backoff
- Sandbox environment toggle
TODO (technical debt acknowledged):
- Group chat not verified end-to-end
- Single-file architecture (should split into gateway/send/auth modules
like weixin channel)
- No tests (weixin has send.test.ts + media.test.ts)
- No typing indicator (onPromptStart/onPromptEnd not yet implemented)
- No channel instructions injection in connect()
- No structured error types
Closes#5201
* feat(qqbot): add QR login, group chat support with typed events
- Add QR code login via @tencent-connect/qqbot-connector with credential persistence
- Add Intent constants for C2C (1<<12) and GROUP_AT_MESSAGE (1<<25)
- Use QQGroupMessageEvent type in handleGroup instead of cast
- Remove resolved TODO comments for group chat verification
- Add msg_seq to send error log for debugging
* fix(qqbot): address PR review — lint errors, token refresh, security
- Use bracket notation for Record<string, unknown> to fix TS4111 lint errors
- Add chmodSync(credsFile, 0o600) for credential file permissions
- Implement token refresh at 80% TTL with expires_in tracking
- Fix RECONNECT opcode: use code 4000 + serverRequestedReconnect flag
- Fix connect() Promise: reject on close before READY via connectReject
- Log empty-token case in sendMessage, drain response body on error
- Clear chatTypeMap/replyMsgId/msgSeqMap in disconnect()
- Capture msgId at send-time to avoid race on replyMsgId
- Switch channel-registry.ts to Promise.allSettled (isolated channel failures)
- Add chatId validation (isValidChatId) to prevent SSRF
* fix(qqbot): add qqbot to build order, fix ESLint default-case
- Add packages/channels/qqbot to scripts/build.js buildOrder
(CLI imports @qwen-code/channel-qqbot but it wasn't being built)
- Add default case to handleGatewayMessage switch
* feat(qqbot): prepend sender name in group messages for shared context
When sessionScope is set to 'thread', all group members share one
session. Prepending [senderName] helps the agent distinguish who
said what in the shared context.
* feat(qqbot): cross-server context continuation via SessionRouter persistence
- Persist SessionRouter mappings to disk via sessionsPath, surviving daemon restarts
- Persist QQ routing state (chatTypeMap, replyMsgId, msgSeqMap) to {name}-state.json
- Backup/restore global sessions.json on disconnect/connect to survive start.ts cleanup
- fixRestoredSessions() workaround for ACP LoadSessionResponse missing sessionId
- READY handler delays resolve() until restoreSessions() completes, preventing race
* feat(qqbot): add Session Resume + reconnect retry resilience
- Support WS session resume (RESUME opcode 6) on reconnect,
falling back to full IDENTIFY when session is invalid
- Add reconnectWithRetry() loop: retries gateway fetch up to 5x
with exponential backoff, then schedules 60s fallback retry
(fixes silent death after GW HTTP 500)
- connect() now retries up to 3 times on initial failure
- Bump maxReconnectAttempts from 10 to 20
- Refresh token before each reconnect attempt
* fix(qqbot): address review feedback from wenshao
- fixRestoredSessions: use entry.target directly instead of tt.get(undefined)
(fixes first restored session routing to wrong conversation when 2+ sessions)
- scheduleTokenRefresh: retry in 60s on token refresh failure, not just log
- sendMessage: move saveQQState() after chunk loop, avoid redundant disk I/O
- handleGroup: drop message when group_openid is missing instead of falling
back to author.id (which would cause 404 on group message send)
* fix(qqbot): address 3rd review from doudouOUC (12 issues)
- QWEN_HOME: use getGlobalQwenDir() instead of homedir()
- name sanitization: prevent path traversal in file paths
- fetch timeouts: AbortSignal.timeout(15s) on all 3 fetch calls
- TOCTOU: writeFileSync with {mode: 0o600} instead of chmodSync after
- msg_seq gaps: only increment seq on send success, break on failure
- message dedup: seenMessages Map with 5min TTL cleanup timer
- disconnect: set disposed flag + flushQQState sync + clear timers
- heartbeat ACK: track lastHeartbeatAck, force close on 2x interval timeout
- reconnect exhaustion: FATAL log when max attempts reached post-connect
- debounced saveQQState: 500ms debounce, flush on disconnect
- handleGroup: skip [senderName] prefix for slash commands, log for audit
- disposed guard: connectGateway checks disposed before creating WS
* fix(qqbot): robustness round — RESUMED, token expiry, SSRF, disposed, typing stubs
- Handle RESUMED event on RESUME success (start heartbeat, restore sessions)
- Check token expiry before sendMessage, refresh if expired
- Tighten isValidChatId regex (remove . and /) to close path traversal
- Reset disposed flag in connect() for reusability
- Add onPromptStart/onPromptEnd stubs (QQ Bot has no typing API)
- Add robustness comments for splitText surrogate pairs, restoreQQState
corruption, and senderId identity fragmentation across contexts
* refactor(qqbot): split into modules — api, accounts, login
Extract HTTP calls, credential I/O, and QR login into separate files
matching the weixin channel's architecture:
- api.ts: fetchAccessToken, fetchGatewayUrl, getApiBase, sendQQMessage
- accounts.ts: getCredsFilePath, loadCredentials, saveCredentials
- login.ts: qrCodeLogin (qrConnect wrapper)
QQChannel.ts drops inline fetch/credential/qrConnect logic and imports
from the new modules. Net -41 lines in the adapter.
* feat(qqbot): markdown message support (msg_type: 2)
Detect markdown syntax in AI responses and send as msg_type=2
with markdown.content field instead of plain-text msg_type=0.
Detection covers headers, code blocks, bold, italic, strikethrough,
inline code, links, and lists via a single regex.
* fix(qqbot): defensive patches from complete review
- reconnectWithRetry: guard against disposed channel to prevent infinite loop
- handleGroup: broaden @mention regex to match both legacy <@!id> and V2 <@openid>
- handleGroup: set isReplyToBot=true (every group msg is an @mention)
- fixRestoredSessions: document fragile private-field access
- saveCredentials: correct TOCTOU claim in comment
- hasMarkdownSyntax: document false-positive trade-off
* fix(qqbot): guard against empty content in C2C and group handlers
- handleC2C: return early when event.content is null/empty (image/sticker msgs)
- handleGroup: return early when cleanText is empty after @mention stripping
* fix(qqbot): close remaining review gaps — disposed guard, connectReject, token retry, RESUMED restore
* fix(qqbot): address wenshao review — RESUME restore removal, disposed guards, timer tracking, logging, heartbeat floor, requiredConfigFields, channel-registry error labels
* fix(qqbot): markdown fallback to plain text on rejection
* docs(qqbot): clarify markdown permission — Open Platform has no gate, FAQ is a different platform
* feat(qqbot): add Ark (msg_type=3) and Media (msg_type=7) message support
- types.ts: ArkKV, ArkPayload, FileType, MediaUploadRequest/Response, MediaPayload
- api.ts: uploadQQMedia() — file upload for rich media
- QQChannel.ts: sendArk(chatId, templateId, kv) + sendMedia(chatId, fileType, url, text?)
- C2C/group upload paths separated (file_info not interchangeable)
- file_type=4 (文件) blocked for groups per QQ API
- Embed (msg_type=4) skipped — QQ频道专用, not available for Bot Open Platform
* feat(qqbot): auto-route !ark / !media commands from LLM text via sendMessage
LLM outputs text — the channel now parses structured commands inline:
!ark(24, #TITLE#=标题, #META_DESC#=描述)
!media(image, https://example.com/photo.jpg, caption text)
parseArkCommand / parseMediaCommand extract at sendMessage entry;
normal text/markdown flow unchanged.
* feat(qqbot): inject channel instructions for ark/media commands
Sets config.instructions on connect() so the LLM learns about:
!ark(template_id, key=val, ...) — 3 default templates (23/24/37)
!media(type, url, [caption]) — image/video/voice/file
Fixes known debt: 'No channel instructions'.
* feat(qqbot): gate ark/media behind config flags (enableArk/enableMedia)
Both features default to false — opt-in via settings.json:
channels.my-qq.enableArk = true
channels.my-qq.enableMedia = true
Instructions injected conditionally; command routing gated per-flag.
* refactor(qqbot): extract resolveRoute() to eliminate duplication across sendMessage/sendArk/sendMedia
disposed check, token refresh, chatId validation, sandbox path selection
now in one place. All three methods call resolveRoute() instead of
repeating the same 15-line preamble.
* chore(qqbot): remove Ark and Media message support
Remove !ark() / !media() text parsing, sendArk/sendMedia methods,
uploadQQMedia, and all related types. The text-parsing approach
was too fragile against LLM output formatting. Only text/markdown
messaging remains.
* fix(qqbot): robustness patches for review findings
- Add { mode: 0o600 } to all writeFileSync calls (state/session files)
- Guard against stale WebSocket close event nuking new connection
- Add isReconnecting guard to prevent parallel reconnectWithRetry chains
- Reset isReconnecting flag in READY, RESUMED, and exhaustion paths
* docs(channel): add QQ Bot user documentation
Add user-facing documentation for the QQ Bot channel adapter:
- New docs/users/features/channels/qqbot.md covering setup, configuration,
QR code login, group chat, Markdown support, token management, connection
resilience, and troubleshooting
- Update docs/users/features/channels/_meta.ts to include QQ Bot in nav
- Update docs/users/features/channels/overview.md to reference QQ Bot
across the intro, quick start, type options, slash commands, and the
media platform differences table
* docs(qqbot): fix prerequisites — QR login needs no developer account
QR code login via qrConnect() does not require a developer account or
manual app registration. First qwen channel start is all you need.
* docs(qqbot): emphasize QR login, keep developer portal as secondary path
Both paths work (config → persisted file → QR scan), confirmed against
fetchToken() code. Reposition QR code login as the primary setup flow,
remove redundant tips/troubleshooting entries.
* docs(qqbot): remove Images and Files section — not supported in channel code
handleC2C/handleGroup both skip messages with no text content.
No media download or upload logic exists in this channel adapter.
* test(qqbot): add unit tests for send utilities
Add vitest test suite for QQ Bot channel following the weixin channel
testing patterns. Extract isValidChatId, hasMarkdownSyntax, and splitText
as exported module-level functions to enable direct testing.
- 27 tests covering: chatId SSRF validation, Markdown syntax detection, and
text chunking for QQ's 2000-char message limit
- Add vitest.config.ts and test script to qqbot package
- Register qqbot in root vitest workspace projects
Refs: #5202
* test(qqbot): add sendMessage flow tests with mocked API
Follow the weixin sendImage test pattern: mock sendQQMessage and
channel-base dependencies to test sendMessage end-to-end.
- C2C/group routing verification
- Markdown msg_type=2 vs plain text msg_type=0
- Markdown rejection fallback to plain text
- Disposed guard and error-stop behavior
- msg_id + msg_seq tracking for multi-chunk streaming
9 new tests, 36 total (all passing)
* test(qqbot): fix review issues — add missing edge cases
Self-review fixes:
- Fix misleading test name: 'returns early when chatId not in chatTypeMap'
→ 'defaults to C2C path for unknown chatId' (code doesn't return early)
- Add SSRF validation test: sendMessage rejects '../traversal' chatId
- Add network error test: thrown sendQQMessage caught by try/catch
- Add token expiration test: expired token + failed refresh → early return
- Hoist mockFetchAccessToken and set default resolved value in beforeEach
to prevent silent undefined-access failures in accidental token-refresh paths
39 tests, all passing
* test(qqbot): add api and accounts unit tests
Add api.test.ts (13 tests) and accounts.test.ts (8 tests) following
weixin channel vitest patterns: vi.hoisted() mocks, vi.mock() module
replacement, and dynamic import() after mock setup.
api.test.ts covers getApiBase, sendQQMessage, fetchAccessToken, and
fetchGatewayUrl — including HTTP errors, missing fields, and request
body format.
accounts.test.ts covers getCredsFilePath, loadCredentials (missing file,
corrupt JSON, missing fields, valid data), and saveCredentials (dir
creation + 0o600 permissions).
All 60 tests pass (39 existing + 21 new). tsc --build and eslint clean.
* chore(qqbot): suppress CodeQL ReDoS false positives
Add codeql[js/polynomial-redos] suppression comments for two
regexes flagged by CodeQL:
- hasMarkdownSyntax(): input is LLM-generated reply text,
never attacker-controlled in Qwen Code Channel context.
- handleGroup(): <@...> prefix is injected by QQ servers;
openid is assigned by QQ, not attacker-chosen.
Both paths have no practical exploit vector — an adversary
would need to either control an LLM's output or register a
malicious openid with QQ, neither of which is achievable.
* fix(qqbot): allow QR-code-only login and guard qrConnect return
- requiredConfigFields: [] — fetchToken() already resolves credentials
from config → persisted file → QR fallback chain. Blocking at config
validation prevented QR-code-only users from starting the channel.
- qrCodeLogin(): add bounds check for empty qrConnect() return value.
If the external library returns an empty array, throw descriptive
error instead of crashing with TypeError on creds.appId.
* chore(qqbot): add comments for requiredConfigFields and qrConnect guard
- index.ts: explain why requiredConfigFields is empty — fetchToken()
already resolves credentials via config → file → QR fallback chain.
Requiring appID/appSecret at config level would block QR-only users
from reaching the fallback through the built-in channel path.
- login.ts: clarify qrConnect() guard is a defensive robustness patch,
not a response to an observed failure. Verified by removing appID
from config and running qwen channel start — QR login triggers
correctly and returns valid credentials.
* fix(qqbot): replace quadratic regexes with linear patterns, remove failed suppress comments
* fix(qqbot): split hasMarkdownSyntax into individual tests to pass CodeQL
* fix(qqbot): replace markdown link regex with indexOf to eliminate CodeQL ReDoS
The desktop vendor step only needs the CLI bundle, but was building all
14 workspaces including webui, sdk, web-shell, and vscode-ide-companion.
This wasted ~30-40% of build time and triggered TS type errors in
vscode-ide-companion on newer Node.js versions.
Add a --cli-only flag to scripts/build.js that truncates the build
order after the CLI package. vendor-qwen-code.ts now passes this flag
when building from a local source checkout, so both local brand builds
and CI desktop-release (source_branch mode) benefit automatically.
* perf(core): F2 cleanup PR A — R9/W11/W12/R10 (post-merge follow-ups) (#4411)
* refactor(core): F2 PR A R9 — McpClientManager options-object ctor
R9 (filed as F2 follow-up from #4336 review): 7 positional ctor args
collapse to (config, toolRegistry, options?: McpClientManagerOptions).
The trailing 5 (eventEmitter, sendSdkMcpMessage, healthConfig,
budgetConfig, pool) become named fields on `McpClientManagerOptions`.
Test factory `mkManager(overrides?)` introduced at the top of
`mcp-client-manager.test.ts` so each of the prior 80 inline
constructions becomes a single line naming only the field(s) the test
overrides; the 4 `undefined` sentinels each test threaded through to
reach the trailing `pool` arg are gone.
Net: 113 LOC removed (test) + 35 LOC added (src exposes interface +
mkManager factory + tool-registry call site update). Behavior
unchanged — same field assignments, same downgrade-enforce-without-
budget breadcrumb, same budget event wiring.
Filed bucket: F2 perf / cleanup PR A (R9 + W11 + W12 + R10/R23 T7),
see issue #4175 item 7 "F2 post-merge cleanup PRs". This is the first
of the 4 fixes in PR A; W11/W12/R10 follow as separate commits.
Test sweep: 84/84 mcp-client-manager.test.ts pass; typecheck clean.
* refactor(core): F2 PR A W11 — extract attachPooledSession + rollbackReservationOnSpawnFailure
W11 (filed as F2 follow-up from #4336 review): two private helpers
on `McpTransportPool` to eliminate inline duplication in `acquire()`:
- `attachPooledSession(entry, id, serverName, cfg, sessionId,
toolReg, promptReg)`: builds `SessionMcpView` + `entry.attach`
with the standard pool release callback. Used by both the
fast-path attach (existing entry) and the post-spawn attach
(after `await inFlight`). NOT used by `createUnpooledConnection`
— its release callback runs `entry.forceShutdown('manual')` +
`indexDetach` directly (no pool refcount accounting since
unpooled entries are per-session).
- `rollbackReservationOnSpawnFailure(reservationResult, serverName)`:
R24 T17 contract — only release the budget slot if THIS acquire
actually reserved a new slot (`'reserved'`); `'already_held'`
skips because the sibling owns it. Used by both the unpooled
catch and the pooled spawn-in-flight catch.
Race-window invariants (W10 / W77 / W90 / W111 / W125 / R24 T17)
stay at the call sites because they describe the SURROUNDING
ordering, not the helpers themselves. Helpers are documented to
defer those decisions back to callers.
Behavior unchanged. Filed bucket: F2 perf cleanup PR A (R9 done /
W11 this commit / W12 + R10 to follow).
Test sweep: 28/28 mcp-transport-pool.test.ts pass; typecheck clean.
* refactor(core): F2 PR A W12 — SessionMcpView precompute filter Sets
W12 (filed as F2 follow-up from #4336 review): `applyTools` /
`applyPrompts` precompute `excludeSet` + `includeSet` once per pass
instead of scanning `cfg.includeTools` / `cfg.excludeTools` arrays
inside every per-tool iteration.
Pre-fix the per-tool predicate (`passesSessionFilter`) walked both
arrays for every snapshot entry → O(M × N) per `applyTools` call.
With M tools × N filter entries, typical M=5-20 / N=2-5 case
finishes in microseconds either way; the win is data-structure
correctness and code clarity, not perceived perf.
`passesSessionFilter` / `passesSessionPromptFilter` (the array-
based predicates) stay exported and unchanged for unit tests + any
caller wanting to test a single name without paying Set construction.
The bulk path uses two new private helpers `compileNameFilter` +
`compiledFilterAccepts` whose Sets live on the `applyTools` /
`applyPrompts` stack frame.
Same semantics: `excludeTools` is direct-equality match (no parens
strip — pre-F2 behavior preserved); `includeTools` strips the first
`(...)` suffix so `toolName(args)` matches `toolName`.
Filed bucket: F2 perf cleanup PR A (R9 + W11 done / W12 this commit
/ R10 to follow).
Test sweep: 13/13 session-mcp-view.test.ts pass; typecheck clean.
* perf(core): F2 PR A R10 / R23 T7 — pid-descendants ps snapshot + pgrep fallback
R10 / R23 T7 (filed as F2 follow-up from #4336 review): the Linux
/ macOS pid-descendant enumeration moves from per-pid `pgrep -P
<pid>` BFS (one subprocess fork per node visited) to a single
`ps -A -o pid=,ppid=` snapshot followed by an in-memory tree walk
over `Map<ppid, pid[]>`. Windows analog: single `Get-CimInstance
Win32_Process | ConvertTo-Csv` snapshot of all `(ProcessId,
ParentProcessId)` rows replaces per-pid
`Get-CimInstance -Filter "ParentProcessId=$p"` BFS.
Two motivations:
1. **Fork count**: typical `npx → tool` / `uvx → tool` wrapper
trees are 2-3 levels deep with B=1-3 children per node →
pre-fix BFS forked ~5-10 subprocesses per pool-shutdown call.
Post-fix: exactly 1 fork regardless of tree depth.
2. **Snapshot consistency**: pre-fix BFS walked the table level
by level; a child that forked between two adjacent BFS levels
could be missed (we'd see the child but query its
descendants AFTER the new fork). The snapshot path captures
the table at one instant; new descendants forked after the
snapshot are tolerated by the existing ESRCH-tolerant
SIGTERM loop.
Caveats:
- `ps -A -o pid=,ppid=` is POSIX standard (macOS / Linux /
*BSD), but BusyBox `ps` <v1.28 (2018) doesn't support `-o`.
Distroless containers may not have `ps` at all. To preserve
behavior on those edge platforms, the legacy per-pid `pgrep`
BFS is retained as a fallback (`listDescendantPidsUnixPgrepFallback`).
Same retention on Windows for the per-pid filter path.
- Snapshot path uses `maxBuffer: 8MB` to cover ~250k-process
pathological hosts. Default 1MB would clip at ~30k processes.
- `MAX_DESCENDANTS = 256` / `MAX_DEPTH = 8` caps preserved on
both snapshot + fallback paths.
- Snapshot scans the entire host process table (not just the
target subtree). On the typical 200-500 process developer
machine this parses in <10ms; the win over BFS is real but
not order-of-magnitude — ~2x improvement, not 100x. PR A's
motivation framing is "fork hygiene + consistency", not raw
perf.
Empty-result detection: snapshot path tracks `parsedRows`. If the
ps/CIM tool runs successfully but produces 0 parseable rows
(BusyBox without `-o` echoing usage, AppLocker truncating CIM
output, etc.), we throw — the outer catch falls back to the
per-pid path. A genuine "root has no children" case parses many
rows and just returns empty from the walk. So the
"no-children-found" semantics are preserved across both paths.
Test gate update: pre-fix `integration: spawn-and-enumerate` test
skipped on `CI === '1'` because pgrep wasn't available on
minimal CI runners. Post-fix `ps -A` is universally available on
non-distroless Linux/macOS — only the Windows skip remains.
6/6 pid-descendants tests pass including the now-active
integration spawn test.
Design doc (`docs/design/f2-mcp-transport-pool.md` §6.4 + the F2
follow-up table at lines 82-85) updated to reflect the snapshot
+ fallback shape, and to mark W11 / W12 / R9 / R10 as ✅ Done in
PR A with the per-fix commit refs.
This commit completes F2 cleanup PR A. Filed bucket order:
R9 (commit 0cb1eaa27) → W11 (commit 2d546efca) → W12 (commit
a4a855ab3) → R10 (this commit). Issue #4175 item 7 "F2 post-
merge cleanup PRs": PR A done; PR B (W93 + W133-a + W134) and
PR C (W133-c SDK breaking) to follow as separate clusters.
Test sweep: 287/287 F2 + cli pass; ESLint clean; typecheck clean
(core + cli). Integration test on macOS local runs the new
snapshot path successfully.
* refactor(core): F2 PR A R2 — wenshao followup (visited set + dedup predicate)
Two Suggestions from wenshao's first PR #4411 review pass (07:15Z),
both small and worth folding before merge:
PR-A-R2 #1 (pid-descendants.ts:309 — walkDescendants visited set):
`walkDescendants`'s BFS lacked a `visited` set. If the snapshot
captures a PID-reuse cycle — rare but possible on busy hosts with
rapid pid churn between `ps -A`'s start and parse, where Linux
wraparound can show a freed pid in a different parent's children
list creating an A→B / B→A cycle — pre-fix BFS would revisit nodes
and fill the MAX_DESCENDANTS=256 quota with duplicate entries,
starving legitimate descendants. Pre-PR-A the per-pid `pgrep` BFS
had the same theoretical issue but was less exposed (each
`pgrep -P pid` call returns only DIRECT children; snapshot captures
the whole tree at once, making cycles instantly visible).
Fix: 3-LOC `Set<number>` add. `root` seeded into `visited` so a
malformed snapshot listing root as a descendant of its own child
doesn't re-enqueue root either.
PR-A-R2 #2 (session-mcp-view.ts:117 — predicate dedup):
After W12, the exported `passesSessionFilter` /
`passesSessionPromptFilter` still called `passesNameFilter` (the
pre-W12 array-based implementation), while `applyTools` /
`applyPrompts` used `compiledFilterAccepts(compileNameFilter(...))`.
Two parallel implementations of the same predicate — future change
to one without the other would silently diverge:
- the exported function's tests (passesSessionFilter unit tests)
would still pass
- the production filter path in applyTools/applyPrompts would
behave differently
Reviewer also noted `passesSessionPromptFilter` had zero callers
in production code or tests after W12 — `applyPrompts` no longer
references it. Kept the export rather than deleting it (matches
the `passesSessionFilter` shape for symmetry + the F3 audit-path
comment block earmarks both as the replay predicates), but routed
both through `compiledFilterAccepts(compileNameFilter(...))` so
there is a single source of truth. Set construction is per-call
for these exports (negligible for unit-test / one-off probes);
the bulk paths in `applyTools` / `applyPrompts` still construct
ONE filter per pass via the original W12 code path.
`passesNameFilter` (the standalone array-based helper) deleted —
its only callers were the two exports, which now use the compiled
path. Public-API surface unchanged: the two exported functions
keep their signatures and semantics.
Test sweep: 19/19 pid-descendants + session-mcp-view tests pass;
typecheck + ESLint clean.
Continues commit chain: f05917071 (R9) → 20d2f1b90 (W11) →
6cf18f641 (W12) → 2a41c6fae (R10) → this (R2 followups).
* fix(core): F2 PR A R3 T3 — Windows CSV delimiter locale fix
`ConvertTo-Csv -NoTypeInformation` honors the system locale's list
separator on PowerShell 5.1. On German / French / Dutch / Italian /
... locales the separator is `;` not `,`, so the regex
`^"(\d+)","(\d+)"$` in `snapshotProcessTreeWin` never matched →
`parsedRows === 0` → snapshot threw → fell back to the per-pid CIM
filter path with ~0.5-1s extra PowerShell startup latency per
descendant on every pool shutdown.
Fix: 1-LOC `-Delimiter ","` on `ConvertTo-Csv`. Forces comma
regardless of locale or PowerShell version. PowerShell 7+ defaults
to comma already; 5.1 (the Windows-bundled version most users have
without explicit upgrade) honored locale. The explicit delimiter
makes both consistent.
Skipped wenshao's companion Suggestion T4 (test coverage for
walkDescendants MAX_DESCENDANTS / MAX_DEPTH caps) as F2 hardening
follow-up — the caps are simple 2-line guards exercisable by
inspection; ~50 LOC of mock infrastructure isn't commensurate
with the regression risk on currently-stable defensive code,
and (per the issue #4175 follow-up bucket) we keep dedicated
test-coverage work out of perf-cleanup PRs.
Continues commit chain: f05917071 (R9) → 20d2f1b90 (W11) →
6cf18f641 (W12) → 2a41c6fae (R10) → ced5d62b0 (R2) → this (R3 T3).
Test sweep: 6/6 pid-descendants tests pass; typecheck + ESLint clean.
* refactor(acp-bridge): F1 test split — lift bridge.test.ts (6861 LOC) to acp-bridge (#4445)
* refactor(acp-bridge): rename httpAcpBridge.test.ts -> bridge.test.ts (git mv)
Pure file rename; zero content change. Follow-up commits will:
- extract FakeAgent + makeChannel + makeBridge into testUtils.ts
- split 4 daemon-host integration tests back to cli/daemonStatusProvider.test.ts
Part of #4175 F1 test split (deferred from #4334).
* refactor(acp-bridge): extract testUtils + split daemon-host tests to cli (#4175 F1)
Net mechanical extraction following commit 2aff1a4d1 (pure git mv of
httpAcpBridge.test.ts -> bridge.test.ts). After this commit
`@qwen-code/acp-bridge` owns the bulk of the lifted bridge test
suite, and cli keeps only the 4 daemon-host integration tests that
need to wire `createDaemonStatusProvider()`.
Changes:
1. New `packages/acp-bridge/src/internal/testUtils.ts` (~280 LOC):
FakeAgent, FakeAgentOpts, ChannelHandle, makeChannel, makeBridge
(no statusProvider default — acp-bridge tests exercise the
no-provider fallback path), WS_A/WS_B/SESS_A constants. Marked
@internal; lives under `internal/` matching the existing
`stderrLine.ts` package-private convention. Exposed via new
`./internal/testUtils` subpath in package.json exports.
2. `packages/acp-bridge/src/bridge.test.ts` shrinks from 6861 ->
~6400 LOC: fixtures replaced with named imports from
`./internal/testUtils.js`; cross-package import
`from './daemonStatusProvider.js'` removed (4 daemon-host tests
moved out); ACP SDK + bridgeErrors / workspacePaths / bridge /
channel / bridgeTypes imports split into multiple statements
reflecting actual post-F1 provenance.
3. New `packages/cli/src/serve/daemonStatusProvider.test.ts`
(~240 LOC, 4 tests): wires real `createDaemonStatusProvider()`
through a cli-side `makeBridge` wrapper to assert end-to-end
daemon env / preflight cells. Imports
`createHttpAcpBridge` via the `./httpAcpBridge.js` re-export
shim — doubles as a shim surface smoke check.
Verification:
- acp-bridge: 291/291 tests pass (177 in bridge.test.ts).
- cli: daemonStatusProvider.test.ts 4/4 pass; full cli suite 6742/6767
green (16 pre-existing failures in AuthDialog / memoryDiagnostics /
useAtCompletion — all on `daemon_mode_b_main` baseline, last
modified by commits predating this branch).
- Tests counts pre-split: 181 in httpAcpBridge.test.ts;
post-split: 177 in bridge.test.ts + 4 in daemonStatusProvider.test.ts
= 181 (parity preserved).
Part of #4175 F1 test split (deferred from #4334).
* refactor(acp-bridge): self-review round 1 — vitest alias + doc/comment polish
Five code-reviewer findings folded in on top of e97282f30:
S1 [Suggestion] — Test-utils ships to npm + cli reads stale dist.
Added `packages/cli/vitest.config.ts:resolve.alias` mapping
`@qwen-code/acp-bridge/internal/testUtils` → the .ts source. The
package subpath export is RETAINED (required for TypeScript
`nodenext` to resolve types — it won't fall back to tsconfig
paths once exports rejects a subpath). Dual-channel approach
documented in the testUtils JSDoc, including the alpha-stage 0.0.1
tradeoff that the file still ships in dist (stripInternal /
.npmignore deferred).
S2 [Suggestion] — Stale wording "two tests" in narrative comment.
bridge.test.ts split-marker now correctly says "4 fallback tests"
(no-provider × 2 surfaces + throwing-provider × 2 surfaces).
S3 [Suggestion] — "Shim smoke check" only half-applied.
daemonStatusProvider.test.ts now routes `BridgeOptions` and
`HttpAcpBridge` types through `./httpAcpBridge.js` shim too
(alongside `createHttpAcpBridge`), so the entire factory surface
the cli tests rely on flows through the F1 re-export shim.
N1 [Nit] — Asymmetric split-marker phrasing.
Both markers now describe the 4 moved tests by surface
(env real / preflight idle / preflight merged-live /
preflight extMethod-throws) rather than "1 of" + "3 more".
N2 [Nit] — testUtils "the suite" ambiguity.
makeChannel JSDoc now references `bridge.test.ts` explicitly
instead of "the suite" (which was unambiguous pre-split when
helpers + 10 createInMemoryChannel sites lived in the same file).
Verification: 291/291 acp-bridge tests pass; 4/4 cli daemon
integration tests pass; tsc clean on both packages (pre-existing
server.ts errors on baseline unchanged); eslint --max-warnings 0
clean on all 4 touched files.
* docs(cli): self-review round 2 — fix stale vitest.config.ts alias comment
Round 2 reviewer caught a 3-way contradiction in the round 1 docs:
- vitest.config.ts said: alias replaces the export, internal/* stays
unpublished (matches stderrLine convention).
- package.json: subpath export IS declared.
- testUtils.ts JSDoc: both channels intentionally retained,
testUtils ships in dist.
Round 1 explicitly chose to retain the export because TS `nodenext`
won't fall back to tsconfig `paths` once `exports` rejects a
subpath; the alias only serves to short-circuit *runtime* resolution
so cli reads src/ not dist/. Rewriting the vitest.config.ts comment
to reflect that dual-channel reality (and pointing readers at
testUtils.ts for the full rationale).
* fix(acp-bridge): #4445 round 3 fold-in — 4 of 7 reviewer threads adopted
PR #4445 review pass — 4 adopt + 3 decline (declines replied
inline; not folded here):
ADOPTED:
T1 [copilot daemonStatusProvider.test.ts:136 — bridge.shutdown
missing]: added `await bridge.shutdown()` to test 2 (preflight
idle). Three of four tests already shut down; symmetry +
future-proof if `createHttpAcpBridge` gains background work
even when no channel was spawned.
T5 [wenshao testUtils.ts:92 — makeBridge naming collision]: cli-
side helper renamed `makeBridge` -> `makeBridgeWithDaemonStatusProvider`
(4 call sites in daemonStatusProvider.test.ts), JSDoc updated to
reference the wenshao thread. testUtils.makeBridge stays as the
canonical name used by ~100 tests in bridge.test.ts. A future
contributor can no longer pick the wrong helper by accident.
T6 [wenshao testUtils.ts:32 — JSDoc mis-claims @internal tag matches
stderrLine.ts convention]: fixed wording. stderrLine.ts uses prose
only; @internal is an additional package-private signal, not a
convention match. Also restructured the npm-leak paragraph to
describe the new .npmignore-via-files-negation enforcement (T7).
T7 [wenshao package.json:70 — testUtils ships to npm]: switched
`files: ["dist"]` -> `files: ["dist", "!dist/internal/testUtils.*",
"!dist/**/*.test.*"]`. Wenshao's suggested `"test"` exports
condition wasn't viable: vitest sets `vitest` not `test`, and
gating on `vitest` would hide types from the cli's tsc compile.
The negation-pattern files-field excludes the built testUtils
from the publish surface while keeping the subpath export entry
that TypeScript `nodenext` needs to resolve types. Verified via
`npm pack --dry-run`: dist/internal/stderrLine.* still ships
(production internal helper); dist/internal/testUtils.* +
dist/**/*.test.* are excluded.
DECLINED (replied on PR threads, not folded here):
T2/T3 [copilot — `handles` array unused in tests 3/4]: bookkeeping
matches the pre-split bridge.test.ts verbatim; cleanup is scope
creep on this rename PR.
T4 [copilot — testUtils eager-imports createHttpAcpBridge,
cross-copy identity risk]: cli daemonStatusProvider.test.ts uses
its OWN local `makeBridgeWithDaemonStatusProvider` and never
imports testUtils.makeBridge — the cross-copy concern isn't
triggered. Premature abstraction on a test-only fixture.
Verification: 291/291 acp-bridge tests pass; 4/4 cli daemon tests
pass; tsc clean both packages; eslint --max-warnings 0 clean on
2 touched .ts files; `npm pack --dry-run` confirms publish-surface
exclusions.
* fix(core): F2 cleanup PR B — self-heal observability (W133-a + W134) (#4460)
* fix(core): F2 cleanup PR B — self-heal observability (W133-a + W134)
W93 declined as already satisfied by W1 fix in #4336 commit 6
(spawnEntry's catch already calls forceShutdown which runs the full
cleanup table — listener removal, timer clear, subscriber detach,
sweep+disconnect, onClosed eviction). Source-verified non-repro.
W133-a: McpClient.onerror now captures the error in a private
`lastTransportError` field (reset at each connect()); the W120
silent-drop block at mcp-pool-entry.ts:346 reads it via the new
`getLastTransportError()` getter and appends `: <error.message>` to
the lastError string on the emitted 'failed' event. Preserves the
literal "silent transport drop" prefix invariant for log-grep
backward compat — pre-fix marker stays a substring.
W134: sweepAndDisconnect now returns SweepResult instead of void —
{ pidSweepError?, disconnectError?, descendantsFound?,
descendantsSignaled? }. The silent-drop fire-and-forget caller chains
to inspect the result and emits a structured warn log when either
pid-sweep threw OR sigtermPids partially signaled (signaled < found)
— surfaces orphan-process pressure without inflating PR scope (no
new SSE event or SDK reducer state; deferred to W134-followup if
maintainers want metrics).
forceShutdown / doRestart sweep callers ignore the return value (JS
implicit-void at await sites preserves behavior).
4 new tests in mcp-transport-pool.test.ts covering W133-a happy path
+ fallback (no prior onerror) + W134 pidSweepError + W134
partial-signal failure modes. Module-mocks pid-descendants.js for
controllable sweep behavior, and debugLogger.js to observe warn
calls (production logger is session-gated and a no-op in tests).
Singleton-stub debugLogger mock so production module-load
`createDebugLogger('McpPool:Entry')` and the test's retrieval get
the same vi.fn instances.
Verification:
- tsc clean: packages/core, packages/cli (server.ts pre-existing
errors unchanged)
- F2 transport-pool: 32/32 pass (28 pre-existing + 4 new)
- mcp-client: 46/46 pass
- eslint --max-warnings 0 clean on 3 touched files
Part of #4175#4336 follow-up bucket.
* fix(core): #4460 round 1 fold-in — 4 copilot doc/comment threads adopted
T1 [copilot mcp-pool-entry.ts:116 — stale line ref in SweepResult JSDoc]:
replaced `mcp-pool-entry.ts:383` with stable method-anchor reference
to the W120 silent-drop block inside `statusChangeListener`. Line
numbers drift on every edit; method names don't.
T2 [copilot mcp-pool-entry.ts:453 — `?? 0` ambiguous in warn payload]:
silent-drop warn log now prints `descendantsFound=unknown` and
`descendantsSignaled=unknown` when the values are undefined (only
reachable in the pidSweepError branch — sweep threw before
assignment). Operators triaging the warn can now distinguish
"sweep succeeded but found 0 descendants" from "sweep itself
threw, count is genuinely unmeasured". Locked in via a new
assertion in the W134 pidSweepError test.
T3 [copilot mcp-client.ts:116 — brittle line refs in lastTransportError
JSDoc]: replaced `mcp-pool-entry.ts:346` and `mcp-client.ts:130`
with stable method/block names (the `statusChangeListener` silent-
drop block; the `client.onerror` arrow inside connect()). Same
fix applied to the parallel comment in mcp-transport-pool.test.ts:730
for consistency.
T4 [copilot mcp-transport-pool.test.ts:797 — singleton-stub mock comment
contradictory]: rewrote the comment to unambiguously describe what
the mock DOES (factory body runs once; inner arrow returns the same
object on every call) instead of the prior hypothetical phrasing
("Returning a fresh object would have...") which read as a
description of current behavior at first glance.
All 4 are doc/comment fixes — zero behavior change apart from the
T2 string format ('unknown' instead of '0'). Verified:
- 32/32 mcp-transport-pool.test.ts pass
- tsc clean on packages/core
- eslint --max-warnings 0 clean on 3 touched files
* fix(core): #4460 round 2 fold-in — remove dead SweepResult.disconnectError field
T5 [wenshao mcp-pool-entry.ts:134 — `disconnectError` is dead data]:
glm-5.1 review caught that the field was populated when
`client.disconnect()` threw (line 844) but no consumer ever read
it — the silent-drop `.then()` handler gated only on
`pidSweepError` and partial-signal; `forceShutdown` and `doRestart`
ignore the return; no test asserted on it.
Removed the field from `SweepResult` and the assignment in the
disconnect catch. The pre-existing `debugLogger.error(`client.disconnect
failed for ...`)` inside `sweepAndDisconnect` already gives operators
the signal — adding it to the outer silent-drop warn would have been
duplicate noise. If a future consumer needs to gate logic on disconnect
failures, re-add the field + reader at that point.
Verification: 32/32 mcp-transport-pool.test.ts pass; tsc + eslint
clean on the touched file.
* feat(sdk/daemon-ui): unified completeness follow-up to #4328 (#4353)
* feat(sdk/daemon-ui): expand event coverage to 28+ daemon event types (PR-A)
Closes the "12+ daemon events fall through to debug" gap surfaced in the PR
the daemon currently emits (Stage 1 + Wave 3-4), so renderers stop having
to peek at `rawEvent.data` for known event categories.
Session-meta:
- session.metadata.changed (from session_metadata_updated)
- session.approval_mode.changed (from approval_mode_changed)
- session.available_commands (from available_commands_update; upgraded
from a status-text fallback to a typed event carrying the command list)
Workspace state (Wave 3-4):
- workspace.memory.changed
- workspace.agent.changed
- workspace.tool.toggled
- workspace.initialized
- workspace.mcp.budget_warning
- workspace.mcp.child_refused
- workspace.mcp.server_restarted
- workspace.mcp.server_restart_refused
Auth device-flow (Wave 4 OAuth, RFC 8628):
- auth.device_flow.started
- auth.device_flow.throttled
- auth.device_flow.authorized
- auth.device_flow.failed (carries DaemonAuthDeviceFlowSdkErrorKind)
- auth.device_flow.cancelled
- `DaemonUiErrorEvent.errorKind?: DaemonErrorKind` — closed-enum error
category propagated from daemon's typed-error taxonomy. Renderers can
branch on errorKind for "retry auth" vs "check file path" affordances
instead of regex-matching `text`.
- `DaemonUiToolUpdateEvent.provenance?: DaemonUiToolProvenance` +
`.serverId?` — closed enum ('builtin' | 'mcp' | 'subagent' | 'unknown').
Falls back to the `mcp__<server>__<tool>` naming heuristic when the
daemon doesn't stamp provenance explicitly. Unblocks UI namespace
dispatch without string-matching toolName.
Session-meta / workspace / auth events do NOT push transcript blocks.
They are intentional sidechannel observations: `lastEventId` advances
(monotonic invariant preserved), but the chat-stream transcript stays
focused on user/assistant/tool/shell/permission content. Renderers
consume them via selectors (introduced in follow-up PRs).
All new event types produce short structured lines in
`daemonUiEventToTerminalText` for tail-style debug consumers. Web/IDE
renderers should consume the typed events directly via subscription.
40/40 tests pass. New tests verify:
- All 16 new event types normalize correctly
- Malformed payloads fall back to debug without leaking raw data
(`secret` field never appears in fallback text)
- MCP tool provenance heuristic (`mcp__github__create_issue` →
provenance='mcp', serverId='github')
- errorKind propagation on session_died / stream_error
- Reducer is no-op on new event types; lastEventId still advances
This is PR-A of the unified-renderer-layer follow-up series:
- PR-A (this commit) — event coverage + closed-enum schema
- PR-B — server-side timestamps + ordering refactor
- PR-C — multimodal content + tool preview taxonomy
- PR-D — render contract (toMarkdown / toHtml / toPlainText) + adapter
conformance test framework
- PR-E — reducer state machine (subagent / progress / current tool /
cancellation propagation)
See https://github.com/QwenLM/qwen-code/pull/4328#issuecomment-4494179724
for the full proposal.
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat(sdk/daemon-ui): server timestamps + event-id-based ordering (PR-B)
Closes the "时间定义不标准" gap surfaced in the PR #4328 review:
- Client-side `Date.now()` drifts across clients
- No daemon-authoritative timestamp propagated to UI
- Out-of-order replay events get fresher `state.now` than originals,
breaking `createdAt` ordering
- `DaemonUiEventBase.serverTimestamp?: number` — daemon-authoritative
wall-clock timestamp extracted from envelope.
- `DaemonTranscriptBlockBase.serverTimestamp?: number` + `clientReceivedAt: number`.
- `createdAt` preserved as `@deprecated` alias for `clientReceivedAt`
(backward compat for code written before this PR).
`extractServerTimestamp` looks at three candidate envelope locations:
1. `event.serverTimestamp` (preferred when daemon adds it)
2. `event._meta.serverTimestamp` (Anthropic-style metadata convention)
3. `event.data._meta.serverTimestamp` (sessionUpdate nested location)
The SDK is ready to consume serverTimestamp WHEN daemon emits it, without
requiring a coordinated SDK release. Undefined when daemon doesn't emit
(current state) — graceful degradation to client-clock ordering.
`selectTranscriptBlocksOrderedByEventId(state)` — returns blocks sorted by:
1. `eventId` (daemon-monotonic SSE cursor) — primary key
2. `serverTimestamp` (daemon wall clock) — fallback for synthetic frames
3. `clientReceivedAt` (local clock) — last resort
Use this when displaying long sessions where event id 5 may arrive AFTER
event id 7 (typical in SSE replay-after-reconnect).
`formatBlockTimestamp(block, opts)` — formats the most authoritative
timestamp on a block using `Intl.DateTimeFormat`. Prefers
`serverTimestamp` over `clientReceivedAt` for cross-client consistency.
Accepts locale / timeZone / dateStyle / timeStyle.
Daemon needs to stamp `_meta.serverTimestamp` on every SSE envelope. This
SDK PR is ready to consume it the moment the daemon ships the field; no
coordination needed.
- serverTimestamp extraction from all three envelope locations
- Defaults undefined when envelope has none
- `selectTranscriptBlocksOrderedByEventId` sorts mixed-arrival events by
eventId (replay scenario)
- `formatBlockTimestamp` prefers serverTimestamp; returns localized string
PR-B of the unified follow-up to PR #4328 (PR-A + PR-B + PR-C + PR-D +
PR-E in one branch).
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat(sdk/daemon-ui): reducer state machine — currentTool / approvalMode / cancellation propagation (PR-E)
Closes the "reducer state machine 设计缺漏" gap surfaced in the PR #4328 review:
- No `currentTool` — UI scans `blocks[]` to find the running tool
- No mirrored approval mode — UI walks events to badge "plan"/"yolo"
- Cancellation does not propagate — in-flight tool blocks stuck at
'in_progress' forever when the parent prompt is cancelled
## State additions (sidechannel, no transcript blocks)
`DaemonTranscriptSidechannelState`:
- `currentToolCallId?: string` — toolCallId of the in-flight tool
- `approvalMode?: string` — mirrored from session.approval_mode.changed
- `toolProgress: Record<string, { ratio?, step? }>` — per-tool progress
shape (daemon-side emission of `tool.progress` events pending)
## Reducer behavior
### `tool.update` events
`IN_FLIGHT_TOOL_STATUSES` = { pending, confirming, running, in_progress }
`TERMINAL_TOOL_STATUSES` = { completed, success, failed, error, canceled, cancelled }
- Tool enters in-flight: set `currentToolCallId = event.toolCallId`
- Tool enters terminal: clear `currentToolCallId` if it matches
- Unknown status (forward-compat): leave pointer untouched
This avoids the failure mode where a future daemon-emitted status like
`'paused'` would silently mark unknown states as either in-flight or
terminal incorrectly.
### `session.approval_mode.changed`
Mirror `event.next` onto `state.approvalMode`. Renderers can render a
mode badge ("plan" / "default" / "auto-edit" / "yolo") with a single
selector call, no event-stream walking.
### `assistant.done` with `reason === 'cancelled'`
`propagateCancellationToInFlightTools` walks every tool block whose
status is still in-flight and force-sets it to 'cancelled'. The daemon
does not guarantee terminal `tool_call_update` for every in-flight tool
when the parent prompt is cancelled, so this propagation prevents UI
spinners from spinning forever.
`currentToolCallId` is also cleared in the same call.
Non-cancellation `assistant.done` (e.g., `reason: 'end_turn'`) does NOT
propagate — in-flight tools remain in-flight until the daemon emits
their terminal update naturally.
## Selectors
- `selectCurrentTool(state)` — returns the running tool block, or undefined
- `selectApprovalMode(state)` — returns the mirrored approval mode
- `selectToolProgress(state, toolCallId)` — per-tool progress query
All exported from `@qwen-code/sdk/daemon`.
## Scope deliberately deferred
Subagent nesting (`parentBlockId` / `delegationId` / `DaemonSubagentTranscriptBlock`)
is NOT in this PR. The shape needs design discussion (how to project nested
events; whether to bake delegation tracking into transcript or sidechannel).
PR-D / PR-F follow-up.
## Test coverage (51/51 pass)
- currentToolCallId set on enter, cleared on terminal
- approvalMode mirrors changes
- Cancellation marks in-flight tools 'cancelled', leaves completed alone
- Unknown status does NOT clear currentToolCallId (forward-compat)
- Non-cancellation `assistant.done` does NOT propagate
## Roadmap
PR-E of the unified follow-up to PR #4328 (PR-A + PR-B + PR-E in this
branch; PR-C / PR-D pending).
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat(sdk/daemon-ui): tool preview taxonomy + multimodal content extraction (PR-C)
Closes two related gaps surfaced in the PR #4328 review:
- `DaemonToolPreview` had only 4 kinds — UI fell back to `key_value` /
`generic` for tools that deserved structured display
- `getTextContent` silently dropped non-text content (image / audio /
resource), so multimodal conversations vanished from the UI
`DaemonToolPreview` extends from 4 to 8 variants:
- `file_diff` — `{ path, oldText?, newText?, patch? }` — file edit tools
(Anthropic-style `oldText/newText`, aider-style `patch`, write-style
`newText` alone)
- `file_read` — `{ path, range?: [start, end] }` — file read tools, with
range extracted from `lineRange` tuple OR `offset/limit` pair
- `web_fetch` — `{ url, method? }` — HTTP fetch tools (requires URL
with scheme to avoid false positives on relative paths)
- `mcp_invocation` — `{ serverId, toolName, argsSummary? }` — MCP server
tool calls, identified via `mcp__<server>__<tool>` naming convention
(same heuristic as PR-A `DaemonUiToolUpdateEvent.provenance`)
Detector order matters — MCP wins first (most specific), then file_diff,
file_read, web_fetch, then the existing command / key_value fallbacks.
New helper `extractContentPart(value): DaemonUiContentPart | undefined`
returns a discriminated union:
```ts
type DaemonUiContentPart =
| { kind: 'text'; text: string }
| { kind: 'image'; mediaType: string; source: { url?, data? } }
| { kind: 'audio'; mediaType: string; source: { url?, data? } }
| { kind: 'resource'; uri: string; mediaType?, description? };
```
The existing `getTextContent` is preserved for backward compat. Renderers
that need to surface non-text content (web UI thumbnails, IDE attachment
chips) now have a typed shape to consume.
- Wiring `extractContentPart` into the normalizer / reducer so text
blocks accumulate `parts: DaemonUiContentPart[]` alongside `text`
(additive shape change requires render contract coordination — PR-D).
- 5 additional tool preview kinds (image_generation / code_block /
tabular / subagent_delegation / search) — useful but not urgent;
current 8 kinds cover the typical agent flows.
- file_diff detection from Anthropic / aider / write shapes
- file_read with lineRange tuple AND offset+limit pair
- web_fetch with method, REJECTS relative paths (no scheme)
- mcp_invocation with serverId + toolName extraction
- Detector priority: MCP wins over file_diff on conflicting shapes
- extractContentPart for text / image (url) / audio (data) / resource
- Unknown content type returns undefined (skip rather than synthesize)
- Image without source returns undefined (defensive)
PR-C of the unified follow-up to PR #4328 (PR-A + PR-B + PR-E + PR-C in
this branch; PR-D render contract pending).
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat(sdk/daemon-ui): render contract — markdown / HTML / plain text helpers (PR-D)
Closes the "render 契约只覆盖 terminal" gap surfaced in the PR #4328 review:
> PR ships `daemonUiEventToTerminalText` for terminal. Web/IDE/channel
> adapters each roll their own projection. No shared contract → adapter
> divergence is inevitable.
## New helpers
```ts
daemonBlockToMarkdown(block, opts?): string // GFM-compatible
daemonBlockToHtml(block, opts?): string // conservatively escaped HTML
daemonBlockToPlainText(block, opts?): string // for copy-paste / logs
daemonToolPreviewToMarkdown(preview, opts?): string
```
All three respect the same `kind` discrimination so adapters can switch
between them without touching call sites.
## Per-kind projection
For each `DaemonTranscriptBlock['kind']`:
- `user` / `assistant` / `thought` — plain text with role labels
- `tool` — header with toolName + structured preview + status badge
- `shell` — fenced code block, stream-discriminated (stdout vs stderr)
- `permission` — title + options list + resolved/pending indicator
- `status` / `debug` / `error` — semantic class / role (error → role=alert)
For each `DaemonToolPreview['kind']`:
- `ask_user_question` — question + options as bullet list
- `command` — fenced bash with optional cwd comment
- `file_diff` — unified diff in fenced code block (oldText/newText OR patch)
- `file_read` — `path (lines N-M)` line
- `web_fetch` — `METHOD url` line
- `mcp_invocation` — `serverId::toolName` with args summary
- `key_value` — bullet list
- `generic` — emphasized summary
## Security
- Default HTML sanitizer escapes `<`, `>`, `&`, `"`, `'` and FIRST strips
ANSI/control sequences via `sanitizeTerminalText` (defense against
agent-emitted escape codes in HTML output).
- Custom sanitizer hook for consumers wanting markdown→HTML pipelines
(markdown-it + DOMPurify, etc.).
- `sanitizeUrls` option strips token-like query params (`token=`, `key=`,
`x-amz-`, etc.) from URLs in `web_fetch` previews.
- `maxFieldLength` truncation defaults 8192, prevents pathological
rendering on huge content.
## Adapter conformance (out of scope for this commit)
The conformance test framework (fixture corpus + `runAdapterConformanceSuite`)
mentioned in PR-D scope is deferred to a follow-up. The render helpers
here are the precondition — once stable, the conformance framework can
use them as the reference projection.
## Test coverage (77/77 pass)
- All 9 block kinds render in markdown (verified for user/assistant/tool/
shell/permission/error specifically)
- file_diff renders as unified diff with old/new lines
- mcp_invocation renders as `server::tool` format
- HTML escapes XSS (`<script>` → `<script>`)
- HTML strips terminal escape sequences before escaping
- Error blocks emit `role="alert"` for screen readers
- plain text drops markdown delimiters
- maxFieldLength truncates with ellipsis
- sanitizeUrls strips token query params
- Custom sanitizer hook works
## Roadmap
PR-D of the unified follow-up to PR #4328 — completes the 5-PR series
(A: event coverage, B: time schema, E: state machine, C: tool preview +
content extraction, D: render contract).
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat(sdk/daemon-ui): 5 additional tool preview kinds — taxonomy complete (PR-F)
Closes the "5 additional preview kinds" item in PR #4353's TODO §A
(SDK-only work).
## New preview kinds (8 → 13)
- `code_block` — `{ language?, code, origin? }` — REPL / formatter /
generator output, fenced as `\`\`\`<language>` in markdown
- `search` — `{ query, resultCount?, top? }` — grep / ripgrep / find /
glob results with up to 5 top hits
- `tabular` — `{ columns, rows, totalRows? }` — structured table output
(50-row cap with `totalRows` truncation indicator); supports both
`columns: string[] + rows: unknown[][]` explicit shape and legacy
`data: Array<Record<>>` shape (auto-infers columns from first row)
- `image_generation` — `{ prompt, thumbnailUrl?, model? }` — dall-e /
diffusion / imagen / flux / sora style tools
- `subagent_delegation` — `{ agentName, task, parentDelegationId? }` —
Anthropic-style Task tool and similar sub-agent dispatchers
## Detector priority
Order matters — most specific wins. New detectors slot in between
`mcp_invocation` and `file_diff`:
```
mcp_invocation > subagent_delegation > search > image_generation
> file_diff > file_read > web_fetch > code_block > tabular
> command > key_value > generic
```
Rationale: subagent / search / image generation are most discriminable
(distinct toolName patterns); file ops next; code_block / tabular last
because their shapes (`code:`, `columns:`) can appear in other tools.
## Render projections
Both `daemonToolPreviewToMarkdown` and the plain-text rendering paths
extended with cases for all 5 new kinds:
- code_block: fenced markdown code block with language tag
- search: bold header + GFM bullet list of top results
- tabular: GFM pipe table with header / separator / body / truncation hint
- image_generation: bold header + blockquoted prompt + embedded markdown
image (URL sanitization respected via `sanitizeUrls` opt)
- subagent_delegation: bold delegate-arrow header + blockquoted task +
optional parent delegation reference
## Test coverage (91/91 pass, +14 new)
- Each detector with positive case
- Detector priority verified: subagent_delegation wins over file_diff
when toolName='Task' has both subagent + file-edit fields
- Tabular row cap (50) + totalRows stamping for truncated data
- Legacy data: Array<Record<>> auto-column inference
- Each render projection with structural assertions (markdown table
format, image embed, bullet lists)
## Roadmap
PR-F of the unified follow-up to PR #4328. Brings the preview taxonomy
to 13 kinds covering: file ops (3), web (1), code/data (2), media (1),
agent control (2 — ask_user_question + subagent_delegation), MCP (1),
search (1), generic fallbacks (2).
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat(sdk/daemon-ui): adapter conformance framework + fixture corpus (PR-G)
Closes the "Adapter conformance test framework" item in PR #4353's TODO §A.
Lets any daemon-ui adapter (TUI / web / IDE / channel / mobile) validate
that it projects a fixed corpus of daemon SSE event streams to the same
semantic shape — catches projection drift before it reaches users.
## API surface
```ts
interface DaemonUiAdapterUnderTest {
reduce(events: readonly DaemonUiEvent[]): unknown;
renderToText(state: unknown): string;
}
interface DaemonUiConformanceFixture {
name: string;
description: string;
envelopes: DaemonEvent[]; // raw daemon envelopes
expectedContains: string[]; // phrases the rendered text MUST contain
expectedAbsent?: string[]; // phrases that MUST NOT appear
normalizeOptions?: { ... }; // forward-compat normalize opts
}
runAdapterConformanceSuite(adapter, opts?): ConformanceSuiteResult
DAEMON_UI_CONFORMANCE_FIXTURES: ReadonlyArray<DaemonUiConformanceFixture>
```
## Design
**Format-agnostic assertion**: adapters can render to ANSI / HTML /
markdown / JSX — the framework only inspects plain text via
`renderToText`. Catches semantic divergence (missing user message,
wrong tool status, leaked secret) without forcing identical formatting.
**Embedded fixture corpus** (no fs reads — works in browser bundle):
- `simple-chat` — user/assistant streaming flow
- `tool-call-lifecycle` — running → completed transition
- `file-edit-diff` — file_diff preview surfacing
- `mcp-invocation` — MCP serverId/toolName extraction via heuristic
- `permission-lifecycle` — request + resolved with outcome
- `mcp-budget-warning` — Wave 3 event (adapter must observe but rendering
is its choice)
- `cancellation-propagates` — tool block status flows
- `malformed-payload-redaction` — uses `includeRawEvent: true` to verify
even a debug-mode adapter doesn't leak `token: secret-do-not-leak`
- `auth-device-flow-success` — Wave 4 OAuth events
- `available-commands-typed-event` — PR-A upgrade from status text
Per-fixture `expectedContains` and `expectedAbsent` describe the
content contract independently of format.
## Suite result
```ts
{
passed: number,
failed: ConformanceFailure[], // each carries missing + leaked + excerpt
total: number,
}
```
**Does not throw** — caller asserts on `result.failed` so adapter test
suites can produce per-fixture diagnostics rather than a single opaque
exception.
## Filter options
`only` / `skip` allow targeted runs during adapter development:
```ts
runAdapterConformanceSuite(myAdapter, { only: ['simple-chat'] });
runAdapterConformanceSuite(myAdapter, { skip: ['cancellation-propagates'] });
```
## Test coverage (97/97 pass, +6 new)
- SDK reference adapter (reducer + markdown render) passes all fixtures
- SDK reference adapter (reducer + plainText render) also passes
- Buggy adapter (empty string output) fails every fixture with non-empty
`expectedContains`
- Buggy adapter (raw event dump via JSON.stringify) caught by redaction
fixture's `expectedAbsent`
- `only` filter narrows to a single fixture
- `skip` filter excludes named fixtures from the corpus
## Usage from adapter authors
```ts
// In your adapter's test file
import { runAdapterConformanceSuite } from '@qwen-code/sdk/daemon';
import { reduceForTui, renderTuiState } from './my-tui-adapter';
it('TUI adapter conforms to daemon UI corpus', () => {
const result = runAdapterConformanceSuite({
reduce: reduceForTui,
renderToText: renderTuiState,
});
expect(result.failed).toEqual([]);
});
```
## Roadmap
PR-G of the unified follow-up to PR #4328. The corpus is intentionally
small (10 fixtures) but extensible — adapter authors can submit new
fixtures via additions to `DAEMON_UI_CONFORMANCE_FIXTURES` to lock in
regression coverage for edge cases their adapter encountered.
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* feat(webui+sdk/daemon-ui): wire transcriptAdapter to SDK render contract (PR-H)
Closes the "WebUI transcriptAdapter migration" item in PR #4353's TODO §A.
Validates the PR-D render contract end-to-end on the real WebUI consumer.
`daemonTranscriptToUnifiedMessages(blocks, options?)` gains a new options
parameter:
```ts
interface DaemonTranscriptAdapterOptions {
useMarkdown?: boolean; // default: false
enrichToolDetailsWithPreview?: boolean; // default: false
}
```
Defaults preserve legacy behavior — existing callers see no change.
For `user` / `assistant` / `thought` blocks, content is projected via
SDK's `daemonBlockToMarkdown` instead of raw sanitized text. The WebUI's
markdown renderer (markdown-it) then gets:
- `**You**\n\n<content>` for user blocks (bold "You" label)
- Raw text for assistant blocks (markdown formatting in agent output
passes through cleanly)
- `> *thought:* <text>` blockquote for thought blocks
For `tool` blocks, `rawOutput` is replaced with `daemonToolPreviewToMarkdown(block.preview)`.
This lets WebUI surfaces without per-preview-kind React components still
display:
- `file_diff` as a fenced unified diff
- `mcp_invocation` as `server::tool` with args summary
- `tabular` as GFM pipe table
- `search` as bullet list with match count
- `image_generation` as embedded markdown image
- `subagent_delegation` as delegate arrow + task quote
Renderers with per-kind components should leave this opt-out.
`packages/sdk-typescript/src/daemon/index.ts` was missing exports for
PR-D / PR-F / PR-G / PR-B / PR-E surface — WebUI's `@qwen-code/sdk/daemon`
import path uses the daemon root, not the ui/ sub-index. Added 15+
re-exports so consumers don't need to use the longer
`@qwen-code/sdk/daemon/ui/index.js` path.
Now exported from `@qwen-code/sdk/daemon` root:
- `daemonBlockToMarkdown` / `daemonBlockToHtml` / `daemonBlockToPlainText`
- `daemonToolPreviewToMarkdown`
- `extractContentPart` + `DaemonUiContentPart` type
- `formatBlockTimestamp` + `selectTranscriptBlocksOrderedByEventId`
- `selectCurrentTool` / `selectApprovalMode` / `selectToolProgress`
- `runAdapterConformanceSuite` + `DAEMON_UI_CONFORMANCE_FIXTURES`
- All associated types
`webui/src/daemon/transcriptAdapter.test.ts` mock blocks updated to include
`clientReceivedAt` (required field added in PR-B). Mechanical change —
every `createdAt: N` test fixture gets a matching `clientReceivedAt: N`.
- WebUI `npm run typecheck` — clean
- SDK `npm run typecheck` — clean
- SDK `vitest run test/unit/daemonUi.test.ts` — 97/97 pass
- WebUI transcriptAdapter test fixtures typecheck against updated
DaemonTranscriptBlockBase schema
PR-H of the unified follow-up to PR #4328. Closes the WebUI migration
gap in TODO §A.
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* docs(daemon-ui): add developer guide + migration cookbook (PR-I)
Closes the final "Documentation" item in PR #4353's TODO §A. Brings the
unified daemon UI surface to ~95% SDK-side completion.
## Files added
- `docs/developers/daemon-ui/README.md` — full API reference
- Three-layer model (normalizer → reducer → render helpers)
- Quick start with idiomatic event-loop pattern
- Event taxonomy (28+ types categorized: chat-stream / session-meta /
workspace / auth device-flow)
- Render contract cookbook (markdown / HTML / plainText)
- Tool preview taxonomy (13 kinds with use cases)
- State selectors (currentTool / approvalMode / toolProgress / ordering)
- Cancellation propagation explanation
- Time semantics (eventId > serverTimestamp > clientReceivedAt
precedence)
- Adapter conformance usage
- ErrorKind dispatch pattern
- Tool provenance dispatch pattern
- Forward-compat principles
- `docs/developers/daemon-ui/MIGRATION.md` — adapter author migration
cookbook
- Step-by-step recommended adoption order (9 steps, value-ranked)
- Before/after code examples for each step
- Backward-compat checklist (everything is additive — no breaking
changes)
- Cross-references to PR-A through PR-H commits
## Roadmap
PR-I of the unified follow-up to PR #4328. Documentation-only — no
code changes; no tests affected.
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): address review feedback
* fix(daemon-ui): address review hardening feedback
* fix(daemon-ui): handle resync-required events
* feat(sdk/daemon-ui): consume daemon-side subagent nesting context (PR-K)
Closes the SDK-side gap for §B1 in PR #4353's TODO list. PR-E originally
deferred subagent nesting because daemon-side parent-context wasn't yet
stamped on tool_call events. After the rebase onto current
daemon_mode_b_main, source verification confirms the daemon now emits
`tool_call._meta.parentToolCallId` + `tool_call._meta.subagentType` via
`SubAgentTracker.getSubagentMeta()` (core), so the SDK side is unblocked.
## Schema additions (additive, forward-compat-safe)
`DaemonUiToolUpdateEvent`:
- parentToolCallId?: string — toolCallId of the parent Task / delegation
- subagentType?: string — sub-agent type label (e.g. 'code-reviewer')
`DaemonToolTranscriptBlock`:
- parentToolCallId?: string — mirror of event field
- subagentType?: string — mirror of event field
- parentBlockId?: string — pre-resolved by reducer when parent already
in state, so renderers don't re-correlate
## Normalizer wiring
`normalizeToolUpdate` checks both top-level and `_meta` for parentToolCallId
+ subagentType (fallback chain mirrors how provenance/serverId are read).
Top-level tool calls without sub-agent context omit the fields cleanly.
## Reducer behavior
- New tool block: resolves `parentBlockId` from `toolBlockByCallId` at
create time. Out-of-order arrival (child before parent) leaves
`parentBlockId` undefined — selectors fall back to `parentToolCallId`
lookup.
- Existing tool block update: adopts parent context if not yet
correlated, never overwrites established correlation (handles the
flow where SubAgentTracker activates after the initial tool_call).
## New public selectors
- selectSubagentChildBlocks(state, parentToolCallId): returns the
array of tool blocks invoked inside a given parent delegation
- isSubagentChildBlock(block): type guard for "this tool block came
from a sub-agent"
Both exported from @qwen-code/sdk/daemon root + ui/index.
## Forward-compat properties
- Top-level tool calls (no sub-agent) work identically as before
- Trimmed parent blocks: child fallback to undefined parentBlockId
- Daemon emits both fields together; SDK reads independently to tolerate
partial future stamping
## Test coverage (129/129 pass, +5 new tests)
- Extract parentToolCallId + subagentType from `_meta`
- Top-level tool calls have undefined parent fields (forward-compat)
- Reducer correlates parentBlockId at create time
- Reducer adopts parent context on later update (out-of-order arrival)
- isSubagentChildBlock discriminator
## Roadmap
PR-K of the unified follow-up to PR #4353. Closes §B1 (subagent nesting)
in the TODO declaration; daemon-side already shipped on
`daemon_mode_b_main` via SubAgentTracker (core).
Remaining TODO §B / §D items still depend on further daemon/Core work:
- §B2 `tool.progress` event type (daemon emit pending)
- §D MessageEmitter multimodal echo + HistoryReplayer inlineData/fileData
(core change pending)
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): PR-K self-review hardening — back-fill / trim / self-ref / docs
Multi-round self-review of PR-K (d8375fe46) surfaced two real bugs, a
few defensive gaps, and missing docs/fixture coverage. All addressed
in one commit.
## Bugs fixed
### Bug 1 — `parentBlockId` never back-filled for out-of-order arrival
Original PR-K resolved `parentBlockId` only at child create time, which
broke this flow:
1. Child arrives WITH parent stamp → block created with
`parentToolCallId` set, `parentBlockId` undefined (parent not in
state yet)
2. Parent arrives later → block created, `toolBlockByCallId` indexed
3. Subsequent child updates: existing-block branch only ran the
back-fill inside `!existing.parentToolCallId`, which is false (we
already adopted the stamp in step 1). `parentBlockId` stayed
undefined forever.
Fix: separate the two correlations.
- existing-block update: independently back-fill `parentBlockId`
whenever `parentToolCallId` is set and `parentBlockId` is missing
- new-block create: scan existing children whose `parentToolCallId`
matches the new block's `toolCallId` and back-fill their
`parentBlockId`. Cheap O(n) over current blocks.
### Bug 2 — dangling `parentBlockId` after trim
`trimTranscriptState` reset `toolBlockByCallId[id]` to the trimmed
sentinel for evicted blocks but did NOT walk surviving children to
null their `parentBlockId` references. Renderers walking
`blockIndexById.get(parentBlockId)` would get undefined, with no
"why" signal.
Fix: post-trim, walk remaining tool blocks; if `parentBlockId`
references an id not in `keptIds`, null it. `parentToolCallId` stays
(survives trimming so selector-keyed queries still work).
## Defensive hardening
- **Self-reference guard** (normalizer): drop
`parentToolCallId === toolCallId` before it reaches the reducer.
Daemon should never emit this, but defending costs nothing.
- **Selector docstring**: clarify `selectSubagentChildBlocks` returns
**direct** children only; document cycle / depth-cap responsibility
for renderers walking up the chain.
- **Cosmetic**: remove redundant `as DaemonToolTranscriptBlock` cast
in `isSubagentChildBlock` (TypeScript already narrows after
`block.kind === 'tool'` on the discriminated union).
- **Alphabetical**: move `isSubagentChildBlock` re-export to correct
position in both `daemon/index.ts` and `daemon/ui/index.ts`.
## Docs + conformance gaps closed
- `README.md` — new "Sub-agent nesting (PR-K)" section with full
reducer behavior, out-of-order handling note, recursive walk example,
cycle-defense note.
- `MIGRATION.md` — new step 8a with before/after for nested rendering.
- `conformance.ts` — new `subagent-nesting` fixture covering parent +
nested child via `tool_call._meta`. Markdown-safe phrases chosen
(markdown escapes `-` so titles cannot be substring-matched as-is).
## Test coverage (+5 tests, 134/134 pass)
- Self-reference dropped in normalizer
- Back-fill on out-of-order parent arrival (child first, parent after)
- Back-fill on later child update when parent now exists
- Dangling `parentBlockId` nulled after parent trimmed
- New `subagent-nesting` conformance fixture passes SDK reference adapter
## Side-effect verification
Verified no regressions:
- Cancellation propagation still cancels parent + children together
(iterates `toolBlockByCallId`, which includes both)
- Render contract unchanged (`daemonBlockToMarkdown` etc. project per
block, no nested awareness required)
- No serializer to update
- `selectTranscriptBlocksOrderedByEventId` unaffected (parent-agnostic)
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): permission block trim contract — wenshao review
Addresses both items from wenshao's review on PR #4353:
## Critical — resolvePermissionBlock missing TRIMMED guard
The sibling `upsertPermissionBlock` (transcript.ts:544) correctly returns
early when `existingId === TRIMMED_PERMISSION_BLOCK_ID`, but
`resolvePermissionBlock` (transcript.ts:581) had no such guard. When
`maxBlocks` trimming evicted a pending permission request, a subsequent
`permission.resolved` event would:
1. Fail the `getWritableBlockById` lookup (sentinel is not a real block id)
2. Fall through and create a brand-new orphan resolution block
This wasted a block slot, accelerated further trimming, and silently
broke the trimmed-block contract that the request-side guard establishes.
Fix: mirror the request-side guard. Read the index entry up front,
return early on the sentinel.
## Suggestion — permissionBlockByRequestId grows unboundedly
`trimTranscriptState` writes `TRIMMED_PERMISSION_BLOCK_ID` for evicted
permission requests but never deletes those entries. Unlike the tool
side (which calls `pruneTrimmedToolIndexes` post-trim), the permission
index grew without bound in long sessions.
Fix: add `pruneTrimmedPermissionIndexes` analogous to the tool-side
helper. Caps the sentinel set at `maxBlocks` entries; older entries are
deleted (any later resolution event still drops cleanly via the new
Critical guard).
## Tests
- Updated existing `keeps orphan permission resolutions visible after
request trimming` test to encode the corrected contract (drops silently
instead of creating an orphan). Test rename: "drops resolution for
trimmed permission requests (wenshao Critical)".
- New `Suggestion: pruneTrimmedPermissionIndexes caps the trimmed
sentinel set` test verifies the cap.
Total: 136/136 tests pass, SDK + WebUI typecheck green.
## Side-effect verification
- `upsertPermissionBlock` already had the equivalent guard — no
asymmetry remains.
- `pruneTrimmedPermissionIndexes` only touches entries holding the
sentinel; live permission blocks are unaffected.
- Selectors over `state.blocks` (e.g. `selectPendingPermissionBlocks`)
iterate the block array, not the index — unaffected by cap.
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): address wenshao + doudouOUC inline reviews (2026-05-23)
Addresses the 13 inline review comments from wenshao (6) and doudouOUC
(7, one overlap) on the 2026-05-23 review round.
## Critical / Important
### sanitizeUrls not threaded through HTML preview path (doudouOUC)
`daemonBlockToHtml` for tool blocks called `daemonToolPreviewToPlainText`
which didn't accept `opts` — when callers set `sanitizeUrls: true`, the
markdown path stripped auth tokens but the HTML path leaked them into
the DOM. Now: helper accepts opts, threads through `web_fetch.url` and
`image_generation.thumbnailUrl`.
### enrichToolDetailsWithPreview overwrote rawOutput (doudouOUC)
The webui adapter replaced structured `rawOutput` with a markdown
summary string when `enrichDetails: true`. Downstream `ToolCallData`
consumers may branch on the shape (object vs string) and break. Plus
the actual tool output was silently dropped.
Fix: keep `rawOutput` verbatim, surface markdown via a new optional
`previewMarkdown` field added to `ToolCallData`.
### transcriptBlockToTerminalText zero test coverage (wenshao)
Added 12 tests covering each `switch` branch (user / assistant / thought
/ tool / shell stdout+stderr / permission unresolved+resolved / status /
debug / error) plus the unknown-kind degradation path. Verified
`assertNever` returns a graceful error line (does NOT throw) — wenshao's
reviewer was slightly wrong on the throw claim but coverage gap was
real.
### selectTranscriptBlocksOrderedByEventId no memoization (wenshao)
Selector was called from React `useSyncExternalStore` and re-sorted on
every dispatch — including sidechannel-only events that don't touch
blocks. Added WeakMap cache keyed on `state.blocks` reference; the
reducer preserves the same array reference for non-block-mutating
events, so the cache hits across renders.
### selectSubagentChildBlocks O(n) per call (wenshao)
Naive `state.blocks.filter()` was O(n) per call; rendering a tree with
m parents made it O(n*m). Built a memoized reverse index keyed on
`state.blocks` reference (WeakMap of parentToolCallId →
DaemonToolTranscriptBlock[]). Each lookup now O(1) after first call.
### Test file TS errors at root tsc (wenshao)
Fixed multiple TS errors in `daemonUi.test.ts` flagged by root
`tsc --noEmit`:
- Added `DaemonTranscriptState` + `DaemonUiEvent` imports
- `block.content` access via `as Array<Record<string, unknown>>` cast
- `delete` on globalThis property via narrower interface cast
- `debug?.text` via `DaemonUiEvent & { text: string }` narrowing (Extract on
union with `'status' | 'debug'` literal would resolve to never)
- 6 occurrences of index-signature access via bracket notation
- `raw: null` added to 3 `DaemonUiPermissionOption` literals (required field)
- Explicit type annotations on conformance-suite `renderToText` params
Note: `webui/src/daemon/transcriptAdapter.test.ts` shows residual
"clientReceivedAt does not exist" errors at root tsc, but this is
environmental — the resolution trace shows `@qwen-code/sdk/daemon`
crossing into a sibling worktree's stale dist via shared workspace
node_modules. In a single-worktree CI checkout this resolves cleanly.
## Suggestions (cleanups)
### Hoist asDaemonErrorKind double-eval (doudouOUC)
`session_died` + `stream_error` cases each computed `asDaemonErrorKind`
twice in the conditional spread (predicate + value). Hoisted to const,
no functional change.
### renderToolHeader bypassed opts (doudouOUC)
Forwarded `opts` so `maxFieldLength` is honored for tool title /
toolName / toolKind.
### isSensitiveKey duplicates (doudouOUC)
Removed duplicate `endsWith('accesskey')` / `endsWith('secretkey')`
checks and the redundant exact-match `privatekey` (already covered by
`endsWith`).
### propagateCancellationToInFlightTools iterated trimmed (wenshao)
Filter `TRIMMED_TOOL_BLOCK_ID` sentinels up front. Avoids redundant
index dereferences in long sessions with many historical tools.
### toolProgress shallow clone (doudouOUC + wenshao)
`cloneTranscriptState` outer `...state` spread shared inner
`{ ratio?, step? }` references between snapshots. Once `tool.progress`
event handlers start mutating in place, the prior snapshot would leak.
Deep-clone the inner records now (cost bounded by in-flight tools,
small).
### isDeviceFlowErrorKind closed set (wenshao + doudouOUC)
Both reviewers suggested strict validation. We INTENTIONALLY kept
lenient pass-through — the public type
`DaemonAuthDeviceFlowSdkErrorKind` explicitly includes `(string & {})`
as a forward-compat escape hatch (existing test `keeps future
auth_device_flow_failed errorKind values observable` enforces this).
Now expose `KNOWN_DEVICE_FLOW_ERROR_KINDS` as documentation and
explain the design in the JSDoc.
## Validation
| | |
|---|---|
| SDK tests | 148/148 pass (+12 terminal coverage + assorted hardening) |
| SDK typecheck | clean |
| WebUI typecheck | clean |
## Side-effect verification
- WeakMap memos invalidate correctly: reducer creates a fresh
`state.blocks` reference only on block-mutating events. Sidechannel
events reuse the same reference.
- `previewMarkdown` is optional and additive on `ToolCallData`;
consumers ignoring it are unaffected.
- `sanitizeUrl` is called only when `opts.sanitizeUrls === true` in HTML
path; default behavior unchanged.
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): wenshao glm-5.1 review — lazy COW + lint + memo verification
Addresses the 6 inline comments from wenshao's 2026-05-23 13:03
CHANGES_REQUESTED review.
## Real fix — WeakMap memoization actually works now (Suggestion #2)
The earlier `sortedBlocksCache` / `childrenIndexCache` WeakMaps keyed on
`state.blocks` reference, but `cloneTranscriptState` did
`blocks: [...state.blocks]` eagerly — every dispatch produced a fresh
array, so the caches never hit. The JSDoc claim "memoize across renders
that don't touch blocks" was misleading.
Fix: lazy copy-on-write.
- `cloneTranscriptState` now shares `blocks` + `blockIndexById` by
reference (no eager copy).
- New `takeBlocksOwnership(state)` performs the array copy at the first
mutation; subsequent mutations in the same dispatch are no-ops
(tracked via module-level `ownedBlocks: WeakMap<State, blocks>`).
- `appendBlock`, `getWritableBlockById`, and `trimTranscriptState` all
take ownership before mutating.
Result: sidechannel events (approval mode change, session metadata,
workspace events, auth device-flow, etc.) preserve `state.blocks`
identity across dispatches. The WeakMap caches actually hit now —
verified by new test `selectTranscriptBlocksOrderedByEventId returns
the same array reference for sidechannel-only events`.
## Lint Criticals (3) — readonly array syntax
`ReadonlyArray<T>` → `readonly T[]` per `@typescript-eslint/array-type`:
- `KNOWN_DEVICE_FLOW_ERROR_KINDS` satisfies clause
- `EMPTY_CHILD_LIST`
- `selectSubagentChildBlocks` return type
## Suggestion #1 — shallow copy from selectSubagentChildBlocks
Return `[...cached]` so accidental in-place mutation (e.g., caller
calling `.sort()` on the result) cannot corrupt the WeakMap-cached
children index for other consumers sharing the same `state.blocks`
snapshot.
## Suggestion #6 — KNOWN_DEVICE_FLOW_ERROR_KINDS sync test
Added test `only contains canonical device-flow error kinds` — runtime
assertion that guards against the array being silently emptied. The
`as const satisfies readonly DaemonAuthDeviceFlowSdkErrorKind[]` at the
declaration site already enforces type-level membership; this test
adds a stable count check.
## Test coverage (+4 new tests, 152/152 pass)
- `selectTranscriptBlocksOrderedByEventId` preserves array identity
across sidechannel-only events (memo hit verification)
- `selectSubagentChildBlocks` preserves WeakMap entry across sidechannel
dispatches
- `selectSubagentChildBlocks` returns shallow copy (caller mutation
doesn't corrupt cache)
- `KNOWN_DEVICE_FLOW_ERROR_KINDS` membership + count assertions
## Side effects
- Block property mutations still leak across snapshots (pre-existing —
the original eager copy was also a shallow array copy with shared
block refs). Not introduced by this change; documented in
`getWritableBlockById` comments.
- All existing block-mutating tests pass — `takeBlocksOwnership` produces
the same observable result as eager copy, just deferred to first
mutation.
Validation:
- SDK tests: 152/152 pass
- SDK typecheck: clean
- WebUI typecheck: clean
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): forward opts in daemonBlockToPlainText tool case
wenshao review 4350741340 (2026-05-23 13:00): the prior doudouOUC
review fixed only the HTML path; the plainText tool case still called
`daemonToolPreviewToPlainText(block.preview)` without `opts`, so
`sanitizeUrls` + `maxFieldLength` were silently ignored when consumers
used the plain-text projection (logs, clipboard, terminal mirroring).
Symmetric fix to the HTML path (line 509). Added test verifying token
stripping reaches `web_fetch.url` via plainText path.
Validation: 153/153 SDK tests, SDK + WebUI typecheck clean.
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): address wenshao 2026-05-23 reviews (3 Critical + 8 Suggestion + 1 false-positive)
Walks all 22 inline comments from wenshao's 13:00-14:56 burst plus
doudouOUC's APPROVED-with-suggestion. 11 real fixes applied; 1 reverted
after gate-check; remaining items either already addressed in prior
commits (stale) or are test-only coverage gaps now filled.
## Security / Correctness Criticals (real)
### sanitizeUrl strips Basic Auth (R2 #1)
`https://user:pw@host/...` previously passed through with userinfo
intact, leaking secrets into rendered markdown / HTML / plaintext.
`u.username = ''; u.password = '';` before serializing.
### thumbnailUrl protocol validation always-on (R2 #2)
`javascript:alert(1)` in `` survived when sanitizeUrls
was false (the default). Added `ensureSafeImageUrl(url)` — protocol
whitelist (http/https/data only) that runs unconditionally for image
URL renderings. `sanitizeUrls: true` still wins for query-param +
Basic Auth stripping.
### permission.resolved orphan after sentinel pruned (R1 #2)
The prior trim-contract fix guarded `existingId === TRIMMED_*`. After
`pruneTrimmedPermissionIndexes` deleted a sentinel (long sessions),
`existingId` became `undefined`, bypassed the guard, and created an
orphan. Reject `undefined || TRIMMED_*` together.
## Behavior Suggestions (real)
### Selective cancellation propagation (R2 #6)
`assistant.done.reason` of `stream_ended` / `reconnected` are
transport-layer signals — the daemon-side tool is still running and SSE
replay will deliver the real terminal status. Marking in-flight tools
cancelled caused a visible spinner-to-red flash on reconnect. Scoped
propagation to `cancelled` || `error` only.
### awaitingResync diagnostics (R2 #3)
State-resync latch silently dropped events with no signal. Added
`console.warn` describing the dropped event type + last resync trigger
so a stuck UI is debuggable. Latch behavior intentionally preserved —
recovery is `store.reset()` on session reconnect.
### selectSubagentChildBlocks: freeze instead of copy (R1 #8)
`[...cached]` per-call defeated React.memo / useMemo identity
stability (every call produced a fresh array reference). Now freeze
the cached arrays at build time in `getOrBuildChildrenIndex` and
return the frozen reference directly — referential stability +
mutation defense (strict-mode throws on `.length = 0` etc.).
### detectSubagentDelegation regex too broad (R3 #2)
`(?:^|_)task$` falsely matched `edit_task` / `list_task` /
`create_task` etc. — common tool names unrelated to delegation.
Anthropic's Task tool is literally named `Task` (no prefix), so
restricted bare-`task` to whole-name only: `^task$`. `delegate` /
`subagent` / `spawn_task` keep the `^|_` prefix.
### memoryChanged bytesWritten finite check (R3 #3)
`typeof === 'number'` accepted NaN / Infinity. Use the existing
`numberField` helper which calls `Number.isFinite(v)`.
### Multi-line blockquote prefix (R3 #1)
`> *thought:* ${text}` only prefixed the first line; subsequent lines
escaped the blockquote. Added `blockquote(raw)` helper that prefixes
every line; applied to thought / debug / error renderings.
## Quality (real)
### plainText / HTML maxFieldLength parity (R1 #5/6/7, doudouOUC approve note)
The tool block in markdown caps via `text()`; plaintext + HTML caps
were missing on header fields, preview content, and permission block
labels. Threaded `cap()` consistently across all three projections.
### isSensitiveKey dedup (R1 #10)
Seven exact-match entries (`password` / `apikey` / `idtoken` /
`sessiontoken` / `clientsecret` / `xapikey` / `xauthtoken`) were
already subsumed by existing `endsWith` rules. Removed.
### Re-export DaemonUiStateResyncRequiredEvent (R2 #7)
Other session-meta event types are exported from the daemon barrel;
this one was missed. Added to both `daemon/ui/index.ts` and
`daemon/index.ts`.
## Reverted after gate-check (false-positive)
### classifySelectedPermissionOption CANCELLED branch (R2 #4)
Reviewer suggested adding `CANCELLED_PERMISSION_TERMS` check before
the `completed` default, so `selected:cancel` would map to cancelled.
This CONFLICTS WITH:
- the design comment at the caller: "A selected option resolves the
prompt even when the option id is a domain value like a city name or
an option id containing deny/cancel"
- the existing test `'cancelled-substring-permission'` with payload
`'selected:abort'` expecting status `'completed'`
The daemon expresses "user cancelled the prompt" via `cancelled` as the
PRIMARY token (handled at the caller layer), not `selected:cancel` —
the latter means "user picked an option labeled cancel", which is a
successful selection. Reverted; added explanatory comment so the next
review round doesn't re-flag it.
## Stale (already fixed)
### R1 #1 (daemonBlockToPlainText opts forwarding)
Already fixed in d35cbb75a (2026-05-23 monitor pass for review
4350741340). No further action.
## Test coverage added
- HTML web_fetch URL sanitization (sanitizeUrls + Basic Auth)
- Image URL protocol validation when sanitizeUrls:false
- HTML shell / permission / thought / debug / status block kinds
- Trimmed-tool cancellation propagation (no throw + transport-layer no-cancel)
- Late permission.resolved after sentinel prune (no orphan)
- Frozen children-index identity stability + mutation guard
- previewMarkdown preserves rawOutput as object (in webui adapter test file)
## Validation
| | |
|---|---|
| SDK tests | **161/161** (was 153 → +8 new) |
| WebUI tests | **9/9** (was 8 → +1 new) |
| SDK typecheck | clean |
| WebUI typecheck | clean |
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): tighten ensureSafeImageUrl to data:image/* only
Audit follow-up (post-f5c54680f review pass): the previous
`ensureSafeImageUrl` whitelist accepted any `data:` URI, which let
`data:text/html,<script>alert(1)</script>` pass the protocol check.
Modern browsers don't execute `<img src="data:text/html,...">`, but
the comment claimed "never legitimate in `<img src>`" which slightly
over-claimed the protection.
Tighten the data: branch to require an `image/<subtype>` MIME prefix.
Verified by a new test that covers: https (allow), data:image/png
(allow), data:text/html (reject → '#'), javascript: (reject → '#').
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): wenshao + doudouOUC R4 review batch
Walks 6 wenshao items (delivered as 8 review submissions — 2 CHANGES_REQUESTED
+ 6 individual COMMENTED — but 6 distinct concerns) and 3 doudouOUC R4
nits. All 9 real issues addressed; no false-positives this round.
## Real Criticals
### awaitingResync recovery API (wenshao R4)
`store.reset()` requires session-id change semantics — wrong shape for
"same-session reconnect with SSE replay" recovery. Added explicit
`store.clearAwaitingResync()` API. Latch is still set on receipt of
`session.state_resync_required` (intentional one-way during replay
window); consumers now have a clean path to clear after the replay
stream drains.
### normalizeAuthDeviceFlowCancelled test coverage (wenshao R4)
Coverage gap surfaced — happy path (valid deviceFlowId) and malformed
fallback to debug both untested. Added 2 tests.
## Real Suggestions
### sanitizeUrl: AWS / Azure / GCP credential patterns
The previous regex caught `x-amz-` and `x-goog-` headers + generic
`signature` / `sig`, but missed:
- `AWSAccessKeyId` (S3 presigned)
- Azure SAS short codes (`sv` / `se` / `sr` / `sp` / `st` / `spr` /
`sip` / `ss` / `srt` / `sig` / `skoid` / etc.)
- GCP signed-URL `GoogleAccessId` + `Expires` (paired with credentials
in signed URL contexts)
Widened regex to include `aws|google|expires` prefixes + added explicit
Azure-SAS Set check.
### detectFileDiff: `content` alias disambiguated
`{ path, content }` was being classified as `file_diff` regardless of
tool semantics — but the same shape is common for file_read assertions
or search queries. Since detectFileDiff runs BEFORE detectFileRead in
the detector chain, this caused mis-classification.
Fix: restrict bare `content` to require either (a) write-intent tool
name (write/create/edit/replace/save/update) OR (b) co-occurrence with
`oldText`. Explicit `newText` / `new_text` / etc. still pass through
unconditionally. Required adding `opts` to the `detectFileDiff`
signature (callers already pass opts to siblings).
### detectFileRead: 0-based offset → 1-based range
Type doc says `range: [startLine, endLine]` is 1-based inclusive. The
offset+limit conversion produced 0-based output ([0, 9] for
offset=0/limit=10), which displayed as "lines 0-9" — line 0 doesn't
exist in 1-based. Convert at the detector: `[offset+1, offset+limit]`.
Updated the matching test (which had encoded the 0-based bug as
expected behavior).
### formatMissedRange — guard inverted / single-event ranges
The naive `lastDeliveredId+1 .. earliestAvailableId-1` formula
produced:
- `gap === 0`: "missed 6-5" (inverted)
- `gap === 1`: "missed 6-6" (single event shown as range)
Added `formatMissedRange()` helper with explicit branches:
- `last < first` → "no events lost (resync requested without gap)"
- `last === first` → "missed 1 daemon event (id N)"
- `last > first` → "missed daemon events X-Y"
Applied in both `transcript.ts` (status block message) and `terminal.ts`
(ANSI projection) — same formula was duplicated.
## doudouOUC R4 nits
### README errorKind list outdated
Replaced `expired / transport / server / internal` with pointer to
`KNOWN_DEVICE_FLOW_ERROR_KINDS` exported constant — canonical list
auto-stays-in-sync.
### README "10 scenarios" stale
Was 10, became 11 with subagent-nesting. Removed the count and let
the corpus be derived at runtime via
`DAEMON_UI_CONFORMANCE_FIXTURES.length`.
### selectTranscriptBlocks danger post lazy-COW
With state.blocks now shared across sidechannel snapshots, a misbehaving
consumer doing `(state.blocks as DaemonTranscriptBlock[]).sort()` would
poison every snapshot sharing the reference. Freeze the blocks array
at the dispatch boundary in `reduceDaemonTranscriptEvents`. Internal
reducer mutation goes through `takeBlocksOwnership` which copies before
mutating, so the frozen reference is never modified in place.
## Validation
| | |
|---|---|
| SDK tests | **162/162** |
| WebUI tests | **9/9** |
| SDK typecheck | clean |
| WebUI typecheck | clean |
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): wenshao R5 review batch — Critical OAuth fragment leak + 10 more
Walks 13 inline items from wenshao's 16:46-17:28 reviews. 11 fixed, 1
deduped (lint-no-console flagged in both reviews), 1 reverted/push-back
(multi-part deny re-flags the same design-intent territory as R2 #4).
## Critical fixes
### sanitizeUrl: OAuth #fragment leak
`sanitizeUrl` cleared query params and Basic Auth userinfo, but
`u.toString()` preserved `u.hash`. OAuth 2.0 implicit grant puts
`access_token=...` directly in the fragment (e.g.,
`https://app/#access_token=gho_xxx&token_type=bearer`); some Azure
SAS variants similarly. Now `u.hash = ''` before serialize. For
rendered output (markdown / HTML / plaintext), the fragment is client-
state-only and dropping it removes the entire fragment-side leak surface.
### ESLint no-console on awaitingResync diagnostic
Project lint forbids bare `console.*`. Added
`eslint-disable-next-line no-console -- intentional diagnostic` per
wenshao's suggestion. Behavior unchanged.
### normalizeAuthDeviceFlowCancelled test coverage (still missing post-R4)
R4 added tests for one of the five device-flow normalizers; the
`cancelled` variant was still uncovered. Added happy + malformed-payload
tests.
## Behavior fixes
### Plaintext sanitizeTerminalText parity
`daemonBlockToPlainText` + `daemonToolPreviewToPlainText` previously
returned ANSI/bidi-control text verbatim, while markdown and HTML
paths sanitized via `sanitizeTerminalText`. A daemon emitting bidi
overrides survived clean to plaintext output — contradicting the
"copy-paste / logs" JSDoc intent. Now routes every text field through
`clean()` = `cap(sanitizeTerminalText(raw))`.
### blockquote helper applied to image_generation + subagent_delegation
R3 added the helper for thought/debug/error but missed two preview
markdown sites (`> ${text(preview.prompt)}` for image_generation,
`> ${text(preview.task)}` for subagent_delegation). Multi-line prompts
/ tasks now stay inside the blockquote.
### Default unrecognized-event branch: single debug block
Was emitting `status + debug` (2 blocks) per unknown event type. In
long sessions where the daemon adds new types an older SDK doesn't
recognize, this doubled block-consumption rate and accelerated
`maxBlocks` trimming of real content. Now emit a single `debug` block
that prefixes the event-type for adapters that want to pattern-match.
### writeIntent regex underscore-boundary aware
R4's `content` alias gate-check used `\b` word boundaries, but `\b`
doesn't match between `write` and `_` in `write_file` (both `\w`).
Fixed to `(?:^|[_-])verb(?:$|[_-])` which catches the canonical
`write_file` naming AND still rejects `prewrite_check`. Verb list
extended per wenshao's suggestion (`overwrite`/`modify`/`patch`/`generate`).
### useDaemonPendingPermissions over-subscription
Hook used `useDaemonTranscriptState()` which fires on every daemon
event (text deltas, tool updates, sidechannel). Switched to
`useDaemonTranscriptBlocks()` which only invalidates when the blocks
array reference changes — block-mutating dispatches only, thanks to
lazy COW. Same selector semantics, ~10x fewer renders in chat-heavy
sessions.
### Conformance suite: try/catch adapter
JSDoc promised "does not throw" but the loop wrapped adapter calls
without try/catch. Buggy adapters aborted the whole suite instead of
producing a structured `ConformanceFailure`. Now wrap; on throw,
capture the error message in `renderedExcerpt: "[adapter threw: ...]"`
and continue.
## Type / Quality fixes
### DaemonTranscriptState.blocks typed readonly
Runtime contract is frozen (lazy-COW poison defense), but the type
was mutable — consumers got runtime `TypeError` for in-place mutation
instead of compile errors. Now `readonly DaemonTranscriptBlock[]` so
mutation is caught at the type level.
### formatMissedRange exported / deduplicated
Helper was duplicated inline between transcript.ts (full phrasing)
and terminal.ts (terser phrasing). Exported from transcript.ts and
reused in terminal.ts to prevent future drift.
## Push-back (false-positive — see reply)
### classifySelectedPermissionOption multi-part deny (`selected:deny:access_violation`)
Re-flags the same `selected:X` design intent rejected in R2 #4. The
caller comment explicitly states a selected option resolves the prompt
even when the option id contains `deny`/`cancel`. The existing test
`cancelled-substring-permission` (payload `selected:abort`, expected
`completed`) codifies this. Daemon expresses true user-cancellation
via the `cancelled` PRIMARY token, not `selected:cancel`. Not
changing; reply directs to the same R2 #4 reasoning.
## Tests added (+10)
- normalizeAuthDeviceFlowCancelled happy + malformed
- sanitizeUrl OAuth fragment access_token rejected
- sanitizeUrl AWS/GCP/Azure SAS credential params stripped
- formatMissedRange no-gap / single-event / multi-event
- detectFileDiff content alias rejected for read-like tools
- detectFileDiff content alias accepted for write-like tools
- writeIntent word boundaries (prewrite_check NOT matched)
- conformance captures adapter throw
- unrecognized event → single debug block
- store.clearAwaitingResync clears latch
## Validation
| | |
|---|---|
| SDK tests | **172/172** (was 162, +10) |
| WebUI tests | **9/9** |
| SDK typecheck | clean |
| WebUI typecheck | clean |
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): wenshao R6 — recovery flow chicken-and-egg + pending pointer
Three Criticals from R6 review (4351217188) all pointing at real bugs
introduced by R4/R5 work — not false positives. Fixes plus regression
tests.
## Critical 1 — same-session reconnect never clears the latch
When the daemon emitted `state_resync_required`, the reducer set
`awaitingResync = true`. The webui provider dispatched
`assistant.done { reason: 'reconnected' }` after re-attaching SSE but
never called `store.clearAwaitingResync()`. Result: events flowed in
on the fresh stream but every one got dropped by the
`applyDaemonTranscriptEvent` passthrough guard. Transcript appeared
permanently frozen with no diagnostic clue (the `console.warn` fired
on each drop, but the user wouldn't necessarily check DevTools).
Fix: in `DaemonSessionProvider.tsx`, after dispatching the synthetic
`reconnected` `assistant.done`, check `awaitingResync` and clear it
BEFORE the new SSE event loop starts.
## Critical 2 — updateCurrentToolPointer breaks on undefined status
In `upsertToolBlock`, a new tool block is created with
`status: event.status ?? 'pending'`. But `updateCurrentToolPointer`
was called with raw `event.status` — when undefined, the function's
own `if (status === undefined) return;` guard short-circuited without
ever pointing at the new (visually-pending) block.
Result: `selectCurrentTool` returned `undefined` for daemon events
that omitted the explicit `status` field, while the block sat at
"pending" in the UI — invisible to the current-tool selector.
Fix: pass the EFFECTIVE status (`event.status ?? 'pending'`) so the
pointer logic mirrors the actual stored status.
## Critical 3 — clearAwaitingResync flow chicken-and-egg
The earlier (R4) JSDoc documented the recovery flow as: "re-subscribe
with `Last-Event-ID: 0`, then call clearAwaitingResync after replay
drains." But while the latch is true, EVERY non-passthrough event is
dropped at `applyDaemonTranscriptEvent`. So during the replay drain,
zero events made it into state, and clearing the latch afterward did
nothing — transcript permanently empty.
Correct flow: clear FIRST, then stream events. Updated JSDoc on both
`types.ts` interface and `store.ts` impl to document this clearly.
Added a regression test (`clearAwaitingResync AFTER dispatching events:
events ARE dropped`) that pins the correct flow in code.
## Regression tests (+3)
- `undefined status` creates pending block AND sets currentToolCallId
- clear-then-dispatch ✓ events flow
- dispatch-then-clear ✗ events dropped (correct flow documentation)
## Validation
| | |
|---|---|
| SDK tests | **175/175** (was 172, +3) |
| WebUI tests | **9/9** |
| SDK typecheck | clean |
| WebUI typecheck | clean |
## Note on doudouOUC heads-up
#4469 (main → daemon_mode_b_main sync, 45 commits since 2026-05-19)
will land soon. doudouOUC's note says rebase should be smooth (no
daemon-ui surface conflicts). Will rebase on the cron's next pass
after #4469 merges.
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): wenshao R7 — escapeMarkdownText covers `<` + details URL sanitization
Two items from wenshao R7 (one inline Suggestion + one Verification-PASS
finding). Both gate-checked as real; fixed.
## escapeMarkdownText: add `<` to escape set
Markdown rendered through markdown-it with `html: true` would
previously pass through raw `<img onerror>` / `<script>` from
reviewer-untrusted metadata fields (tool title / toolKind / status /
permission label / preview labels). The HTML render path already
escapes via `defaultEscapeHtml`; this brings markdown to the same
safety baseline.
Note: `escapeMarkdownText` is only applied to metadata fields, NOT to
assistant/user/thought body text (those are intentionally markdown
content; escaping `<` there would mangle legitimate markdown).
## markdown tool details: sanitize URL credentials when sanitizeUrls:true
`daemonBlockToMarkdown`'s `case 'tool':` branch appended
`block.details` (serialized `rawInput` JSON) through `text()` which
only handled ANSI/bidi. When `rawInput.url` contained credentials
(Basic Auth in userinfo / OAuth in `#fragment` / signed-URL query
params), the preview path correctly sanitized via `sanitizeUrl`, but
the details dump leaked the raw URL.
HTML + plaintext branches exclude details entirely, so they didn't
leak. The asymmetry meant a consumer rendering markdown + relying on
the R5 fragment-leak protection would still leak via details.
Fix: added `sanitizeUrlsInText(text)` helper that regex-replaces every
`https?://` URL in a string with its `sanitizeUrl(url)` form. Applied
to `block.details` i…
* docs(serve): v0.16-alpha known limits + SDK QWEN_SERVER_TOKEN env fallback (PR 27) (#4473)
* docs(serve): v0.16-alpha known limits + SDK QWEN_SERVER_TOKEN env fallback (PR 27)
First PR in the F5 release chain (PR 27 → 28 → 30a → 31) per the
2026-05-24 v0.16-alpha scope freeze in #4175 (text-only chat / coding
+ local-only deployment).
## SDK ergonomic micro-change (~50 LOC + 4 tests)
`DaemonClient` constructor falls back to `QWEN_SERVER_TOKEN` env
var when `opts.token` is absent — closes the asymmetry where the
daemon side already honors this var (--token CLI flag fallback,
already in main since PR 15) but the SDK forced clients to thread
it through every construction.
Properties:
- Browser-safe via `globalThis.process` indirection (the SDK is
imported by @qwen-code/webui; literal process.env access would
explode at module load on browser bundles)
- Whitespace stripped (matches daemon-side trim — handy for
`export QWEN_SERVER_TOKEN=\"\$(cat token.txt)\"` where cat adds a
trailing newline)
- Empty / whitespace-only treated as unset (a stale
`export QWEN_SERVER_TOKEN=\"\"` won't accidentally send
Authorization: Bearer with no token)
- Resolved at construction, not lazily per-request (later
process.env mutations don't affect already-built clients)
- Explicit opts.token wins over env
Tests: 4 new in DaemonClient.test.ts `bearer auth` describe
covering env fallback / explicit-wins / empty-treated-unset /
whitespace-stripped. Plus a defensive snapshot/restore on the
existing 'omits Authorization when no token' test so an
inherited test-runner export of QWEN_SERVER_TOKEN doesn't turn
that assertion into a false positive.
This SDK fallback is the entire ergonomic replacement for PR 29's
SDK env/file fallback. PR 29's other features (auto-gen daemon
token, instance-path keying, stale cleanup) remain deferred to
v0.16.x — all are DX improvements over the boot-time security gate
already shipped in PR 15.
## v0.16-alpha docs (~120 LOC markdown)
- docs/users/qwen-serve.md: new "v0.16-alpha known limits" section
enumerating product surface (text-only ✅, multimodal ❌),
deployment surface (local launchers ✅, containerized ❌, multi-
daemon ❌, BYO-token ✅), and hardening posture (boot security
gate ✅, mutation gate ✅, MCP guardrails ✅, prompt absolute
deadline ⏸️, rate limiting ⏸️, --max-body-size ⏸️). Adds an
alpha banner at the top of the file.
- docs/developers/examples/daemon-client-quickstart.md:
documents the SDK env fallback in both the Hello-daemon
intro and the Authentication section, with the "export +
no-token-arg" recommended path called out for local dev.
Verification: 125/125 DaemonClient.test.ts pass (121 existing +
4 new); 4/4 daemon-public-surface.test.ts pass (constructor
signature unchanged); tsc clean on packages/sdk-typescript;
eslint --max-warnings 0 clean on touched .ts files.
Part of #4175.
* fix(sdk): #4473 round 1 fold-in — 2 copilot doc threads adopted
T1 [copilot DaemonClient.ts:144 — stale line refs in readTokenFromEnv
JSDoc]: removed `runQwenServe.ts:175` (token resolution actually
lives at line 302-318 today, would drift again on next refactor)
and `docs/users/qwen-serve.md:173`. Replaced with stable
symbol/section references ("runQwenServe token-resolution path";
"qwen-serve user guide CLI flags section").
T2 [copilot daemon-client-quickstart.md:33 — `~/.qwen/server-token`
implies built-in path that doesn't exist]: PR 27 explicitly defers
token auto-generation + file-store fallback (PR 29 deferred features).
The example incorrectly suggested a standard file location.
Replaced with two explicit user-managed alternatives:
- `openssl rand -hex 32` one-shot
- `cat ./my-token-file` user-managed file
Both threads were accurate suggestions caught at the right time
(zero behavior change; pure docstring/example accuracy).
Verification: 125/125 DaemonClient tests pass; tsc + eslint clean
on touched files.
* docs(deploy): local launch templates for v0.16-alpha (PR 30a) (#4483)
* docs(deploy): local launch templates for v0.16-alpha (PR 30a)
Third PR in the F5 release chain (PR 27 ✅ → PR 30a → 28 → 31) per
the 2026-05-24 v0.16-alpha scope freeze in #4175 (text-only +
local-only). Pure markdown, zero code.
New `docs/users/qwen-serve-deploy-local.md` (~160 LOC) with
copy-paste-ready templates for:
- systemd user-level unit (Linux) + system-wide alternative
callout for shared dev hosts
- launchd LaunchAgent plist (macOS) with explicit "no ~ /
\$HOME expansion" warning since that's a common foot-gun
- tmux session for interactive supervision
- nohup one-liner with "not recommended" caveats
- curl smoke-check (/health + /capabilities) + token rotation
walkthrough (covers all four launchers)
All templates inline `QWEN_SERVER_TOKEN=...` directly per the BYO-
token guide PR 27 added to qwen-serve.md. No auto-gen, no token-
store infrastructure — user generates via openssl rand -hex 32 and
pastes into the unit/plist. Each template carries an explicit
"DO NOT COMMIT this file with a real token" comment at the token
line.
Cross-references the SDK env fallback PR 27 added: one shell-level
`export QWEN_SERVER_TOKEN=\$(cat token-file)` covers both the
daemon-side flag fallback AND the SDK-side DaemonClient
construction fallback. Restart-and-crash semantics cross-link to
the existing Durability model section rather than duplicate.
Cross-links from qwen-serve.md "v0.16-alpha known limits" line 32
(forward reference "templates land in PR 30a" becomes a live
link) and "What's next" section (natural discovery hub at the
bottom). _meta.ts gets a sibling nav entry under qwen-serve.
Out of scope (deferred to v0.16.x or later): containerized
deployment (PR 30b), cross-host federation, auto-gen tokens,
native Windows service. WSL2 footnote covers Windows users for
free without committing to an unvalidated nssm wrapper.
Anchor integrity verified: links to #v016-alpha-known-limits /
#authentication / #durability-model all resolve to live sections
in qwen-serve.md.
Part of #4175.
* fix(docs): #4483 round 1 fold-in — 14 review threads adopted
All 14 unresolved threads (5 copilot + 9 wenshao) source-verified
and ADOPTED. Net effect: every code-block in the doc is now
copy-paste-runnable + the security / restart / log-location
posture matches what real local-deployment operators expect.
CRITICAL fixes:
T1 + T2 + T3 + T12 [copilot/wenshao — `--bind` flag does NOT exist]:
Source-verified at packages/cli/src/commands/serve.ts:58 — the CLI
flag is `--hostname` (with `--port`). All 4 templates (systemd /
launchd / tmux / nohup) had `--bind 127.0.0.1` which would fail at
startup with "unknown option". Replaced with `--hostname 127.0.0.1
--port 4170` (explicit port for parity with launchd
ProgramArguments). Defaults are 127.0.0.1:4170 already, but
explicit-is-better here for copy-paste docs.
T6 [wenshao Critical — systemd missing loginctl enable-linger]:
Without `loginctl enable-linger`, the user-level systemd instance
shuts down at logout / does not start at boot. "Across reboots"
was a stated goal of the doc. Added the linger command to the
systemd manage block + a paragraph explaining why it's required
for headless dev boxes.
T11 [wenshao — nohup missing workspace cd]:
Daemon defaults to process.cwd() — running `nohup qwen serve` from
~ or /tmp silently binds the wrong workspace, causing every
POST /session with the expected cwd to return 400 workspace_mismatch.
Wrapped in `bash -c 'cd ~/your-project && qwen serve ...'` and added
a paragraph explaining the silent foot-gun.
SUGGESTION fixes (security / correctness):
T7 [wenshao — systemd Environment= exposes token in unit file]:
Replaced inline `Environment=QWEN_SERVER_TOKEN=...` with
`EnvironmentFile=%h/.qwen-serve-token-env`. Unit file is typically
644 (world-readable); EnvironmentFile keeps the token in the
user's chmod 600 file. Added a setup step that wraps the existing
token in KEY=value form for systemd to read.
T8 [wenshao — launchd /tmp logs have 3 problems]:
Symlink-attack risk on shared workstations + truncate-on-load
destroys diagnostic logs at exactly the wrong moment + macOS
periodic-daily cleans /tmp after 3 days. Switched to
`~/Library/Logs/qwen-serve/{out,err}.log`. Added the mkdir step
in the manage block + a paragraph noting log truncation on
unload→load.
T9 [wenshao — launchd KeepAlive=true respawns on clean SIGTERM]:
Bare `<true/>` makes `kill <pid>` impossible (daemon respawns
immediately). Switched to `<dict><key>SuccessfulExit</key><false/></dict>`
to match systemd Restart=on-failure semantics. Added
`ThrottleInterval=10` to mirror systemd RestartSec=5 and prevent
restart storms on persistent failures.
T14 [wenshao — plist itself needs chmod 600]:
The plist embeds the inline token. Files in ~/Library/LaunchAgents/
default to 644. Added `chmod 600 ...plist` to the manage block.
T4 [copilot — /capabilities auth wording wrong]:
Doc said /capabilities "always requires auth" — but it's only
gated when a token is configured (or --require-auth is set). On
a zero-config loopback boot neither route requires a header.
Reworded "Verifying the daemon is up" section to call out both
paths ("templates above all configure a token, so Authorization
is needed in practice").
T5 [copilot — token rotation missing chmod 600]:
Step 1 of token rotation now writes `~/.qwen-serve-token` AND
`~/.qwen-serve-token-env` AND chmods both 600. Mirrors the
initial generation block.
T10 [wenshao — restart-and-crash section self-contradictory]:
Said sessions "re-attach via Last-Event-ID resume" then immediately
"a restart drops sessions". Rewrote to clearly distinguish
WITHIN-process disconnects (Last-Event-ID covers them, in-memory
ring) from RESTART (drops everything; cross-restart durability
not in v0.16-alpha). Also documented the systemd vs launchd
KeepAlive semantics difference.
T13 [wenshao — bullet structure under "Generate a bearer token"]:
The original bullet list framed `--token CLI flag` and the env
var as if one consumed the other. Rewrote as a paragraph: "daemon
reads token from either --token or QWEN_SERVER_TOKEN; SDK falls
back to QWEN_SERVER_TOKEN; one shell-level export covers both".
Verification: `grep -c '\-\-bind ' docs/users/qwen-serve-deploy-local.md`
returns 0 (all bind→hostname); section structure intact (9 H2
sections, expected); 4 cross-link anchors to qwen-serve.md still
resolve (#authentication / #v016-alpha-known-limits /
#durability-model + the original out-of-scope list).
Net diff: +220/-160 (mostly net-additive — every fix added
context paragraphs explaining "why").
* fix(docs): #4483 round 2 fold-in — 2 wenshao threads adopted (T15 noise resolved)
T16 [wenshao — hardcoded /usr/local/bin/qwen breaks nvm/Volta/Apple Silicon Homebrew users]:
Both systemd `ExecStart` and launchd `ProgramArguments` had
hardcoded `/usr/local/bin/qwen` — only correct for Linuxbrew
/ Intel macOS Homebrew / manual global install. Most Node
developers use nvm (~/.nvm/...), fnm, Volta, or Homebrew on
Apple Silicon (/opt/homebrew/bin/qwen) and would hit
"No such file or directory" on first `systemctl --user start`.
Switched both templates to `/PATH/TO/qwen` placeholder + added a
prominent callout block above each template listing the common
locations (Linuxbrew, nvm, fnm, Volta on Linux; Apple Silicon
Homebrew, Intel Homebrew, nvm, Volta on macOS) and explicitly
pointing at `which qwen` as the discovery step. Inline
comments at the ExecStart / ProgramArguments lines reinforce
"systemd does NOT read $PATH" / "launchd does NOT read $PATH".
T17 [wenshao — shell-wide export leaks token to every subprocess]:
Added a callout block immediately after the `export QWEN_SERVER_TOKEN=...`
setup step warning against adding it to .bashrc/.zshrc on shared
workstations. Profile-level export exposes the token to every
child process (IDE subprocesses, browser debuggers, `npm`
scripts from unrelated projects). Points users at the systemd
EnvironmentFile= / launchd EnvironmentVariables mechanisms below
for persistent setups since both scope the token to just the
daemon process.
T15 [wenshao — empty "test" comment]:
Resolved without code change. Comment body was just "test";
appears to be an accidental post.
Verification: `/usr/local/bin/qwen` now only appears inside the
explanatory "common locations" prose blocks (NOT in the actual
templates, which use `/PATH/TO/qwen` placeholder); zero `--bind`
left in the file.
* feat(daemon+sdk): cross-client real-time sync completeness (#4484)
* feat(acp-bridge): cross-client real-time sync completeness (5 fixes)
Audit (cross-client sync, 2026-05-24) of the daemon's per-session
EventBus fan-out surfaced gaps where one client's actions did not
propagate to other SSE-subscribed clients on the same session. This
commit closes five of them — all bridge-layer fixes, no agent-side
changes — with regression tests covering the new sentinel frame.
## 1. user_message_chunk echo on the interactive prompt path
The agent's `Session#executePrompt` (Session.ts:556+) forwards the
prompt straight to the LLM without emitting `user_message_chunk` to
the session bus. The cron path (Session.ts:1402) and HistoryReplayer
(HistoryReplayer.ts:65) DO emit it; only the interactive path was the
outlier. Result: when client A sent a prompt, other clients on the
same session saw only the agent's reply, never the input — they had
to wait for a session reload to learn what A had asked.
Fix: `echoPromptToSessionBus` helper publishes one `user_message_chunk`
per content block of the incoming `PromptRequest`, stamped with the
envelope-level `originatorClientId` so SDK consumers with
`suppressOwnUserEcho: true` filter the echo on the originator's UI.
Multi-modal blocks (image / audio / resource) pass through verbatim
for future-compat with Core's multi-modal echo work.
`_meta.source: 'bridge-echo'` distinguishes bridge-synthesized echoes
from agent-emitted content. Used today only for diagnostic visibility;
becomes load-bearing once SDK-side dedup matures (deferred follow-up).
## 2. prompt_cancelled broadcast in cancelSession
`bridge.cancelSession` forwarded the ACP cancel notification to the
agent and resolved pending permissions, but did NOT publish any event
on the session bus. Other clients learned that A had cancelled only
by absence of further `agent_message_chunk` frames — heuristic and
late.
Fix: emit a `prompt_cancelled` envelope before the ACP forward so
peer clients see the cancel as a first-class event. Envelope-level
`originatorClientId` identifies the cancelling client (the one calling
`POST /cancel`). Permission-resolution events generated by the
subsequent `cancelPendingForSession` continue to omit an originator
(those are system-initiated wind-downs, not user-voted).
## 3. replay_complete sentinel in EventBus.subscribe
A consumer attaching via `Last-Event-ID: <n>` had no positive signal
when the replay loop drained — they had to heuristically time out the
catch-up spinner. The state-resync path already had a synthetic
`state_resync_required` frame; the success path lacked parity.
Fix: emit an id-less `replay_complete` synthetic frame at the end of
the replay loop (same pattern as `client_evicted` / `state_resync_required`
— no slot in the per-session monotonic sequence). Fires both when
replay actually delivered frames AND when there was nothing to replay
(empty ring), so the consumer always sees the transition from
"catching up" to "live". `data.replayedCount` is the actual count of
force-pushed frames (not derived from id arithmetic, which would
over-count when the state-resync path leaves a hole before the ring's
earliest id).
3 EventBus test cases updated to assert the sentinel frame ordering.
## 4. originatorClientId on session_metadata_updated envelope
`updateSessionMetadata` resolved the trusted client id for validation
(`resolveTrustedClientId(entry, context.clientId)`) but did not stamp
it on the broadcast envelope. UIs couldn't attribute the rename to a
specific client. Sibling events (`model_switched`, `approval_mode_changed`)
all stamp envelope-level `originatorClientId`; this brings the metadata
broadcast to parity.
## 5. originatorClientId on session_closed envelope
`session_closed` carried the closing client in `data.closedBy` only,
but every other event the bridge publishes uses the envelope-level
`originatorClientId` field. Added the envelope-level stamp (kept
`data.closedBy` for back-compat) so SDK consumers can read the
attribution from the same place across all event types.
## Out-of-scope (deferred to follow-up)
The cross-client sync audit also surfaced 3 items that require larger
design discussion:
- **In-session ACP `setModel` bus emit** — `Session.ts#setModel` calls
`config.switchModel` directly without going through the bridge's
publish path. Fixing this requires a new ACP sessionUpdate type
(`current_model_update`, parallel to existing `current_mode_update`)
or a side-channel callback from agent to bridge.
- **Workspace-wide broadcast of non-persisted approval-mode changes** —
current behavior only broadcasts workspace-wide on `persist=true`;
the design intent of the persist flag relative to multi-client
visibility needs alignment.
- **Serialize `setSessionApprovalMode` through a queue** — analogous to
`entry.modelChangeQueue` for `setSessionModel`. Race-condition fix.
- **Reconcile `permission_resolved.originatorClientId` semantics** —
it currently carries the VOTER's clientId; `permission_request`
carries the prompt originator. SDK consumers need to special-case
the type. Either change to consistent semantics or add a separate
`voterClientId` field.
These are tracked as follow-ups, not in this PR.
## Validation
| | |
|---|---|
| Bridge tests | 291/291 pass |
| eventBus tests | 105/105 pass (3 updated) |
| TypeScript | clean |
* test(acp-bridge): multi-client user_message_chunk echo coverage
Adds two integration tests for the cross-client sync fix:
- "echoes user_message_chunk to ALL session subscribers": two SSE
subscribers (A + B) on the same session; client A sends a prompt;
asserts BOTH receive the user_message_chunk with the originator
stamp + `_meta.source: 'bridge-echo'`. This is the core multi-client
property — a prompt from one client is visible to every subscriber,
not just the originator.
- "echoes one user_message_chunk per content block (multi-modal)":
a two-block prompt (text + resource_link) produces two echo frames
in order.
Validates the bridge-layer echo end-to-end through the real
EventBus + subscribeEvents path, not just a unit of the helper.
* feat(daemon+sdk): address review — abort-path cancel, SDK recognition, hardening
Round-2 review of the cross-client sync work. Adds the sibling cancel
path, SDK-side recognition of the two new event types so consumers can
react instead of debug-dropping, plus hardening + test coverage flagged
in review.
## Bridge (acp-bridge)
- Abort-path cancel broadcast: the `sendPrompt` `onAbort` closure
(originator SSE disconnect — the most common cancel trigger: tab
close, network drop, laptop sleep) previously resolved permissions +
forwarded ACP cancel WITHOUT publishing `prompt_cancelled`. Only the
explicit `cancelSession` route emitted it. Extracted a shared
`broadcastPromptCancelled` helper, called from both paths.
- echoPromptToSessionBus hardening: read `req.prompt` directly (no
`unknown` cast so a future SDK type change is a compile error); cap
echoed blocks at MAX_ECHO_CONTENT_BLOCKS (256) to bound fan-out + ring
pressure; corrected the non-text comment (all ContentBlock variants
are published verbatim, not "metadata-only").
- Documented prompt_cancelled's "cancel requested, not confirmed"
semantic and the intentional unconditional broadcast.
## SDK (sdk-typescript)
The bridge now produces `prompt_cancelled` and `replay_complete`.
Without SDK recognition they fall through the normalizer default to
`debug` and the reducer drops them — consumers (VSCode ext, web UI,
React CLI) can't react. Added:
- both types to DAEMON_KNOWN_EVENT_TYPE_VALUES
- normalizer cases → typed UI events `prompt.cancelled` /
`session.replay_complete`
- DaemonUiPromptCancelledEvent + DaemonUiReplayCompleteEvent types,
union + barrel re-exports
- reducer: prompt.cancelled runs propagateCancellationToInFlightTools
(clears peer-cancelled tool spinners, same idempotent path as
assistant.done(cancelled)); session.replay_complete no-ops on blocks
- terminal projection cases for both
- guarded the existing awaitingResync console.warn with optional
chaining so the no-console lint rule passes without referencing the
member in the guard condition
## Tests
- bridge.test.ts: prompt_cancelled attribution; session_closed +
session_metadata_updated envelope originatorClientId
- eventBus.test.ts: resync + replay paths assert the trailing
replay_complete sentinel (replayedCount = actual delivered frames)
- daemonUi.test.ts: normalize prompt_cancelled / replay_complete (incl.
empty-ring zero count); reducer cancellation propagation; replay no-op
## Validation
| | |
|---|---|
| acp-bridge tests | all pass |
| SDK tests | 637/637 |
| SDK + bridge typecheck | clean |
| webui consumer typecheck | clean |
## Deferred (docs/qwen-daemon/cross-client-sync-followups.md)
Ghost-echo-on-forward-failure; in-session ACP setModel bus emit;
approval-mode workspace broadcast + serialization; permission_resolved
voter semantics.
* test(acp-bridge): cover prompt_cancelled on the sendPrompt abort path
Review follow-up: the existing `prompt_cancelled` test only exercised
the explicit `cancelSession` route. The `onAbort` path (originator SSE
disconnect — tab close / network drop / laptop sleep, the most common
production cancel trigger) had no test asserting the broadcast reaches
peer subscribers. A future refactor dropping the `broadcastPromptCancelled`
call from `onAbort` would have passed silently and re-opened the
cross-client gap.
New test: hangs the prompt via a non-resolving `promptImpl`, attaches a
peer subscriber, aborts the originator's `sendPrompt` signal mid-flight,
and asserts the peer receives `prompt_cancelled` with the originator's
`clientId`. Releases the hung prompt before shutdown.
acp-bridge: 183/183 pass.
---------
Co-authored-by: 秦奇 <[email protected]>
* feat(serve): add POST /session/:id/recap (#4504)
* feat(serve): add POST /session/:id/recap
Wraps generateSessionRecap (core/services/sessionRecap.ts) so daemon
clients can fetch a one-sentence "where did I leave off" summary
without driving the agent through a full prompt turn. Mirrors the
ext-method roundtrip used by /session/:id/approval-mode — bridge
forwards `qwen/control/session/recap` to the ACP child, which calls
the existing core helper against the per-session GeminiClient history.
- Route: non-strict mutation gate (parity with /prompt — costs tokens
but mutates no state)
- Capability tag: `session_recap`
- SDK: `client.recapSession(sessionId, opts)` +
`session.recap(opts)` convenience wrapper
- 60s bridge-side backstop timeout; client-disconnect aborts the
HTTP wait (LLM call in the child still completes — recap is short)
- Recap is best-effort: short history / transient model failure
surfaces as 200 with `recap: null`, not an error
Tests cover the route (200 happy path, 200 null recap, client-id
context, 404 on unknown session, malformed client-id, non-strict gate
posture), the bridge ext-method roundtrip (success, null recap,
SessionNotFoundError), the SDK client + session-client wrappers
(URL encoding, body, headers, signal propagation, 404 throw), and a
public-surface type lock for `DaemonSessionRecapResult`.
Closes part of #4175 (Top 5 ROI port #1 from the daemon coverage gap
inventory). Targets daemon_mode_b_main integration branch.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(serve): reconcile recap cancellation docs with actual v1 behavior
Per chiga0's review on #4504 (option 1 — match docs to reality rather
than wire up cosmetic AbortController plumbing). The route, design doc,
and protocol reference all claimed "client disconnect aborts the
bridge-side wait" via `res.once('close')`, but the route has no such
listener and the bridge accepts no `AbortSignal`. The only ceilings
are the 60s `SESSION_RECAP_TIMEOUT_MS` backstop and the transport-
closed race against ACP channel death.
Wiring an HTTP-side AbortController in isolation would be cosmetic
because the ACP child handler also passes a never-aborting
`AbortController().signal` to the core helper (no cross-process abort
plumbing yet) — e2e cancel needs both layers. Recap is short (~1–5s,
`maxOutputTokens: 300`), so the absent cancellation is acceptable for
v1; a request-id-based cancel ext-method can land in a follow-up.
Also adds two known-limit bullets to the user guide per chiga0's other
minor notes: token-cost amplification on no-token loopback (no
per-route rate limit) and concurrent-recap safety (side-query reads
chat history via `GeminiClient.getChat().getHistory()` snapshot and
runs through a separate `BaseLlmClient`, never mutating the session's
`GeminiChat`).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(serve): finish recap cancellation reconciliation in acpAgent ext-method
The previous commit (058bde70f) reconciled the cancellation narrative
in 3 doc files + the route comment in server.ts, but missed the inline
comment inside the ACP child's `SERVE_CONTROL_EXT_METHODS.sessionRecap`
handler. That comment still claimed "Client disconnect aborts the
bridge-side wait" — the exact false statement 058bde70f was meant to
remove from the codebase. Worse, the new server.ts comment from 058bde70f
points readers at this handler for corroboration ("This matches the ACP
child's `acpAgent.ts` handler ..."), so a reader following that crumb
would land on a comment saying the opposite.
Per @wenshao's `[Suggestion]` review on #4504, applying his suggested
replacement verbatim. Comment-only change; no behavior delta.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(serve): finish recap cancellation reconciliation across bridge + SDK JSDocs
Third pass on the same task. wenshao caught one more spot in
`bridge.ts:330` (JSDoc for `SESSION_RECAP_TIMEOUT_MS` claimed "actual
cancellation on client disconnect is handled at the HTTP route layer"
— the exact opposite of what the route comment + protocol doc + design
doc + acpAgent comment all now say).
Pre-empting another round-trip by sweeping the rest of the codebase
and fixing the two remaining misleading SDK JSDocs in the same go:
- `DaemonClient.recapSession`: previously said "cancellation is via
the optional signal" without qualifying that the signal aborts ONLY
the local HTTP fetch. The daemon-side wait + the child-side LLM call
both ignore it. Spelled out the layered reality: signal → fetch
cancellation only; bridge → 60s backstop; ACP child → always runs to
completion. Also corrected the "bypasses fetchTimeoutMs" claim — the
raw `_fetch` simply doesn't go through that wrapper at all.
- `DaemonSessionClient.recap`: same clarification on the wrapper that
delegates to `recapSession`.
Comment-only changes; no behavior delta.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(daemon): add voterClientId to permission_resolved (A4) (#4539)
* feat(daemon): add voterClientId to permission_resolved (A4)
Resolve the originator/voter ambiguity on permission_resolved without
breaking wire or SDK consumers (design PR #4511, A4):
- Wire: the mediator now emits data.voterClientId alongside the envelope
originatorClientId on permission_resolved (same value, the resolving
voter). Both are omitted together for no-voter resolutions (timer expiry,
session-closed, loopback voter with no clientId). permission_already_
resolved is unchanged (deliberately stamps neither).
- SDK: the normalizer exposes an optional voterClientId on the
permission.resolved typed event, reading data.voterClientId and falling
back to the envelope originatorClientId for daemons predating the field.
originatorClientId stays available on the base (no rename, no break).
voterClientId is the canonical, unambiguous name; originatorClientId on
permission_resolved is kept as a deprecated alias (it means the voter here,
unlike the prompt originator on permission_request).
Tests: permissionMediator emits voterClientId (+ omits both with no voter);
normalizer surfaces voterClientId from data, falls back to originatorClientId,
omits it for no-voter. acp-bridge 297, sdk daemon-ui 186 pass.
* test(daemon): cover the prompt-originator vs voter distinction (A4)
Add the distinguishing case wenshao asked for: client A submits the prompt
(permission_request.originatorClientId === A) while a different client B casts
the resolving vote (permission_resolved.voterClientId === B), and assert the
two differ — the disambiguation A4 exists to enable. The prior tests only
covered the same-client value.
---------
Co-authored-by: 秦奇 <[email protected]>
* feat(serve): --allow-origin <pattern> CORS allowlist (T2.4 #4514) (#4527)
* feat(serve): --allow-origin <pattern> CORS allowlist (T2.4 #4514)
Replace the unconditional `denyBrowserOriginCors` 403-wall with a
configurable allowlist when `--allow-origin <pattern>` is set. Each
pattern is either `*` (any origin, refuses to boot without a bearer
token) or a canonical URL origin validated by round-tripping through
`new URL(...).origin`. Matched origins receive standard CORS response
headers (`Access-Control-Allow-Origin: <echoed>`, `Vary: Origin`,
methods/headers/max-age) plus 204 short-circuit for OPTIONS preflight;
unmatched origins keep today's 403 envelope. `Origin: null` is always
rejected even under `*`. Conditional capability tag `allow_origin`
advertised when the flag is set so SDK/webui clients can pre-flight.
When `--allow-origin` is unset the install path is unchanged and
today's behavior is preserved bit-for-bit. Loopback self-origin hits
are unaffected — the existing demo-page Origin-strip shim runs first.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(serve): align --allow-origin '*' wording with the actual boot gate
Copilot review on #4527 caught a doc/code mismatch: 5 spots said `*` is
"only safe with --require-auth" but the actual boot check refuses `*`
only when no bearer token is configured (any source: --token, env, or
--require-auth). Update the wording in all 5 spots to match the
implementation, and call out the secondary loopback-only caveat that
/health and /demo remain pre-auth on loopback unless --require-auth is
set — operators with a `*` allowlist on loopback should pair with
--require-auth for full hardening.
Tightening the code instead would break legitimate `*` + token + loopback
dev workflows that want /health to remain reachable for k8s/Compose
probes; the actual API surface is gated regardless of --require-auth.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address allow-origin review feedback
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): in-session model switch reaches the bus (A1) (#4546)
* feat(daemon): in-session model switch reaches the bus (A1)
Implements A1 from the side-channel coordination design (#4511): a /model
slash command or plan-mode model switch now reaches attached clients, where
previously only the HTTP POST /session/:id/model path published model_switched.
Transport (per design v7): current_model_update is NOT an ACP SessionUpdate
variant (the type is the external @agentclientprotocol/sdk union — it has
current_mode_update but no model equivalent), so the agent emits the change
over the agent->bridge extNotification side-channel.
- Agent: Session.setModel emits a `qwen/notify/session/model-update`
extNotification after switchModel resolves (success-only; captures the
previous model id). Fire-and-forget — a failed notification never fails the
switch.
- Bridge: BridgeClient.extNotification demuxes it to a model_switched bus
event (currentModelId -> data.modelId), SUPPRESSED while the bridge is
driving its own model roundtrip (entry.modelRoundtripInFlight, set around
setSessionModel / applyModelServiceId) so the HTTP path — which also flows
through Session.setModel — does not double-publish. Structured demux log
records promoted / suppressed / dropped decisions.
Scope: this is the core A1 path + suppress + observability. The §2.2
post-roundtrip reconciliation and the timeout-race staleness check (for the
rarer concurrent-in-session / timed-out-then-late races documented in the
design) are a tracked follow-up.
Tests: agent emits the notification on success and not on failure; bridge
promotes it to model_switched when idle and suppresses it during a bridge
roundtrip. acp-bridge 302 pass.
* fix(daemon): address review on A1 in-session model update
- Update the extNotification JSDoc to list both recognized methods
(mcp-budget-event + model-update).
- Drop previousModelId from the model-update notification — nothing consumed
it end-to-end (dead data); model_switched is {sessionId, modelId}.
- setSessionModel: publish model_switched INSIDE the modelChangeQueue work
callback (while modelRoundtripInFlight is still true), mirroring
applyModelServiceId, so the agent notification can't slip through after the
flag clears if transport ordering ever changes.
acp-bridge 302 pass; typecheck + lint clean.
* test(daemon): cover A1 demux defensive branches
Add the three branch tests wenshao flagged: malformed model-update params
(non-string ids → early return, no emit), unknown sessionId (dropped, not
buffered), and originatorClientId propagation (a model-update during an
in-flight prompt inherits activePromptOriginatorClientId on the promoted
model_switched).
---------
Co-authored-by: 秦奇 <[email protected]>
* feat(serve): prompt absolute deadline + SSE writer idle timeout (#4514 T2.9) (#4530)
Squashed: 8 commits for clean rebase onto daemon_mode_b_main.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* Feat/daemon react cli (#4380)
* feat(daemon): add shared UI transcript layer
* fix(daemon): address ui review feedback
* test(daemon): cover raw event diagnostics option
* fix(daemon): address latest ui review
* fix(daemon): cover reconnect and status edge cases
* fix(daemon): guard prompt busy cleanup
* feat(daemon): add shared UI transcript layer
* fix(daemon): address ui review feedback
* test(daemon): cover raw event diagnostics option
* fix(daemon): address latest ui review
* fix(daemon): cover reconnect and status edge cases
* fix(daemon): guard prompt busy cleanup
* fix(daemon): handle trimmed tool updates
* fix(daemon): cap transcript text blocks
* fix(daemon): dedupe trimmed tool diagnostics
* fix(daemon): harden webui transcript edge cases
* fix(daemon): preserve webui daemon events
* fix(daemon): address latest ui review comments
* feat(web-shell): add daemon-backed UI shell
* feat(web-shell): improve session routing and slash commands
* feat(daemon): add shared UI transcript layer
* fix(daemon): address ui review feedback
* test(daemon): cover raw event diagnostics option
* fix(daemon): address latest ui review
* fix(daemon): cover reconnect and status edge cases
* fix(daemon): guard prompt busy cleanup
* fix(daemon): handle trimmed tool updates
* fix(daemon): cap transcript text blocks
* fix(daemon): dedupe trimmed tool diagnostics
* fix(daemon): harden webui transcript edge cases
* fix(daemon): preserve webui daemon events
* fix(daemon): address latest ui review comments
* fix(daemon): close latest ui review nits
* fix(daemon): harden ui review edges
* fix(daemon-ui): address wenshao 2 Critical findings (#4328 review)
## Critical #1 — 401/403 reconnect storm + transcript wipe
`DaemonSessionProvider`'s reconnect loop kept retrying `createOrAttach` on
401/403 even with `autoReconnect: true`. Each cycle:
- hit the daemon with the same bad token → 401 again
- cleared the session handle
- the next successful attempt (if token magically recovered) would
receive a different sessionId, triggering the `store.reset()` branch
at line 143 and wiping the user's transcript
- no terminal "auth failed" state surfaced to the user
Fix: split `TERMINAL_SESSION_HTTP_STATUSES` into `AUTH_FAILURE_HTTP_STATUSES`
(401, 403) and the rest (404, 410). On auth failure, return from the
reconnect loop unconditionally regardless of the `autoReconnect` flag —
these are credential failures, not transient. The user must update
credentials; daemon spam must stop.
`extractHttpStatus` helper factored out of `isTerminalSessionHttpError` to
share between the two predicates.
## Critical #2 — rawInput / rawOutput leaking secrets to UI
`normalizer.normalizeToolUpdate` forwarded `rawInput` / `rawOutput`
verbatim onto `DaemonUiToolUpdateEvent` → `DaemonToolTranscriptBlock`. The
`details` projection was redacted via `stringifyRedactedJson` /
`redactSensitiveFields`, but the underlying `rawInput` / `rawOutput`
fields were unredacted. Any UI component that read those fields directly
(ShellToolCall, WriteToolCall, JSON debug panels) leaked the raw values
to the DOM.
Example: `{ command: 'curl', apiKey: 'sk-prod-...' }` had `apiKey`
redacted in `details` but exposed verbatim on `rawInput`.
Fix: apply `redactSensitiveFields` to both `rawInput` and `rawOutput`
ONCE at the normalizer boundary, then reuse the redacted shape for the
`details` projection. Downstream is uniformly safe; no double traversal.
## Tests (49/49 pass)
- SDK `daemonUi.test.ts` (36 tests, +1) — new test `redacts sensitive
fields in tool.update rawInput and rawOutput at normalizer boundary`
verifies full-event string scan finds zero secret values + structural
keys preserved with values `'[redacted]'`.
- WebUI `DaemonSessionProvider.test.tsx` (13 tests, +2) — new tests
`breaks out of the reconnect loop on 401 / 403 auth failures even when
autoReconnect is true` and `still reconnects on 404 / 410
session-not-found errors when autoReconnect is true` lock in the
asymmetry: auth failure → 1 attempt only; session-not-found → retries
until success.
## Out of scope (declined / deferred — see PR review reply)
- CRIT #3 `withActionTimeout` test coverage gap → behavior correct,
test-only follow-up (avoids PR bloat)
- Suggestions #4-7 → 4 nice-to-haves, deferred to keep PR focused on
production-correctness fixes
Generated with AI
Co-authored-by: Claude Opus 4.7 <[email protected]>
* fix(daemon-ui): redact tool details in web transcript
* feat(web-shell): align daemon UI interactions
* fix(web-shell): address daemon UI review comments
* feat(web-shell): sync independent web-shell with lib build, i18n, and daemon serve enhancements
Bring in the independently developed web-shell package with full lib
build support (vite.lib.config.ts, tsconfig.lib.json), i18n layer,
new dialogs (Help, Theme, ReleaseSession), composer hiding during
approvals, and SDK dependency restructured as peerDependency. Also
adds daemon serve routes (detach endpoint, rename persistence) and
fixes acp-bridge testUtils missing cancelImpl.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell): address daemon UI review comments
- Strip token from URL after caching (prevents Referer/history leak)
- Add URL scheme allowlist for markdown links/images (block javascript:)
- Add CORS restriction in vite dev server
- Handle state_resync_required event (reset store)
- Reset promptStatus on SSE disconnect
- Handle 401/403 in reconnect loop (no retry on auth failures)
- Heartbeat consecutive failure detection (3 strikes → disconnect)
- Strip <style> tags in SVG sanitization
- Replace naive diff with LCS-based buildUnifiedDiff
- Fix inputHighlight decoration ordering (sort before add)
- Add isEditableTarget guard in useDelayedGlobalKeyDown
- Fix AskUserQuestion keyboard handler (no capture phase)
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell): address second-round review Critical issues
- Add size guard to buildUnifiedDiff (fallback when n*m > 250k)
- Strip SVG animation elements (animate, set, animateTransform, animateMotion)
- Reset promptStatus to idle on state_resync_required
- Restrict getAllowedDaemonOrigin to same port as page origin
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell): address remaining PR #4380 review issues
- SVG sanitizer: strip style/use/image/feImage/mpath, block external hrefs
- Markdown: split isSafeHref/isSafeImageSrc (allow data:image for img only)
- Heartbeat: fire disconnect once at 3 failures, self-heal on success
- state_resync_required: reset store and reconnect (remove dead code)
- Auth 401/403: log error, stop reconnect loop, show error state
- replaceSessionUrl: delete ?token param to prevent leak
- removeDaemonTokenFromUrl() called at module init
- Vite dev server: cors: false
- killSession: forgetSession before byId.delete (prevent lost events)
- inputHighlight: collect ranges and sort before adding to builder
- useDelayedGlobalKeyDown: isEditableTarget guard from shared utils
- buildUnifiedDiff: proper O(nm) LCS, hasDiffContent lightweight check
- detachDaemonClient: restore console.warn for observability
- App.tsx: use rAF-coalesced messageBlocks in extractPendingPermission
- extractPendingPermission: extract toolCallId from toolCall record
- vite.lib.config: wrap CSS injection in try/catch for CSP
- Add test coverage: server routes, SDK methods, transcriptAdapter
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell): address third-round PR #4380 review issues
Critical fixes:
- ToolApproval: reset submittedRef via useEffect on request.id change
- Effect cleanup: reject pendingSessionLoadRef on dispose
- sanitizeSvg: strip style attributes with external url() values
Suggestion fixes:
- <use> elements: keep fragment-only href, strip external (+ xlink:href fallback)
- SAFE_IMAGE_DATA_URI: remove svg+xml (can load external subresources)
- extractStreamingState: accept blocks directly, remove state dependency
- coalescedState useMemo removed — rAF coalescing no longer defeated
- Auth failure log: use missingSessionId instead of already-cleared vars
- newSession(): reject pending loadSession promise
- COPY_MESSAGES: wire constants to copyFromLastAssistantMessage
- Add 39 tests for isSafeHref, isSafeImageSrc, sanitizeSvg
- Add 3 tests for toolCallId extraction fallback
- Fix test fixtures: resolved: undefined, clientReceivedAt: 1
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell): delegate readWorkspaceFile to SDK client
Replaces the manual fetch() call with session.client.readWorkspaceFile()
which provides fetchWithTimeout (30s default) and error normalization.
Ensures DaemonClient baseUrl is always absolute by falling back to
window.location.origin in proxy mode.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell): address fourth-round PR #4380 review issues
- Fix suppressedOwnUserEchoCountRef not decrementing on prompt failure
- Add heartbeat status guard to prevent overwriting 'connecting' state
- Abort stale activePrompts when SSE session disconnects
- Truncate displayName to 256 chars in renameSession endpoint
- Fix DiffView counting +++ / --- header lines as additions/deletions
- Preserve existing command properties in mergeCommands
- Fix bridge cwd override by params spread order
- Validate all href attributes on SVG <use> elements
- Extend external url() check to all SVG attributes, not just style
- Unify detachDaemonClient baseUrl with DaemonClient construction
- Delegate loadMcpTools to SDK client instead of returning stub
- Add createAtCompletionSource factory with baseUrl/token fallback
- Reset AskUserQuestion state on request.id change
- Add useEffect cleanup for queue drain setTimeout
- Suppress replay_complete from reaching UI as unrecognized event
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell): address fifth-round PR #4380 review issues
- Use safeWorkspaceCwd in buildWorkspaceToolsStatus for consistency
- Wire loadMcpTools to return SDK tools instead of hardcoded empty array
- Consolidate WebShellMcpToolsStatus types (remove duplicate in McpDialog)
- Abort active prompts in loadSession before switching sessions
- Pass daemon credentials to @-completion source via Editor props
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell,cli): address PR #4380 review issues and fix duplicate user message
- Remove Session#executePrompt's emitUserMessage() call to eliminate
duplicate user_message_chunk events (bridge-echo is the single source)
- Move removeDaemonTokenFromUrl() to main.tsx entry point (S19)
- Add mount-grace, interaction guard, safe default index to ToolApproval (Critical#1)
- Fix stale credential capture in Editor @-completion (Critical#3)
- Add submittedRef guard to AskUserQuestion, remove unsafe fallback (S18/S23)
- Use .then() pattern for clipboard writeText (S17)
- Add i18n for approval dialog and rename messages (S20)
- Add session load timeout (S15)
- Distinguish MCP error types with DaemonHttpError (S12)
- Clear stale heartbeat error on success (S13)
- Fix null vs undefined clientId check in server detach (S16)
- Add daemon.test.ts for origin validation coverage
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell,cli): address PR #4380 R9 review — detach loose equality, ToolApproval stale refs, session load timeout leak
- server.ts: change `clientId == null` to `=== null` so absent header falls through to detachClient instead of hanging the request
- server.test.ts: add test for detach without X-Qwen-Client-Id header
- ToolApproval.tsx: use refs to fix stale closures in handleKeyDown, reset submittedRef on request.id change, sync selectedRef on mouse hover, remove unstable request.options from effect deps
- useDaemonSession.ts: store and clear timeout handle in PendingSessionLoad across all resolution paths
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(web-shell): add submittedRef guard to AskUserQuestion handleCancel
Prevents double-submission on rapid Escape+Enter and avoids sending
empty optionId when no reject option exists.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: ytahdn <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
* chore: remove stale files superseded by main refactors
Auth provider files were removed by #4287 (auth unification) and
httpAcpBridge.test.ts was moved to packages/acp-bridge in the
F1 test split. These existed in the original orphan branch baseline
but were deleted via sync-main commits.
* feat(serve): add daemon file logger (#4548) (#4559)
* docs(serve): design spec for daemon file logger (#4548)
Document the architecture, daemon-id scheme, API surface, tee
semantics, boot/shutdown flow, and test plan for adding a daemon-
specific file sink to qwen serve diagnostics. Companion to issue
#4548.
* docs(serve): implementation plan for daemon file logger (#4548)
Bite-sized task list covering: pure formatter, file init, info/warn/
error + flush, raw file-only tee, latest symlink, acp-bridge sink
injection, spawn factory refactor, runQwenServe wiring, docs, and
final verification + PR creation. Companion to the design spec.
* docs(serve): fix plan inaccuracies after second review pass (#4548)
- updateSymlink: re-export from core barrel first, then import
- bridge.test.ts harness: use makeBridge/makeChannel from testUtils
(MockStream was hallucinated)
- writeServeDebugLine: enumerate all 6 call sites, not 2
- createServeApp: correct 3-arg signature (opts, getPort, deps);
daemonLog goes in deps, not as a 1st-arg key
* feat(serve): buildDaemonLogLine formatter (#4548)
* feat(serve): daemon logger opt-out env + no-op shape (#4548)
* feat(serve): daemon logger file init + degraded fallback (#4548)
* feat(serve): daemon logger info/warn/error + flush (#4548)
* feat(serve): daemon logger raw() file-only tee (#4548)
* feat(serve): daemon logger latest symlink (#4548)
* feat(acp-bridge): onDiagnosticLine sink for serve debug tee (#4548)
* feat(acp-bridge): createSpawnChannelFactory with onDiagnosticLine (#4548)
* feat(serve): route sendBridgeError through daemonLog (#4548)
* feat(serve): init daemonLogger in runQwenServe + flush on shutdown (#4548)
* docs(serve): document daemon log file path and opt-out (#4548)
* feat(daemon): ACP Streamable HTTP transport at /acp [RFD #721] (#4472)
* fix(serve): post-merge fixes for #4291 review (7 threads) (#4305)
* fix(serve): address qwen-latest review on merged #4291 (7 threads)
Seven post-merge findings from the qwen-latest review on #4291,
all real. Most are tightening fixes for issues introduced by the
earlier rounds of #4291 — the same security / DRY / observability
classes the original review surfaced, applied to surfaces that
weren't covered initially.
#1 (deviceFlow.ts:1179) — late-poll observer closure retained the
entire entry by reference (deviceCode/pkceVerifier BrandedSecrets +
cancelController) for the lifetime of the daemon if `provider.poll()`
never settled. Memory leak + indefinite secret retention. Destructure
the four fields the closure actually needs (deviceFlowId, providerId,
initiatorClientId, audit sink) so the entry is GC-eligible the
moment runPollTick returns.
#2 (server.ts) — `callerIsInitiator` was duplicated verbatim across
three locations: GET handler, toDeviceFlowStartResponseBody,
toDeviceFlowStateBody. The exact bug class #4291 was fixing was
"POST and GET diverged on the same redaction policy" — duplicating
the gate recreated the preconditions for divergence. Extracted to
shared `callerIsDeviceFlowInitiator(view, callerClientId)` helper
with the consolidated threat-model JSDoc. All three sites now call
the helper.
#3 (deviceFlow.ts:1110) — timeout callback constructed two separate
`DeviceFlowPollTimeoutError` instances (one for `signal.reason`, one
for the wrapper rejection). Each capture its own V8 stack trace,
and `signal.reason.stack` would diverge from the caught rejection's
stack — confusing for operators inspecting both. Build the sentinel
ONCE per timer fire and pass the same instance to both sites.
#4 (qwenDeviceFlowProvider.ts:273) — `Error.name` is a freely
assignable string property; a hostile fetch wrapper could set
`e.name = 'X\n[serve] FAKE LINE\x1b[31m'` to inject log lines or
ANSI sequences via the same vector we already closed for `oauthError`.
The non-OAuth catch path interpolated `${err.name}` raw. Apply the
same `sanitizeForStderr()` helper.
#5 (deviceFlow.ts:1551) — on the timeout path, `rawProviderError`
is undefined (deliberately, to skip the misleading
`provider.poll() threw (raw): ...` audit template), but that left
the audit hint field omitted entirely. Operators reading the
durable audit trail saw `errorKind: 'upstream_error'` with no signal
whether it was a hung IdP or a generic provider failure. Use
`result.hint` (which already carries the timeout-specific
`provider.poll() timed out after Nms; check IdP connectivity` text
built in the catch) so the audit matches the SSE event.
#6 (server.ts) — the `QWEN_SERVE_DEBUG` env-var check was inlined
in the GET route handler, duplicating the `isServeDebugMode()`
helper from `./debugMode.js` that workspaceAgents and
workspaceMemory already use. The inline copy also had a dead `?? ''`
fallback (the value is guaranteed truthy at that point per the
preceding check). Use the canonical helper.
#7 (deviceFlow.ts:1217) — late-rejection observer interpolated the
raw `lateErr.message` into the audit hint (truncated to 256 bytes,
but RFC 8628 `device_code` values fit comfortably in 256 bytes).
The provider's catch already uses the `name + length` redaction
pattern to prevent WAF-echoed `device_code`/PKCE leaks; the
registry layer was undoing that hardening because the same failure
settled late. Apply the same `name + length` pattern at the late-
rejection site.
Tests:
- Existing late-rejection test reseeded with a `device-code-secret-*`
substring inside the long detail; hard-negative-asserts the seeded
secret is absent from the audit + asserts the new
`Error (message N bytes; raw suppressed)` shape.
- Existing poll-timeout test now also asserts: hint IS defined on
the audit (not omitted), hint contains `'timed out after'` /
`'check IdP connectivity'`, and `signal.reason instanceof
DeviceFlowPollTimeoutError` (proves the single sentinel is
shared between abort and reject).
- New `sanitizes control characters in attacker-controlled
err.name` test in qwenDeviceFlowProvider.test.ts pins the round-4
#4 fix with a hostile `e.name` containing `\n` + `\x1b[31m...`.
cli serve 702/702 (was 686, +16 — additional tests imported via
the acp-bridge package lift on main); sdk 421/421; typecheck clean
across all 4 workspaces; eslint --max-warnings 0 clean on touched
files.
Refs: #4175, #4255, #4291🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address deepseek-v4-pro review on #4305 (4 threads)
Round-5 fold-in. Four findings from the deepseek-v4-pro review on
PR #4305 — all real, three are sister fixes for the same security
classes that #4305 already closed at adjacent surfaces.
#1 (deviceFlow.ts) — `pollTimedOut` race correctness. The flag was
set unconditionally inside the timer callback. If the provider
settled the wrapper at 29.9s, `finally` would call
`clearScheduled(pollTimer)` — but if the timer callback was already
queued for execution before the clear landed (a real possibility
in Node's event-loop ordering, even if not always observed in
practice), this branch could still run and incorrectly mark
`pollTimedOut`. Move the flag assignment to the catch block where
the settled cause is unambiguous via `instanceof
DeviceFlowPollTimeoutError`. New test pins the negative: provider
beats the timeout → no spurious `lost_late_poll_after_timeout`
audit even after ticking 2× the ceiling.
#2 (deviceFlow.ts) — late-rejection observer interpolated raw
`lateErr.name` into the audit hint without sanitization. Same
attacker-controlled vector closed at the provider layer for
`err.name` in round-4. Route through `sanitizeForStderr`.
#3 (deviceFlow.ts) — late-success observer interpolated
`latePollResult.kind` directly into the audit template. While the
typed shape is `'pending' | 'slow_down' | 'success' | 'error'`, a
non-conforming provider could return an arbitrary string. Same
log-injection vector. Route through `sanitizeForStderr`.
#4 (qwenDeviceFlowProvider.ts → deviceFlow.ts) —
`sanitizeForStderr` only stripped ASCII C0/C1 + DEL; bypass via
Unicode lookalikes:
- U+2028/U+2029: LINE/PARAGRAPH SEPARATOR (newline-equivalent in
most Unicode-aware terminals — most direct log-forging vector)
- U+200B–U+200F: zero-width chars + LRM/RLM
- U+202A–U+202E: bidirectional override controls
- U+FEFF: BOM / ZWNBSP
A malicious IdP returning `slow_down [serve] FAKE` in
`oauthError` would otherwise still forge log lines.
Architectural change: `sanitizeForStderr` was previously private to
`qwenDeviceFlowProvider.ts`. To address #2/#3, the registry layer
needs to call it too. Lifted into `deviceFlow.ts` (the foundation
module) and re-imported from the provider. Single source of truth;
the regex is now a module-level constant compiled once with explicit
`\uXXXX` escapes (via `String.raw` so the source is greppable, not
literal-Unicode-laden).
Tests:
- `does NOT attach late-poll observer when the provider beats the
timeout` — N1 race regression
- `sanitizes hostile latePollResult.kind in late-observer audit` — N3
- `sanitizes hostile lateErr.name in late-rejection observer audit` — N2
- `sanitizes Unicode lookalike controls (U+2028 LINE SEPARATOR,
bidi, ZWNBSP) in oauthError` — N4
cli serve 706/706 (was 702, +4 — all new round-5 tests); sdk
421/421; typecheck clean; eslint --max-warnings 0 clean on touched
files.
Refs: #4175, #4255, #4291, #4305🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address gpt-5.5 + qwen-latest review on #4305 round-5 (5 threads)
Round-6 fold-in. Five findings split between maintainability,
security hardening, and a real defensive bug.
#1 (qwenDeviceFlowProvider.test.ts) — gpt-5.5: round-5 #4 test
embedded U+2028 / U+200E / U+FEFF as literal characters in source.
Invisible in GitHub diffs / most editors; the negative
`not.toContain('')` looked like an empty-string check. Rewrote
the payload + assertions to use named `\uXXXX`-bound constants.
Also added a companion test exercising U+2066–U+2069 (round-6 #5
below).
#2 (deviceFlow.ts) — qwen-latest: the late-poll observer's
`void tracked.then(...)` was missing a terminal `.catch(() => {})`.
A synchronous throw inside either handler (e.g., a misbehaving
`audit.record`: backpressure, malformed payload, sink out-of-disk)
would reject the derived promise unhandled. On Node 22's default
`--unhandled-rejections=throw`, that crashes the daemon. Added the
terminal `.catch(() => {})` matching the persist-tracker pattern.
New test injects a poison audit sink that throws specifically on
the `lost_late_poll_after_timeout` call; asserts `flushAsync()`
resolves cleanly.
#3 (deviceFlow.ts) — qwen-latest: the `case 'error'` audit-record
hint interpolated `rawProviderError` (raw `err.message`) without
`sanitizeForStderr`. Per ES2019+ `JSON.stringify` no longer escapes
U+2028/U+2029 — those would still forge log lines downstream
through file/stdout audit sinks. Apply the same sanitizer used on
every other provider-controlled audit path. New test pins a hostile
provider message containing U+2028 + ANSI escape and asserts
neither survives.
#4 (deviceFlow.ts) — qwen-latest: the round-5 #1 comment claimed
"`DeviceFlowPollTimeoutError` isn't exported as a public DeviceFlow
contract", but it IS `export class` (the test file constructs it
directly for fixtures). With `pollTimedOut = true` keyed solely on
`instanceof`, a future provider that imports + throws the class
would spoof the registry's "I caused the timeout" signal —
attaching a phantom late-poll observer.
Fix: introduce a runtime brand `_isRegistryTimeout: boolean` on the
class (default `false`) plus an internal-only
`makeRegistryPollTimeoutError(ms)` helper that sets the brand to
`true`. The brand is set ONLY at the registry's race-timer
construction site. Both gates updated:
- `if (err instanceof X && err._isRegistryTimeout === true)` in
the catch (for `pollTimedOut`)
- `if (lateErr instanceof X && lateErr._isRegistryTimeout === true)`
in the late-rejection self-filter
A provider-thrown brand-false instance now flows through the
generic provider-throw audit path — correctly auditing the misuse
rather than silently swallowing it. Repurposed the original "no
double-audit when registry's own DeviceFlowPollTimeoutError is
late-rejected" test (which was actually exercising the brand-false
path) into the inverted assertion: brand-false provider throw IS
audited as a real failure. Removed the orphaned old assertion; the
brand-true happy path is implicitly covered by the hanging-provider
test (which exercises the registry-built timeout end-to-end).
#5 (deviceFlow.ts) — qwen-latest: `sanitizeForStderr` regex covered
U+202A–U+202E (bidi embedding/override) but missed U+2066–U+2069
(LRI/RLI/FSI/PDI). These are the primary CVE-2021-42574
("Trojan Source") attack vectors — a hostile IdP swapping U+2066
for U+202D achieves the same visual reordering and would have
bypassed the round-5 filter entirely. Extended the regex range and
JSDoc; new test exercises U+2066/U+2068/U+2069 in `oauthError` and
asserts none survive while substantive ASCII parts remain.
cli serve 713/713 (was 710, +3 round-6 tests + the round-5 #4
rewrite + the round-6 #5 companion); typecheck clean across all 4
workspaces; eslint --max-warnings 0 clean on touched files.
Refs: #4175, #4255, #4291, #4305🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): replace literal U+2028 with explicit escape in round-6 #3 test
PR #4312 review (Copilot): the round-6 #3 test (sanitizes
rawProviderError) regressed back to embedding a literal U+2028
character in source via `const U_2028 = ' '`. That's the same
maintainability anti-pattern round-6 #1 was fixing in the sister
test. Internal-consistency fix: switch to the explicit ` `
escape so the constant is greppable and reviewable in GitHub diffs.
Refs: #4291, #4305, #4312🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): post-merge P2 corrections from Codex review on #4282 (#4297)
* fix(serve): post-merge P2 corrections from Codex review on #4282
Follow-up to PR #4282 (Wave 4 PR 17) addressing four P2 issues
flagged by Codex's `/review` after the squash-merge to main:
P2-1 — Read the workspace context filename for init
`qwen serve` parent never goes through `loadCliConfig`, so the
process-global `getCurrentGeminiMdFilename()` stays on the default
`QWEN.md` even when the workspace configures
`context.fileName: 'AGENTS.md'`. `runQwenServe` now snapshots the
workspace's merged setting at boot and forwards via
`BridgeOptions.contextFilename`, so init writes the same file the
ACP child reads.
P2-2 — Restart MCP servers with a fresh disabledTools snapshot
`Config.disabledTools` was frozen at construction time;
`setWorkspaceToolEnabled` only updated settings.json. The
documented "toggle + restart" workflow re-registered just-disabled
tools because rediscovery still saw the bootstrap snapshot. Added
`Config.setDisabledTools()` plus a re-read at the ACP restart
handler so `discoverMcpToolsForServer` honors the latest set.
P2-3 — Match the SDK timeout to the daemon's restart budget
Bridge waits up to 300s for stdio MCP discovery; SDK helper used
the client-wide 30s default and aborted valid slow restarts.
Added a per-call `timeoutMs` plumbed through `fetchWithTimeout`,
defaulting `restartMcpServer` to 5 minutes.
P2-4 — Reject symlinked parent directories before init writes
`lstat(target)` only checked the final component; a symlinked
parent (e.g. `docs -> /tmp` with `context.fileName:
'docs/QWEN.md'`) would let `writeFile` follow the link and create
/ truncate outside `boundWorkspace`. Added
`canonicalizeExistingAncestor` (walks up through ENOENT to the
deepest extant ancestor, then `realpath`s) and verifies the
canonical parent stays within the canonical workspace.
5 new tests (4 bridge / 2 SDK):
- contextFilename snapshot honored
- parent-symlink escape rejected
- nested real subdir accepted
- restartMcpServer survives 1.2s response with 1s default timeout
- restartMcpServer honors a 50ms caller override
Typecheck clean across cli / sdk-typescript / core.
1604/1604 unit tests pass.
* fix(serve): fold-in 1 — address 16:32:44-round review on #4282
Follow-up addressing the 8 unresolved review threads opened on PR
shipping in this same #4297; addresses correctness gaps + missing
test coverage that would otherwise let regressions ride into main.
Behavior fix:
- broadcastWorkspaceEvent gains a `skipSessionId` parameter; when
`setSessionApprovalMode` runs with `persist:true`, the broadcast
skips the requesting session so it doesn't receive the same
`approval_mode_changed` event twice (once via session-scoped
publish + once via broadcast). The SDK reducer's
`approvalModeChangedCount` now increments by 1, not 2, on the
requesting client (peers still see 1 via the broadcast).
Addresses #3260501134.
Observability + posture:
- broadcastWorkspaceEvent now mirrors PR 16's publishWorkspaceEvent
member: per-entry success/failure accounting + an "ALL buses
dropped" stderr elevation. The previous local helper silently
swallowed every publish failure. Addresses #3260501126.
- WorkspaceInitPathEscapeError + WorkspaceInitSymlinkError typed
classes for the two boundary guards in initWorkspace, mapped to
HTTP 400 by sendBridgeError. Previous generic `Error` fell
through to the 500 handler, telling operators "daemon broken"
when the actual fix was workspace-config correction. Addresses
#3260501161.
Public surface symmetry:
- Re-export McpServerNotFoundError, McpServerRestartFailedError,
WorkspaceInitPathEscapeError, WorkspaceInitSymlinkError from the
serve barrel. External embeds matching these via `instanceof`
no longer need deep imports. Addresses #3260501163.
Test coverage:
- restartMcpServer bridge tests (5): success + event broadcast,
soft-skip + refused event, McpServerNotFoundError translation,
McpServerRestartFailedError translation, originator clientId
stamping. Addresses #3260501141.
- sendBridgeError mapping tests (4): McpServerNotFoundError → 404,
McpServerRestartFailedError → 502, WorkspaceInitPathEscapeError
→ 400, WorkspaceInitSymlinkError → 400. Addresses #3260501148.
- initWorkspace boundary guard tests (2 added): symlink-at-target
rejected, contextFilename '../outside.md' rejected. Addresses
#3260501157.
- TrustGateError tests assert the typed class via `.toThrow(TrustGateError)`,
not just message text. Addresses #3260501165.
Also updates the existing fold-in 4 S2 broadcast test to reflect
the new no-duplicate semantics on the requesting session.
Typecheck clean across cli / sdk-typescript / core.
1615/1615 unit tests pass.
* fix(serve): fold-in 2 — copilot + wenshao review on #4297
Round-2 reviewer adoption on the same PR:
Critical fixes:
- `restartMcpServer` JSDoc documents `timeoutMs: 0` as "disable the
timeout entirely", but the `> 0` guard in `fetchWithTimeout`
rejected `0` and silently fell back to the 30s client default.
Loosened the guard to `>= 0` so `0` flows through to the
no-timeout branch via the existing truthiness check; NaN /
negative inputs still coerce to the client default. Addresses
duplicate reports from copilot (#3260577538) and wenshao
(#3260661833).
- TS2322 in the slow-fetch test stub: `resolveResponse` was typed
against `import('undici-types').Response` but assigned a
`(v: Response) => void`. Re-typed against the global `Response`
throughout. Caught only by tsc runs that include the test
files. Addresses #3260663072.
Test fidelity:
- Slow-fetch stub now observes `init.signal` and rejects on abort,
so a regression that drops the per-call `timeoutMs` override
will reliably fail the test instead of resolving after the
timer fired (false-negative coverage). Addresses #3260577600.
- New test pinning the `timeoutMs: 0` semantics: 1ms client
default + a stub that resolves after 50ms. Without the `>= 0`
fix, the call would abort at 1ms; with it, the explicit
`0` disables the timer and the call completes.
Bug fixes:
- `runQwenServe.contextFilenameForInit` previously called
`String(arr[0])` on the array branch, producing a literal
`"[object Object]"` filename for hand-edited bad data. Now
validates each element with `typeof === 'string'` and falls
back to `undefined` (so the bridge uses its
`getCurrentGeminiMdFilename()` default) when no string is
found. Addresses #3260577641.
Documentation drift:
- `Config.getDisabledTools()` JSDoc rewritten to describe the
mutable-via-`setDisabledTools()` semantics introduced by P2-2,
and the "registration-time only / no retroactive unregister"
contract that pairs with it. Old comment claimed the set was
frozen at construction. Addresses #3260577677.
Observability:
- `acpAgent` MCP-restart `loadSettings` failure now surfaces a
stderr line naming the server + the underlying error, instead
of silently swallowing it. The documented "toggle + restart"
workflow used to break with zero diagnostic when settings.json
was corrupted or unreadable. Addresses #3260663303.
Code organization:
- Moved `canonicalizeExistingAncestor` after `describeStatKind` so
the latter's JSDoc is no longer orphaned (TypeScript only
associates the last `/** ... */` block before a declaration).
Addresses #3260668618.
Typecheck clean across cli / sdk-typescript / core.
1616/1616 unit tests pass.
* fix(serve): fold-in 3 — read merged scope on MCP restart refresh
Critical bug from wenshao review (#3260725526) on PR #4297:
the P2-2 acpAgent re-read narrowed `Config.disabledTools` to
`SettingScope.Workspace` alone, dropping User / System scope
entries. The bootstrap Config received `merged.tools?.disabled`
(union of all scopes), so user-level / system-level disables
worked at boot — but the first `mcp restart` would replace the
in-memory set with the workspace scope alone, silently re-enabling
any tool that was disabled at a higher scope but absent from the
workspace file.
The asymmetry vs. the persist-write path is deliberate and
documented:
- Reads (here): merged — match the bootstrap Config snapshot,
preserve user/system policy.
- Writes (`runQwenServe.persistDisabledTools`): workspace scope —
don't bake higher-scope entries into the workspace file
(per-#4282 fold-in 1 H2 fix).
Two paths look alike but answer different questions.
Typecheck clean across cli / sdk-typescript / core.
1616/1616 unit tests pass.
* fix(test): fold-in 4 — wire timeoutMs:0 stub to init.signal
Critical follow-up from wenshao (#3260810242) on PR #4297:
the new `timeoutMs: 0` regression test (added in fold-in 2)
inherited the same flaw it was meant to prevent — the slow-fetch
stub didn't observe `init.signal`, so a regression that ignored
the `0` override would fire the AbortController at the 1ms client
default but the stub would keep the promise pending. The 50ms
`resolveResponse` would win, the test would still pass, and the
documented "0 disables timeout" contract would be unprotected.
Mirrored the listener pattern already used by the two sibling
tests in fold-in 2 — `init.signal.addEventListener('abort', () =>
reject(...))`. Now a regression that re-rejects `0` triggers the
abort, the stub rejects, the test fails.
8/8 restartMcpServer SDK tests pass; SDK typecheck clean.
* fix(serve): fold-in 5 — TOCTOU + setDisabledTools coverage
Two new critical reviews from wenshao on PR #4297:
C1 — TOCTOU between lstat and writeFile (#3260836305):
The `lstat(target)` symlink check and the subsequent `writeFile`
were two separate syscalls, leaving a race window where a local
attacker with workspace write access could substitute a symlink
between them. With `force: true`, `writeFile` would follow the
link and truncate an external target.
The `action === 'created'` path now uses `fs.open(target, 'wx')`
(O_WRONLY|O_CREAT|O_EXCL), which atomically refuses any
pre-existing inode (regular file, dir, OR symlink) at the target
path. EEXIST after the absence check most plausibly means a
race-created symlink, so we throw `WorkspaceInitSymlinkError(kind:
'target')` — same typed class the route maps to 400.
The `force: true` overwrite path retains the existing TOCTOU as a
documented limitation; closing it requires `O_NOFOLLOW`-aware open
which the post-PR18 `WorkspaceFileSystem` migration will provide.
C2 — P2-2 zero test coverage (#3260836302):
The `setDisabledTools` runtime sync was the only Wave-4 P2 fix
without a dedicated test. Added 5 Config-level tests:
- Initializes from `disabledTools` ConfigParameters
- Defaults to empty set when omitted
- `setDisabledTools` replaces the live snapshot
- Defensive copy: caller-set mutations don't leak into the live snapshot
- Accepts an empty set (clears live snapshot)
Plus a TOCTOU regression test in httpAcpBridge.test.ts that
spies fs.lstat / fs.readFile to simulate the race window:
pre-creates a symlink, makes lstat lie about it, asserts the
'wx' open catches the racing inode and throws the typed
`WorkspaceInitSymlinkError(kind: 'target')`.
1622/1622 unit tests pass; typecheck clean across cli /
sdk-typescript / core.
* fix(serve): fold-in 6 — count actual skips in broadcast alarm
DeepSeek review on #4297 (#3261079572):
`broadcastWorkspaceEvent` unconditionally subtracted 1 from the
`eligible` recipient count whenever `skipSessionId` was set, even
when the id matched zero live sessions (caller mistake, stale id,
or the matching session was just torn down between resolution and
broadcast). In a single-session workspace that's the difference
between `eligible = 0` (alarm suppressed) and `eligible = 1`
(alarm fires when the publish failed) — silently losing the
all-dropped breadcrumb the telemetry was meant to surface.
Today's call sites pass real session ids so the bug doesn't
manifest in practice, but the defensive shape is small: track
`skippedCount` inside the loop and subtract that, so the alarm
condition is self-consistent regardless of how the caller mis-uses
the param.
162/162 bridge tests pass; CLI typecheck clean.
* fix(serve): fold-in 7 — close overwrite TOCTOU, harden boot + diagnostics
Round-7 review on PR #4297. Three critical fixes + one suggestion
test, plus a regression test for the overwrite TOCTOU close.
C1 — force:true overwrite TOCTOU (#3262615446):
The fold-in 5 fix only closed the `'created'` action via 'wx';
the `'overwrote'` branch still used plain `fs.writeFile`, so a
local writer could swap the verified regular file to a symlink
between the lstat/readFile checks and the write and have the
forced overwrite truncate an external target. Switched to
`fs.open(target, O_WRONLY | O_TRUNC | O_NOFOLLOW)` — `O_NOFOLLOW`
makes open() fail with ELOOP on a symlink at the final component
even under race. ELOOP / ENOENT (race-deleted) translate to
`WorkspaceInitSymlinkError(kind: 'target')` so the route still
maps to a structured 400 instead of a generic 500.
C2 — settings.json corrupt blocks daemon boot (#3262625091):
`loadSettings(boundWorkspace)` at boot had no try/catch — a
corrupted, malformed, or temporarily unreadable settings file
threw synchronously and prevented daemon startup. Pre-PR this
never happened because settings were read lazily inside request
handlers. Wrapped in try/catch with stderr fallback so the daemon
keeps booting (with the bridge's default context filename) when
the file is broken.
C3 — malformed `tools.disabled` clears policy silently (#3262625101):
When `merged.tools?.disabled` is present but not an array
(boolean / string / object from a hand-edited settings.json), the
ternary `Array.isArray(...) ? ... : []` substituted an empty list
without firing the surrounding catch block. After an MCP restart
every disabled tool would silently re-register. Added an explicit
`!Array.isArray && !== undefined` check that stderr-logs the
malformed type before clearing — operators see the
misconfiguration instead of a stealth re-enable.
S1 — contextFilename extraction tested (#3262690842):
Lifted the inline `firstStringInArray` + branching into an
exported `extractContextFilename(value: unknown)` helper and
added `runQwenServe.test.ts` with 5 tests covering the four
branches the suggestion called out: non-empty string, array with
strings, array with no strings, non-string non-array.
Plus a TOCTOU regression test for the overwrite path that
verifies `O_NOFOLLOW` returns `WorkspaceInitSymlinkError(kind:
'target')` when the file is race-substituted with a symlink
behind the lstat/readFile mocks.
S2 (acpAgent restart-handler integration test #3262690845) is
deferred — Config-level coverage of `setDisabledTools` already
locks the load-bearing surface (5 tests in fold-in 5), and
adding a full acpAgent integration test requires heavy ext-method
plumbing. The new C3 stderr diagnostic plus existing tests give
us the regression signal we need without that scaffolding.
1627/1627 unit tests pass; typecheck clean across cli /
sdk-typescript / core / acp-bridge.
* fix(serve): fold-in 8 — split ELOOP / ENOENT diagnostic in overwrite path
qwen-latest review on PR #4297 (#3262861754):
The fold-in 7 ELOOP/ENOENT branch shared one error message that
said "swapped to a symlink." That's accurate for ELOOP (genuine
O_NOFOLLOW rejection — likely an attack race) but misleading for
ENOENT in the overwrite path: there `readFile` just succeeded
proving the file existed, so ENOENT means the file was DELETED
between the content check and the open — a benign race with a
concurrent writer (git checkout, editor save, lockfile rename),
NOT a symlink swap. An operator seeing the symlink language for
a benign delete would `ls -la`, see no symlink, and waste time
hunting an attack that didn't happen.
Split into two messages:
- ELOOP: "swapped to a symlink between the content check and the
overwrite — refusing to follow it"
- ENOENT: "deleted between the content check and the overwrite
(likely a concurrent writer) — refusing to recreate blindly"
Both still surface as `WorkspaceInitSymlinkError(kind: 'target')`
so the route maps to a structured 400; the class doubles as the
workspace-init race-condition bucket with kind='target' meaning
"target inode misbehaved at write time" generally.
Updated the existing fold-in 7 TOCTOU test to assert the ELOOP
message specifically, and added a new ENOENT race-delete test
that mocks lstat/readFile to land on the overwrote action against
a non-existent path — verifies the message says "deleted" and
NOT "swapped to a symlink."
170/170 bridge tests pass; CLI typecheck clean.
* fix(serve): fold-in 9 — route MCP restart through registry cleanup wrapper
gpt-5.5 critical review on PR #4297 (#3263088414):
The fold-in 5 P2-2 fix refreshed `Config.disabledTools` from merged
settings, but then called `manager.discoverMcpToolsForServer()`
directly — bypassing the `ToolRegistry.discoverToolsForServer`
wrapper that PURGES the server's existing `DiscoveredMCPTool`
entries (and `revealedDeferred` markers) plus its prompts before
rediscovery. Without the cleanup, `registerTool` only consulted
the refreshed `disabledTools` set for NEWLY-discovered tools —
entries already in the registry from the prior MCP boot kept
serving requests. Net effect: toggle-disable-then-restart
silently left the disabled tool live, breaking the documented
"toggle + restart" workflow that P2-2 was meant to fix.
Routed through `toolRegistry.discoverToolsForServer(serverName)`
which:
1. Removes existing `DiscoveredMCPTool` entries for this server
2. Drops their `revealedDeferred` reveal state
3. Removes the server's prompts via `removePromptsByServer`
4. THEN delegates to `manager.discoverMcpToolsForServer` for the
actual reconnect + rediscover
The pre-discovery budget / in-flight checks still go through the
`manager` reference (which is the same object the registry
wrapper would forward to) — so soft-skip semantics for
`budget_would_exceed`, `in_flight`, `disabled` are preserved.
CLI typecheck clean; 403/403 server + bridge tests pass.
* fix(serve): fold-in 10 — qwen-latest 05:45-round review on #4297
5 review threads from qwen-latest's late round on PR #4297 (now closed
in favor of #4313 against `daemon_mode_b_main`). 1 critical + 4
suggestions, all adopted.
C1 — extractContextFilename / getCurrentGeminiMdFilename divergence
(#3263954685): with `context.fileName: [' ', 'AGENTS.md']`, the
daemon parent's `extractContextFilename` (which skips empty entries)
wrote `AGENTS.md`, but the ACP child's `getCurrentGeminiMdFilename`
(which returned `arr[0]` unconditionally) read `''`. The init'd file
was orphaned. Aligned `getCurrentGeminiMdFilename` to skip empty
entries with the same semantics, falling back to
`DEFAULT_CONTEXT_FILENAME` when all entries are empty.
S2 — WorkspaceInitSymlinkError reused for non-symlink races
(#3263954690): the EEXIST race-create and ENOENT race-delete cases
were surfacing as `code: 'workspace_init_symlink'`, misleading
operators into hunting symlink attacks for benign concurrent-
modification windows. Split into a sibling `WorkspaceInitRaceError`
class (`kind: 'eexist' | 'enoent'`, HTTP code
`workspace_init_race`). The genuine symlink class stays for ELOOP,
lstat-detected target symlinks, and parent-realpath escapes.
S3 — fsConstants.O_NOFOLLOW defensive `?? 0` (#3263954697): matches
the existing codebase convention in
`core/src/utils/{sessionStorageUtils,gitDiff}.ts` and
`cli/src/ui/utils/customBanner.ts`. Functionally a no-op (JS
bitwise coerces undefined to 0) but consistent.
S5 — Parent-directory TOCTOU still open (#3263954707): O_NOFOLLOW
only protects the final path component; a local writer could swap
a real parent dir for a symlink between
`canonicalizeExistingAncestor` and `fs.open`. Added
`verifyParentWithinWorkspace` post-open helper that re-realpaths
`path.dirname(target)` and refuses with
`WorkspaceInitSymlinkError(kind: 'parent')` if the parent moved.
On the create path (where we just opened with `'wx'`), the failure
also unlinks the file we just made best-effort. Residual race
window narrowed from "between pre-check and open" to "between
post-open realpath and writeFile" — sub-millisecond, documented as
accepted Stage-1 trust posture.
S4 — broadcastWorkspaceEvent vs publishWorkspaceEvent stale comment
(#3263954688): the "now removed" comment was inaccurate (5 call
sites still use the closure). Replaced with an accurate
description of why both coexist (factory closure can't `this`-call
proxy member; closure also takes `skipSessionId` for persisted
approval-mode mirror) and a TODO marker for future helper extraction.
Two existing tests updated to assert the new `WorkspaceInitRaceError`
class for EEXIST / ENOENT scenarios (the symlink-class assertions
are preserved for ELOOP / lstat / parent cases).
1759/1759 unit tests pass; typecheck clean across all 4 packages.
* feat(acp-bridge): F1 — acp-bridge package self-sufficiency (#4175 mechanical lift + BridgeFileSystem seam) (#4319)
* refactor(acp-bridge): lift defaultSpawnChannelFactory to acp-bridge/spawnChannel (#4175 F1 step 1)
First mechanical lift of #4175 F1 (acp-bridge package self-sufficiency).
Moves the production spawn factory + its `killChild` helper +
`SCRUBBED_CHILD_ENV_KEYS` denylist + `KILL_HARD_DEADLINE_MS` constant
from `cli/src/serve/httpAcpBridge.ts` (~283 lines) to
`@qwen-code/acp-bridge/spawnChannel`. This unblocks
`channels/base/AcpBridge.ts` and `vscode-ide-companion`'s
acpConnection from each reimplementing the child lifecycle — they can
now consume the same primitive.
Backward compatible: `cli/src/serve/httpAcpBridge.ts` imports the
lifted factory and re-exports it, so existing references in
`cli/src/serve/index.ts:90` and the factory's own internal usage
(`opts.channelFactory ?? defaultSpawnChannelFactory`) keep resolving.
Bridge tests that mock `defaultSpawnChannelFactory` via
`BridgeOptions.channelFactory` are unaffected.
Side cleanups: drops `spawn` / `ChildProcess` / `Readable` / `Writable`
/ `ndJsonStream` / `MissingCliEntryError` imports from
httpAcpBridge.ts (all only used by the lifted spawn factory).
- 44/44 acp-bridge tests pass
- 174/174 cli httpAcpBridge tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor(acp-bridge): lift BridgeClient + permission types to acp-bridge/bridgeClient (#4175 F1 step 2)
Second mechanical lift of #4175 F1 (acp-bridge package self-sufficiency).
Moves `BridgeClient` class (~700 LOC) + `PendingPermission` interface +
`PermissionResolutionRecord` interface + `MAX_RESOLVED_PERMISSION_RECORDS`
constant + early-event capacity constants + `describeStatKind` and
`sliceLineRange` helpers from `cli/src/serve/httpAcpBridge.ts` to
`@qwen-code/acp-bridge/bridgeClient`.
Design choice for SessionEntry boundary: introduce a minimal
`BridgeClientSessionEntry` interface in bridgeClient.ts with only the
four fields BridgeClient actually reads from the factory's richer
`SessionEntry` (`sessionId`, `events`, `pendingPermissionIds`,
`activePromptOriginatorClientId`). The factory's `SessionEntry`
structurally satisfies it — TypeScript's structural typing enforces
the match at the `resolveEntry` callback signature, so no explicit
conversion is required and the bridge package stays free of daemon-host
session-bookkeeping types.
Cross-package writeStderrLine handling: inline the 3-line helper in
bridgeClient.ts (mirrors the spawnChannel.ts pattern from F1 step 1)
so acp-bridge has no reverse dependency on `cli/src/utils/stdioHelpers`.
httpAcpBridge.ts shrinks from 4406 LOC to 3647 LOC (-759 lines).
Removed ACP SDK imports that only BridgeClient consumed: `Client`,
`RequestPermissionRequest`, `WriteTextFileRequest`,
`WriteTextFileResponse`, `ReadTextFileRequest`, `ReadTextFileResponse`,
`SessionNotification`. Kept the ones the factory still uses
(`CancelNotification`, `PromptRequest`, `RequestPermissionResponse`,
`SetSessionModelRequest`, `SetSessionModelResponse`).
Backward compatible: httpAcpBridge.ts re-exports `BridgeClient`,
`BridgeClientSessionEntry`, `PendingPermission`,
`PermissionResolutionRecord`, and `MAX_RESOLVED_PERMISSION_RECORDS` so
the `ChannelInfo.client: BridgeClient` field declaration below + any
embedder reaching into these types keep resolving.
- 44/44 acp-bridge tests pass
- 174/174 cli httpAcpBridge tests pass
- 229/229 cli server tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor(acp-bridge): lift createHttpAcpBridge factory to acp-bridge/bridge (#4175 F1 step 3)
Third + final mechanical lift of #4175 F1 (acp-bridge package
self-sufficiency). Moves the `createHttpAcpBridge` factory closure
(~3000 LOC) + `ChannelInfo` + `SessionEntry` interfaces + factory-only
helpers (`canonicalizeExistingAncestor`, `verifyParentWithinWorkspace`,
`withTimeout`, `isServeDebugLoggingEnabled`, `writeServeDebugLine`,
`hasControlCharacter`) + factory constants (`DEFAULT_INIT_TIMEOUT_MS`,
`MCP_RESTART_TIMEOUT_MS`, `DEFAULT_MAX_SESSIONS`, `MAX_EVENT_RING_SIZE`,
`DEFAULT_PERMISSION_TIMEOUT_MS`, `DEFAULT_MAX_PENDING_PER_SESSION`,
`MAX_DISPLAY_NAME_LENGTH`) from `cli/src/serve/httpAcpBridge.ts` to
`@qwen-code/acp-bridge/bridge`.
`cli/src/serve/httpAcpBridge.ts` shrinks from 3647 LOC to 97 LOC — a
pure re-export shim that preserves every existing relative import
path (`./httpAcpBridge.js`) so `server.ts`, `runQwenServe.ts`,
`workspaceAgents.ts`, `workspaceMemory.ts`, `index.ts`, plus the bridge
test suite, keep resolving without any call-site changes.
The new `bridge.ts` reuses what was already in acp-bridge (errors,
types, options, status helpers, channel types, event bus, workspace
paths) via local relative imports — no reverse dependency on `cli`.
`writeStderrLine` is inlined at the top of `bridge.ts` (same pattern as
`spawnChannel.ts` + `bridgeClient.ts` from F1 steps 1-2) so the
package self-contained promise holds.
Cumulative F1 impact across the 3 mechanical lift steps:
- httpAcpBridge.ts: 4682 LOC → 97 LOC (-4585 lines; the original file
was 98% bridge core, 2% backward-compat re-exports)
- 3 new files in acp-bridge: spawnChannel.ts (~270 LOC), bridgeClient.ts
(~745 LOC), bridge.ts (~3515 LOC)
- All daemon-host concerns (env snapshot, daemon preflight cells)
remain in `cli/src/serve/daemonStatusProvider.ts` and reach the
bridge through the `BridgeOptions.statusProvider` seam frozen by
PR 22b/2.
- 735/735 cli serve tests pass across 17 files
- 174/174 cli httpAcpBridge tests pass
- 44/44 acp-bridge tests pass
- typecheck clean across acp-bridge + cli
`packages/cli/src/serve/httpAcpBridge.test.ts` (~6600 LOC) is
intentionally NOT moved in this commit — it currently imports
`createHttpAcpBridge` / `defaultSpawnChannelFactory` / `BridgeClient`
via the cli shim and keeps passing without changes. Moving it to
`acp-bridge/src/bridge.test.ts` is a follow-up worth tracking
separately so the production-code lift can land + be reviewed cleanly.
The `BridgeFileSystem` injection seam (originally bundled into F1 as
the 22b' scope) is also deferred to a follow-up so the mechanical lift
stays mechanical — design + implementation of the fs injection is its
own discussion.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(acp-bridge): add BridgeFileSystem injection seam (#4175 F1 step 5, 22b' scope)
Adds the `BridgeFileSystem` injection seam originally scoped as #4175
22b'. When a `BridgeFileSystem` is wired through
`BridgeOptions.fileSystem`, `BridgeClient.readTextFile` and
`BridgeClient.writeTextFile` delegate to it instead of running their
inline `fs.realpath` / `fs.writeFile` / `fs.readFile` proxy.
This unblocks production `qwen serve` plumbing PR 18's
`WorkspaceFileSystem` (TOCTOU guards, symlink-substitution checks,
trust gate, `.gitignore`, audit hooks) into the ACP fs methods —
closing the `ws.ts:613` follow-up thread that has been tracked since
PR 18 landed. The serve-side adapter that wraps `WorkspaceFileSystem`
+ the `runQwenServe` wiring are intentionally split into the
immediate-follow-up so this PR stays focused on the seam design.
Backward compatible: `fileSystem` is optional on `BridgeOptions`.
Tests, Mode A in-process consumers, channels (`packages/channels/base/
AcpBridge.ts`), and the VSCode IDE companion all keep working
unchanged — they omit the field and `BridgeClient` falls through to
the inline proxy that has been the Stage 1 default since #3889.
API:
- `BridgeFileSystem.readText(params: ReadTextFileRequest):
Promise<ReadTextFileResponse>`
- `BridgeFileSystem.writeText(params: WriteTextFileRequest):
Promise<WriteTextFileResponse>`
The interface mirrors ACP SDK request/response types directly so the
adapter does the minimum amount of translation (`{ path, content }`
↔ `WorkspaceFileSystem`'s `ResolvedPath` brand types + options bag).
- 735/735 cli serve tests pass (inline fallback path preserved)
- 44/44 acp-bridge tests pass
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): catch README + stale source comments up to F1 lift
Self-review fold-in: post-F1 the package README still said "PR 22a"
and listed `BridgeClient` / `createHttpAcpBridge` /
`defaultSpawnChannelFactory` under "What's not here yet" — both
contradicted by this PR. Updated:
- README lift-history table now shows PR 22a / 22b/1 / 22b/2 as
merged and F1 (this PR) as the slice that closes the bridge core
+ adds `BridgeFileSystem`. F3 PR 24 row aligned to the
feature-cohesive plan.
- "What's here today" now documents `spawnChannel`, `bridgeClient`,
`bridge`, `bridgeFileSystem` modules.
- "What's not here yet" section removed (its 2 bullets are both
resolved by F1).
- Subpath import list updated to enumerate all 14 subpaths.
- Backward-compat section updated to call out the 97-line shim and
the 6 consuming files that still import via `./httpAcpBridge.js`.
Source-comment line-number drift:
- `channel.ts:12` no longer claims `defaultSpawnChannelFactory` is
"still in cli/src/serve/httpAcpBridge.ts" — points to the lifted
location.
- `permission.ts:33` + `permission.ts:45` no longer reference
`httpAcpBridge.ts:1096-1106` / `httpAcpBridge.ts:1003` (file is
now 97 lines after F1). Updated to point at the structurally-
equivalent locations inside the lifted `bridgeClient.ts`.
- `permission.ts:7` no longer says first-responder still lives in
`cli/src/serve/httpAcpBridge.ts` — points at the bridgeClient.ts
location.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): adopt 3 Copilot review comments on F1 doc accuracy
Folds in 3 of 4 Copilot inline comments from #4319 review:
1. `bridgeClient.ts` writeTextFile preserveMode comment said "fall
through to umask defaults" for new files, but the code passes
`mode: preserveMode?.mode ?? 0o600` to `fs.writeFile`. Updated the
"BkwQW" comment + the inner catch-block comment to clarify that
new files actually get the `0o600` default applied at writeFile
time (NOT umask defaults — the explicit `mode` arg bypasses umask
for atomicity per the `Blehd` comment block).
2. `bridgeFileSystem.ts` JSDoc referenced
`cli/src/serve/bridgeFileSystemAdapter.ts` as if the file exists,
but it's deferred to the immediate F1 follow-up PR. Reworded as
"the immediate follow-up PR will land a serve-side adapter" so
reviewers don't grep for a non-existent file.
3. `bridgeOptions.ts` `fileSystem` field JSDoc had the same wording
issue ("Production `qwen serve` wires this to..."). Same fix — now
says "The immediate F1 follow-up will land a serve-side adapter"
so the deferred state is obvious.
Declined from this review round:
- Copilot inline #1 (`spawnChannel.ts:155` stderr forwarder drops
empty lines): pre-existing behavior since #3889. F1 lifted verbatim
— not a regression introduced here. Out of scope for a lift PR.
- github-actions bot summary: most items are pre-existing notes
(TOCTOU residual race, SCRUBBED_CHILD_ENV_KEYS allowlist concern,
sliceLineRange benchmark threshold) on code the F1 lift moved
verbatim. One ("httpAcpBridge.ts still has ~3700 LOC") is a false
positive — the file is 97 LOC after F1. Others are cosmetic
refactors (extract FIXME to tracking issue, ARCHITECTURE_DECISIONS
doc system, deprecation timeline) that aren't worth churning the
lift PR over.
- 44/44 acp-bridge tests pass
- typecheck clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): tighten BridgeFileSystem contract + re-export type from shim
Self-review + code-reviewer agent fold-in, two changes:
1. `cli/src/serve/httpAcpBridge.ts` shim now re-exports
`BridgeFileSystem` from `@qwen-code/acp-bridge/bridgeFileSystem`
so the immediate F1 follow-up adapter (in `cli/src/serve/`)
can import it via the established `./httpAcpBridge.js` path
like every other daemon-side bridge import does. Without this
the adapter would need to deep-import from acp-bridge while
every other serve file goes through the shim — inconsistent.
2. `BridgeFileSystem.readText` + `writeText` JSDoc now spells out
the two defensive gates the inline proxy carried (non-regular-
file rejection + 100 MiB buffered-size cap for reads;
write-then-rename atomicity + dangling-symlink walk-through +
mode preservation + `0o600` new-file default for writes). When
a `BridgeFileSystem` is injected, the inline path is FULLY
bypassed — without the contract spelled out, a future adapter
author could silently drop the `/dev/zero` / 500 MB log RSS
defenses the inline path established.
Note on F1 CI: this PR targets `daemon_mode_b_main` but the
`.github/workflows/ci.yml` `pull_request` trigger is scoped to
`branches: main / release/**`, so the main CI workflow (Lint /
Test on Linux/macOS/Windows / CodeQL) does NOT run on this PR.
This is a by-design side effect of the new feature-cohesive
branching strategy — `daemon_mode_b_main → main` periodic merges
will trigger the full CI matrix, providing safety net coverage
before any F-series work lands on `main`. Locally verified:
- 174/174 cli httpAcpBridge tests pass
- 44/44 acp-bridge tests pass
- 735/735 cli serve tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(acp-bridge): cover BridgeFileSystem injection seam + extract shared writeStderrLine (#4319 wenshao review)
Folds in wenshao review on #4319:
1. **[Critical]** zero test coverage for the F1 step 5 `BridgeFileSystem`
delegation branches in `BridgeClient.writeTextFile` /
`BridgeClient.readTextFile` and the factory's
`opts.fileSystem` → constructor positional-arg forwarding.
New `packages/acp-bridge/src/bridgeClient.test.ts` adds 6 tests
covering:
- writeTextFile delegates to injected fileSystem.writeText (inline
proxy fully bypassed; `fakeFs.writeText` called with the original
params; `readText` mock not invoked)
- writeTextFile invalid-path call succeeds purely via the mock
when fileSystem is injected (proof that the inline `fs.realpath`
path doesn't run)
- readTextFile delegates to injected fileSystem.readText
- readTextFile propagates injection errors to the caller
- inline-fallback regression guard: write actually hits disk via
the inline proxy when fileSystem is omitted (real tmp file
round-trip)
- same for read
Why these matter: the 7-arg `BridgeClient` constructor places
`fileSystem` at the tail as optional. A reordering — or dropping
the arg from `bridge.ts` factory's `new BridgeClient(..., opts.fileSystem)`
call — would silently bypass the adapter in production and the
inline `fs.writeFile` raw-path would run with no audit / trust /
TOCTOU coverage. The delegation tests would catch that because
the mock fileSystem would never be invoked.
2. **[Suggestion]** `writeStderrLine` was defined identically in
`bridge.ts:117` and `bridgeClient.ts:30` (22 call sites across the
two files). Both consumers live in the SAME `@qwen-code/acp-bridge`
package, so the original "no reverse-dep on cli" justification
doesn't apply within the package. Extracted to
`packages/acp-bridge/src/internal/stderrLine.ts` — a single source
of truth that future behavior changes (timestamp prefix, log
level, structured field) can edit once. `internal/` subpath is
intentionally not in `package.json`'s `exports`, keeping the
helper package-private. `spawnChannel.ts` deliberately does NOT
consume it (its stderr writes use `process.stderr.write(prefix +
line + '\n')` directly because each line carries its own
`[serve pid=… cwd=…]` line prefix).
- 6/6 new BridgeFileSystem-seam tests pass
- 50/50 acp-bridge total (44 existing + 6 new)
- 174/174 cli httpAcpBridge tests pass (no regression from refactor)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(acp-bridge): cover defaultSpawnChannelFactory env scrubbing + fix bridge.ts comment refs (#4319 wenshao round 2)
Folds in wenshao review on #4319 round 2 — 1 Critical + 2 Suggestions:
1. **[Critical] spawnChannel.ts has 0 unit tests, security-critical
paths untested.** Now that `defaultSpawnChannelFactory` is a public
export of `@qwen-code/acp-bridge`, channels + IDE consumers can't
rely on cli-package integration tests for env-scrubbing guarantees.
Refactored the inline env-scrubbing logic into a pure exported
helper `scrubChildEnv(source, scrubbed, overrides)`. Behavior is
byte-identical to the pre-extraction inline implementation; the
factory body now reads:
const childEnv = scrubChildEnv(
process.env, SCRUBBED_CHILD_ENV_KEYS, childEnvOverrides);
Added `packages/acp-bridge/src/spawnChannel.test.ts` with 12 tests
covering:
- shallow-clone (no aliasing into live process.env)
- QWEN_SERVER_TOKEN stripping
- non-scrubbed vars pass through
- override-add a new key
- override-replace an existing key
- override with undefined deletes the key (PR 14 fix#4247 wenshao R5)
- override CANNOT re-introduce a scrubbed key (defense in depth)
- override CANNOT undo the scrub by setting undefined for a scrubbed key
- override-apply-after-scrub ordering invariant
- empty overrides equals no overrides
- multi-key scrub for forward-compat (the WARNING comment on
SCRUBBED_CHILD_ENV_KEYS anticipates a future sandboxed-agent
mode expanding the denylist; this verifies the loop already
handles that)
The killChild SIGTERM→SIGKILL escalation + STDERR_LINE_CAP_CHARS
truncation are NOT covered yet — they require either real child
processes or extensive node:child_process mocking; both are
orthogonal to the env-scrubbing security guarantees wenshao
explicitly called out, and can land as a follow-up if anyone
wants the full surface tested.
2. **[Suggestion] bridge.ts comments referenced a "consolidated re-
export block earlier in this file" that doesn't exist in acp-bridge
(only in the cli shim).** Fixed both occurrences (~line 292, ~line
310) to point at the actual local import + the package barrel
re-export.
3. **[Suggestion] bridge.ts canonicalizeWorkspace re-export comment
referenced `./fs/paths.ts`.** Updated to mention the full lift
chain: extracted to `cli/src/serve/fs/paths.ts` in PR 18, then
lifted here to `./workspacePaths.ts` in PR 22b/1.
- 12/12 new spawn env-scrub tests pass
- 62/62 acp-bridge total (50 existing + 12 new spawn)
- 174/174 cli httpAcpBridge tests still pass (the factory's inline
env-scrubbing refactor preserves byte-identical behavior)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): fix 14-arg→7-arg typo in test docstring + simplify canonicalizeWorkspace re-export doc (#4319 wenshao round 3)
Folds in 2 of 3 wenshao Suggestions from #4319 round 3:
1. `bridgeClient.test.ts:20` JSDoc said "the 14-arg constructor's
positional slot" — typo I introduced when writing the test in
`fbc92bccf`. The same docstring correctly says "the constructor
takes 7 positional args" at line 25. Updated to "7-arg".
2. `bridge.ts:3461` `canonicalizeWorkspace` re-export JSDoc no longer
references the historical `cli/src/serve/fs/paths.ts` location.
Reads cleaner as a present-tense pointer to `./workspacePaths.ts`
(where the implementation actually lives now post-PR 22b/1).
Git history covers the lift chain; the docstring should describe
current state.
DECLINED + tracked separately:
- **[Critical]** `closeSession` + `killSession` use module-scoped
`channelInfo` instead of `channelInfoForEntry(entry)` — channel-
overlap edge case can kill the wrong channel. Wenshao explicitly
notes "pre-existing bug preserved by the lift" — F1's mechanical-
lift scope shouldn't carry behavior fixes, and the fix needs a
channel-overlap regression test to land safely. Tracked as #4325.
- 62/62 acp-bridge tests pass (no regression from doc tweaks)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): polish from second-pass self-review (cross-platform test + package metadata + dead tombstones)
Five small adoptions from a second-pass code-reviewer agent review on
F1 (no new external comments — pre-emptive cleanup before reviewer
returns):
1. **`bridge.ts:290-313`** — deleted two standalone "InvalidPermission
OptionError / WorkspaceInit* / McpServer* lifted to bridgeErrors"
tombstone comments. Pre-22b they were load-bearing (explained why
the class wasn't `class`-defined inline at that file location).
Post-F1 the symbols are imported at the top of the file and the
comments sit between unrelated code (`writeServeDebugLine` /
`MAX_DISPLAY_NAME_LENGTH` / `DEFAULT_INIT_TIMEOUT_MS`) with no
anchor. Dead doc — removed.
2. **`README.md`** — `spawnChannel` entry now lists `scrubChildEnv`
alongside `defaultSpawnChannelFactory` + `killChild` +
`SCRUBBED_CHILD_ENV_KEYS`. Channels / VSCode IDE consume the
package barrel so the helper should be visible in the inventory.
3. **`package.json:description`** — refreshed from the PR 22a wording
("EventBus, AcpChannel, in-memory channel, PermissionMediator
interface") to include F1 additions (`createHttpAcpBridge` /
`BridgeClient` / `defaultSpawnChannelFactory` / `BridgeFileSystem`).
Visible on `npm view`-style tooling + IDE hover so worth keeping
current.
4. **`bridgeClient.test.ts:92-115`** — swapped `/proc/no-such-file`
for `/this/dir/never/exists/file.txt` and reworded the comment.
`/proc/` is Linux-only; on macOS / Windows the inline proxy's
dangling-symlink fallback would write through to a path under
root rather than failing. Test passed regardless (mock assertion,
not real disk) but the comment overstated portability.
5. **`spawnChannel.test.ts:36`** — added a comment block explaining
why the test deliberately hand-rolls the SCRUBBED set instead of
importing the production `SCRUBBED_CHILD_ENV_KEYS`. The
decoupling is intentional (pure-function parameterized test +
forward-guard for future denylist expansion) but a naive reader
would think it's an oversight.
- 62/62 acp-bridge tests pass
- 174/174 cli httpAcpBridge.test.ts pass
- typecheck + eslint + pre-commit hooks clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(acp-bridge): bridge.ts security fold-in from #4297 review (3 issues)
Folds 3 unresolved review comments from the post-merge thread on #4297
(wenshao via qwen-latest agent) into F1 (#4319). All 3 touch
`acp-bridge/src/bridge.ts` — the same file F1 already moves the lifted
factory into — so consolidating here saves opening a separate
follow-up PR and keeps the security narrative in one reviewable
commit. The 2 cross-package fixes (`core/src/memory/const.ts` test
gap + `cli/src/serve/runQwenServe.ts` malformed-context fallback)
will land as their own small PRs after F1 merges.
#### Fix 1 (wenshao Critical, #4297 thread): `fs.unlink(target)`
arbitrary-file-deletion primitive in `verifyParentWithinWorkspace`
'create'-cleanup
After `fs.open(target, 'wx')` creates the empty file at the real
parent, an attacker with local workspace write access can swap the
parent directory for a symlink (`docs/` → `/etc`). The cleanup's
`fs.unlink(target)` re-resolves the TEXTUAL path through the
attacker's freshly-planted parent symlink, deleting whatever file
exists at the external location.
Fix: drop the `fs.unlink(target)` line. The 0-byte file at the
pre-race location is harmless (0 bytes, inside the workspace we'd
already verified) — leaving it over deleting an arbitrary external
file is the right safety trade. Comment block explains the
reasoning so future maintainers don't re-introduce the unlink.
#### Fix 2 (wenshao Critical): `O_TRUNC` arbitrary-file-truncation
primitive in workspace-init 'overwrite' branch
`O_TRUNC` causes the kernel to truncate the file to zero bytes AT
`open(2)` SYSCALL TIME — strictly before `verifyParentWithinWorkspace`
runs. A parent-symlink TOCTOU race between
`canonicalizeExistingAncestor` and this `open()` zeros the file at
the attacker-redirected location (arbitrary-file-truncation
primitive against any file the daemon UID can open). The pre-fix
code's own comment on `verifyParentWithinWorkspace` acknowledged
this as "Acceptable residual posture for the Stage-1 trust model";
wenshao pushed back that arbitrary-file-zeroing exceeds the
Stage-1 trust budget.
Fix: drop `O_TRUNC` from the open flags. Truncation moves to AFTER
`verifyParentWithinWorkspace` succeeds, via `fh.truncate(0)` on the
fd we already hold. fd-based truncate does NOT re-resolve the path
— an attacker swapping the parent symlink after we open can't
redirect the truncation.
#### Fix 3 (wenshao Suggestion): `canonicalizeExistingAncestor`
missing `ELOOP` catch
Circular symlinks in the parent path (`a -> b`, `b -> a`) cause
`fs.realpath` to fail with `ELOOP`. Without catching it, the error
propagates as an unstructured HTTP 500 instead of the typed
`WorkspaceInitSymlinkError` (HTTP 400) the route handler expects
from the workspace-init race-detection family.
Fix: add `'ELOOP'` to the caught error codes alongside `'ENOENT'`
and `'ENOTDIR'`. Walking up the parent chain when ELOOP hits at a
sub-component preserves the existing "walk to the deepest extant
ancestor" contract — the deepest realpath-able ancestor still
dictates the canonical prefix.
#### Why no new tests in this commit
- Fix 1 is a single-line removal: any regression that re-adds the
unlink would be caught by reviewing the diff; existing 174-test
`httpAcpBridge.test.ts` integration suite confirms the create-path
still works (file is created + closed correctly; only the
attacker-cleanup branch changes).
- Fix 2 is a structural move (truncate from open-time to post-verify);
the existing overwrite-init integration tests confirm the
end-to-end behavior is unchanged (file ends up empty after init).
Adding a TOCTOU race regression test requires controlled
filesystem-race simulation that exceeds reasonable test infra
scope for this PR.
- Fix 3 is a one-word addition to an error code list; the
`canonicalizeExistingAncestor` helper is module-private and the
integration test for circular-symlink → typed 400 would require
exporting it OR setting up a real circular-symlink workspace.
Both routes widen scope beyond the security fix itself; the
high-level behavior is verifiable by the existing route-error-
mapping test pattern + diff review.
A follow-up PR can add the integration tests once the security fix
itself has shipped; the immediate priority is closing the
arbitrary-file-deletion + arbitrary-file-truncation primitives.
- 62/62 acp-bridge tests pass
- 174/174 cli httpAcpBridge.test.ts pass
- typecheck + eslint clean
#### Refs
- Original review on #4297 (wenshao via qwen-latest agent), post-
merge, currently unresolvable on #4297 itself because that PR is
already MERGED.
- Other 2 #4297 review threads (`const.ts` test coverage,
`runQwenServe.ts` malformed-context observability) target files
outside F1's scope and will land as separate follow-up PRs.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: post-merge Codex P2 fold-in — MCP restart disabled-tools normalization + SDK timeout headroom (#4319)
Folds in 2 P2 findings from a Codex review run on `git diff main...HEAD`
of F1 PR #4319. Both are pre-existing in code merged into
`daemon_mode_b_main` before F1 was created (#4282 PR 17), but they're
tiny tactical fixes (~25 LOC + 1 LOC) on the same integration branch
the same reviewer (wenshao) already engages with, so folding into F1
saves an extra follow-up PR cycle.
#### Fix 1: normalize disabled tool names during MCP restart refresh
`packages/cli/src/acp-integration/acpAgent.ts:1563-1566`
The bootstrap path in `cli/src/config/config.ts:1426-1434` applies a
4-step normalization to `tools.disabled`:
1. typeof string filter
2. .trim()
3. drop empty after trim
4. dedupe via Set
The MCP-restart refresh path only did step 1, then stored the raw
strings. `ToolRegistry` checks disabled tools with EXACT
`Set.has(tool.name)`, so a tool disabled at boot as `' Foo '` (or
`'Foo\n'`) is no longer matched after `restartMcpServer` and gets
silently re-registered. This contradicts the documented "toggle +
restart" workflow that #4282 PR 17 advertised.
Fix: mirror the bootstrap normalization verbatim before
`setDisabledTools`. Adds 6 lines + a 7-line comment pointing at the
bootstrap reference for future maintainers.
#### Fix 2: add headroom to MCP restart SDK timeout
`packages/sdk-typescript/src/daemon/DaemonClient.ts:102`
The SDK's `MCP_RESTART_DEFAULT_TIMEOUT_MS` was EXACTLY 300_000ms, the
same ceiling the daemon's own `MCP_RESTART_TIMEOUT_MS` uses for the
upper bound on a single MCP rediscovery. For restarts that finish
(or fail with a typed `McpServerRestartFailedError` JSON envelope)
near 300s, the client `AbortSignal` could fire BEFORE the daemon had
finished serializing + transmitting the response, yielding a client
`TimeoutError` even though the daemon was still within its own
budget.
Fix: bump to 330_000ms (10% / 30s headroom over the daemon ceiling).
Comment updated to call out the race + the rationale for the
specific headroom value. Callers needing tighter caps still pass
their own `timeoutMs` to `restartMcpServer`.
#### Why folded into F1 vs separate follow-up PRs
These are post-merge findings on `#4282 PR 17` code, not F1-introduced
regressions. Normally we'd track as separate follow-up issues (mirror
of the #4325 / `channelInfo` decline). But:
- Both fixes are TINY (~25 LOC + ~2 LOC including comment); the bridge
security fold-in commit `7bd66c6e8` set the precedent of folding in
small same-branch issues when the cost-benefit favors closing them
immediately.
- Same reviewer (wenshao via qwen-latest agent) — won't be confused
by the scope expansion; in fact the original PR 17 commenter is
also the one who'd review the follow-up issue's fix.
- Both fixes target `daemon_mode_b_main`-only paths (MCP restart route
added by PR 17 lives on the integration branch).
- Saves opening 2 trivial follow-up issues that would just sit until
someone picks them up.
#### Verification
- sdk-typescript: 424/424 tests pass (no test hardcoded the old
300_000 default — only the constant declaration itself referenced it)
- cli acp-integration: 282/282 tests pass (no test exercised the
exact whitespace-bearing disabled-tools scenario, so no test
changes were strictly required; a regression test would belong in
a separate test-coverage PR alongside the const.ts test gap from
the #4297 unresolved-comment thread)
- typecheck clean across cli + sdk-typescript
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): wenshao review round 4 — 3 Suggestion fold-ins (#4319)
1. **bridge.ts:2270 stale line refs in `publishWorkspaceEvent` JSDoc**
— comment said `permission_resolved at line 1717` (actual: line 682)
and `broadcastWorkspaceEvent closure at ~line 2127` (actual: line
1281). Line numbers drifted across the lift commits. Replaced both
with function-name refs (`in resolvePending`, `declared above in
this factory body`) that survive future edits.
2. **`ws.ts:613` opaque references in bridgeFileSystem.ts:20 +
bridgeOptions.ts:267** — no `ws.ts` file exists in the repo; the
ref came from an internal review thread on PR 18 that future
readers can't locate. Replaced with a self-contained description
("post-PR-18 follow-up thread about BridgeClient's inline fs proxy
bypassing WorkspaceFileSystem (originally raised in…
* refactor(daemon): drop dead try/catch around model_switched publish (BX9_p) (#4557)
* fix(serve): post-merge fixes for #4291 review (7 threads) (#4305)
* fix(serve): address qwen-latest review on merged #4291 (7 threads)
Seven post-merge findings from the qwen-latest review on #4291,
all real. Most are tightening fixes for issues introduced by the
earlier rounds of #4291 — the same security / DRY / observability
classes the original review surfaced, applied to surfaces that
weren't covered initially.
#1 (deviceFlow.ts:1179) — late-poll observer closure retained the
entire entry by reference (deviceCode/pkceVerifier BrandedSecrets +
cancelController) for the lifetime of the daemon if `provider.poll()`
never settled. Memory leak + indefinite secret retention. Destructure
the four fields the closure actually needs (deviceFlowId, providerId,
initiatorClientId, audit sink) so the entry is GC-eligible the
moment runPollTick returns.
#2 (server.ts) — `callerIsInitiator` was duplicated verbatim across
three locations: GET handler, toDeviceFlowStartResponseBody,
toDeviceFlowStateBody. The exact bug class #4291 was fixing was
"POST and GET diverged on the same redaction policy" — duplicating
the gate recreated the preconditions for divergence. Extracted to
shared `callerIsDeviceFlowInitiator(view, callerClientId)` helper
with the consolidated threat-model JSDoc. All three sites now call
the helper.
#3 (deviceFlow.ts:1110) — timeout callback constructed two separate
`DeviceFlowPollTimeoutError` instances (one for `signal.reason`, one
for the wrapper rejection). Each capture its own V8 stack trace,
and `signal.reason.stack` would diverge from the caught rejection's
stack — confusing for operators inspecting both. Build the sentinel
ONCE per timer fire and pass the same instance to both sites.
#4 (qwenDeviceFlowProvider.ts:273) — `Error.name` is a freely
assignable string property; a hostile fetch wrapper could set
`e.name = 'X\n[serve] FAKE LINE\x1b[31m'` to inject log lines or
ANSI sequences via the same vector we already closed for `oauthError`.
The non-OAuth catch path interpolated `${err.name}` raw. Apply the
same `sanitizeForStderr()` helper.
#5 (deviceFlow.ts:1551) — on the timeout path, `rawProviderError`
is undefined (deliberately, to skip the misleading
`provider.poll() threw (raw): ...` audit template), but that left
the audit hint field omitted entirely. Operators reading the
durable audit trail saw `errorKind: 'upstream_error'` with no signal
whether it was a hung IdP or a generic provider failure. Use
`result.hint` (which already carries the timeout-specific
`provider.poll() timed out after Nms; check IdP connectivity` text
built in the catch) so the audit matches the SSE event.
#6 (server.ts) — the `QWEN_SERVE_DEBUG` env-var check was inlined
in the GET route handler, duplicating the `isServeDebugMode()`
helper from `./debugMode.js` that workspaceAgents and
workspaceMemory already use. The inline copy also had a dead `?? ''`
fallback (the value is guaranteed truthy at that point per the
preceding check). Use the canonical helper.
#7 (deviceFlow.ts:1217) — late-rejection observer interpolated the
raw `lateErr.message` into the audit hint (truncated to 256 bytes,
but RFC 8628 `device_code` values fit comfortably in 256 bytes).
The provider's catch already uses the `name + length` redaction
pattern to prevent WAF-echoed `device_code`/PKCE leaks; the
registry layer was undoing that hardening because the same failure
settled late. Apply the same `name + length` pattern at the late-
rejection site.
Tests:
- Existing late-rejection test reseeded with a `device-code-secret-*`
substring inside the long detail; hard-negative-asserts the seeded
secret is absent from the audit + asserts the new
`Error (message N bytes; raw suppressed)` shape.
- Existing poll-timeout test now also asserts: hint IS defined on
the audit (not omitted), hint contains `'timed out after'` /
`'check IdP connectivity'`, and `signal.reason instanceof
DeviceFlowPollTimeoutError` (proves the single sentinel is
shared between abort and reject).
- New `sanitizes control characters in attacker-controlled
err.name` test in qwenDeviceFlowProvider.test.ts pins the round-4
#4 fix with a hostile `e.name` containing `\n` + `\x1b[31m...`.
cli serve 702/702 (was 686, +16 — additional tests imported via
the acp-bridge package lift on main); sdk 421/421; typecheck clean
across all 4 workspaces; eslint --max-warnings 0 clean on touched
files.
Refs: #4175, #4255, #4291🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address deepseek-v4-pro review on #4305 (4 threads)
Round-5 fold-in. Four findings from the deepseek-v4-pro review on
PR #4305 — all real, three are sister fixes for the same security
classes that #4305 already closed at adjacent surfaces.
#1 (deviceFlow.ts) — `pollTimedOut` race correctness. The flag was
set unconditionally inside the timer callback. If the provider
settled the wrapper at 29.9s, `finally` would call
`clearScheduled(pollTimer)` — but if the timer callback was already
queued for execution before the clear landed (a real possibility
in Node's event-loop ordering, even if not always observed in
practice), this branch could still run and incorrectly mark
`pollTimedOut`. Move the flag assignment to the catch block where
the settled cause is unambiguous via `instanceof
DeviceFlowPollTimeoutError`. New test pins the negative: provider
beats the timeout → no spurious `lost_late_poll_after_timeout`
audit even after ticking 2× the ceiling.
#2 (deviceFlow.ts) — late-rejection observer interpolated raw
`lateErr.name` into the audit hint without sanitization. Same
attacker-controlled vector closed at the provider layer for
`err.name` in round-4. Route through `sanitizeForStderr`.
#3 (deviceFlow.ts) — late-success observer interpolated
`latePollResult.kind` directly into the audit template. While the
typed shape is `'pending' | 'slow_down' | 'success' | 'error'`, a
non-conforming provider could return an arbitrary string. Same
log-injection vector. Route through `sanitizeForStderr`.
#4 (qwenDeviceFlowProvider.ts → deviceFlow.ts) —
`sanitizeForStderr` only stripped ASCII C0/C1 + DEL; bypass via
Unicode lookalikes:
- U+2028/U+2029: LINE/PARAGRAPH SEPARATOR (newline-equivalent in
most Unicode-aware terminals — most direct log-forging vector)
- U+200B–U+200F: zero-width chars + LRM/RLM
- U+202A–U+202E: bidirectional override controls
- U+FEFF: BOM / ZWNBSP
A malicious IdP returning `slow_down [serve] FAKE` in
`oauthError` would otherwise still forge log lines.
Architectural change: `sanitizeForStderr` was previously private to
`qwenDeviceFlowProvider.ts`. To address #2/#3, the registry layer
needs to call it too. Lifted into `deviceFlow.ts` (the foundation
module) and re-imported from the provider. Single source of truth;
the regex is now a module-level constant compiled once with explicit
`\uXXXX` escapes (via `String.raw` so the source is greppable, not
literal-Unicode-laden).
Tests:
- `does NOT attach late-poll observer when the provider beats the
timeout` — N1 race regression
- `sanitizes hostile latePollResult.kind in late-observer audit` — N3
- `sanitizes hostile lateErr.name in late-rejection observer audit` — N2
- `sanitizes Unicode lookalike controls (U+2028 LINE SEPARATOR,
bidi, ZWNBSP) in oauthError` — N4
cli serve 706/706 (was 702, +4 — all new round-5 tests); sdk
421/421; typecheck clean; eslint --max-warnings 0 clean on touched
files.
Refs: #4175, #4255, #4291, #4305🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address gpt-5.5 + qwen-latest review on #4305 round-5 (5 threads)
Round-6 fold-in. Five findings split between maintainability,
security hardening, and a real defensive bug.
#1 (qwenDeviceFlowProvider.test.ts) — gpt-5.5: round-5 #4 test
embedded U+2028 / U+200E / U+FEFF as literal characters in source.
Invisible in GitHub diffs / most editors; the negative
`not.toContain('')` looked like an empty-string check. Rewrote
the payload + assertions to use named `\uXXXX`-bound constants.
Also added a companion test exercising U+2066–U+2069 (round-6 #5
below).
#2 (deviceFlow.ts) — qwen-latest: the late-poll observer's
`void tracked.then(...)` was missing a terminal `.catch(() => {})`.
A synchronous throw inside either handler (e.g., a misbehaving
`audit.record`: backpressure, malformed payload, sink out-of-disk)
would reject the derived promise unhandled. On Node 22's default
`--unhandled-rejections=throw`, that crashes the daemon. Added the
terminal `.catch(() => {})` matching the persist-tracker pattern.
New test injects a poison audit sink that throws specifically on
the `lost_late_poll_after_timeout` call; asserts `flushAsync()`
resolves cleanly.
#3 (deviceFlow.ts) — qwen-latest: the `case 'error'` audit-record
hint interpolated `rawProviderError` (raw `err.message`) without
`sanitizeForStderr`. Per ES2019+ `JSON.stringify` no longer escapes
U+2028/U+2029 — those would still forge log lines downstream
through file/stdout audit sinks. Apply the same sanitizer used on
every other provider-controlled audit path. New test pins a hostile
provider message containing U+2028 + ANSI escape and asserts
neither survives.
#4 (deviceFlow.ts) — qwen-latest: the round-5 #1 comment claimed
"`DeviceFlowPollTimeoutError` isn't exported as a public DeviceFlow
contract", but it IS `export class` (the test file constructs it
directly for fixtures). With `pollTimedOut = true` keyed solely on
`instanceof`, a future provider that imports + throws the class
would spoof the registry's "I caused the timeout" signal —
attaching a phantom late-poll observer.
Fix: introduce a runtime brand `_isRegistryTimeout: boolean` on the
class (default `false`) plus an internal-only
`makeRegistryPollTimeoutError(ms)` helper that sets the brand to
`true`. The brand is set ONLY at the registry's race-timer
construction site. Both gates updated:
- `if (err instanceof X && err._isRegistryTimeout === true)` in
the catch (for `pollTimedOut`)
- `if (lateErr instanceof X && lateErr._isRegistryTimeout === true)`
in the late-rejection self-filter
A provider-thrown brand-false instance now flows through the
generic provider-throw audit path — correctly auditing the misuse
rather than silently swallowing it. Repurposed the original "no
double-audit when registry's own DeviceFlowPollTimeoutError is
late-rejected" test (which was actually exercising the brand-false
path) into the inverted assertion: brand-false provider throw IS
audited as a real failure. Removed the orphaned old assertion; the
brand-true happy path is implicitly covered by the hanging-provider
test (which exercises the registry-built timeout end-to-end).
#5 (deviceFlow.ts) — qwen-latest: `sanitizeForStderr` regex covered
U+202A–U+202E (bidi embedding/override) but missed U+2066–U+2069
(LRI/RLI/FSI/PDI). These are the primary CVE-2021-42574
("Trojan Source") attack vectors — a hostile IdP swapping U+2066
for U+202D achieves the same visual reordering and would have
bypassed the round-5 filter entirely. Extended the regex range and
JSDoc; new test exercises U+2066/U+2068/U+2069 in `oauthError` and
asserts none survive while substantive ASCII parts remain.
cli serve 713/713 (was 710, +3 round-6 tests + the round-5 #4
rewrite + the round-6 #5 companion); typecheck clean across all 4
workspaces; eslint --max-warnings 0 clean on touched files.
Refs: #4175, #4255, #4291, #4305🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): replace literal U+2028 with explicit escape in round-6 #3 test
PR #4312 review (Copilot): the round-6 #3 test (sanitizes
rawProviderError) regressed back to embedding a literal U+2028
character in source via `const U_2028 = ' '`. That's the same
maintainability anti-pattern round-6 #1 was fixing in the sister
test. Internal-consistency fix: switch to the explicit ` `
escape so the constant is greppable and reviewable in GitHub diffs.
Refs: #4291, #4305, #4312🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): post-merge P2 corrections from Codex review on #4282 (#4297)
* fix(serve): post-merge P2 corrections from Codex review on #4282
Follow-up to PR #4282 (Wave 4 PR 17) addressing four P2 issues
flagged by Codex's `/review` after the squash-merge to main:
P2-1 — Read the workspace context filename for init
`qwen serve` parent never goes through `loadCliConfig`, so the
process-global `getCurrentGeminiMdFilename()` stays on the default
`QWEN.md` even when the workspace configures
`context.fileName: 'AGENTS.md'`. `runQwenServe` now snapshots the
workspace's merged setting at boot and forwards via
`BridgeOptions.contextFilename`, so init writes the same file the
ACP child reads.
P2-2 — Restart MCP servers with a fresh disabledTools snapshot
`Config.disabledTools` was frozen at construction time;
`setWorkspaceToolEnabled` only updated settings.json. The
documented "toggle + restart" workflow re-registered just-disabled
tools because rediscovery still saw the bootstrap snapshot. Added
`Config.setDisabledTools()` plus a re-read at the ACP restart
handler so `discoverMcpToolsForServer` honors the latest set.
P2-3 — Match the SDK timeout to the daemon's restart budget
Bridge waits up to 300s for stdio MCP discovery; SDK helper used
the client-wide 30s default and aborted valid slow restarts.
Added a per-call `timeoutMs` plumbed through `fetchWithTimeout`,
defaulting `restartMcpServer` to 5 minutes.
P2-4 — Reject symlinked parent directories before init writes
`lstat(target)` only checked the final component; a symlinked
parent (e.g. `docs -> /tmp` with `context.fileName:
'docs/QWEN.md'`) would let `writeFile` follow the link and create
/ truncate outside `boundWorkspace`. Added
`canonicalizeExistingAncestor` (walks up through ENOENT to the
deepest extant ancestor, then `realpath`s) and verifies the
canonical parent stays within the canonical workspace.
5 new tests (4 bridge / 2 SDK):
- contextFilename snapshot honored
- parent-symlink escape rejected
- nested real subdir accepted
- restartMcpServer survives 1.2s response with 1s default timeout
- restartMcpServer honors a 50ms caller override
Typecheck clean across cli / sdk-typescript / core.
1604/1604 unit tests pass.
* fix(serve): fold-in 1 — address 16:32:44-round review on #4282
Follow-up addressing the 8 unresolved review threads opened on PR
shipping in this same #4297; addresses correctness gaps + missing
test coverage that would otherwise let regressions ride into main.
Behavior fix:
- broadcastWorkspaceEvent gains a `skipSessionId` parameter; when
`setSessionApprovalMode` runs with `persist:true`, the broadcast
skips the requesting session so it doesn't receive the same
`approval_mode_changed` event twice (once via session-scoped
publish + once via broadcast). The SDK reducer's
`approvalModeChangedCount` now increments by 1, not 2, on the
requesting client (peers still see 1 via the broadcast).
Addresses #3260501134.
Observability + posture:
- broadcastWorkspaceEvent now mirrors PR 16's publishWorkspaceEvent
member: per-entry success/failure accounting + an "ALL buses
dropped" stderr elevation. The previous local helper silently
swallowed every publish failure. Addresses #3260501126.
- WorkspaceInitPathEscapeError + WorkspaceInitSymlinkError typed
classes for the two boundary guards in initWorkspace, mapped to
HTTP 400 by sendBridgeError. Previous generic `Error` fell
through to the 500 handler, telling operators "daemon broken"
when the actual fix was workspace-config correction. Addresses
#3260501161.
Public surface symmetry:
- Re-export McpServerNotFoundError, McpServerRestartFailedError,
WorkspaceInitPathEscapeError, WorkspaceInitSymlinkError from the
serve barrel. External embeds matching these via `instanceof`
no longer need deep imports. Addresses #3260501163.
Test coverage:
- restartMcpServer bridge tests (5): success + event broadcast,
soft-skip + refused event, McpServerNotFoundError translation,
McpServerRestartFailedError translation, originator clientId
stamping. Addresses #3260501141.
- sendBridgeError mapping tests (4): McpServerNotFoundError → 404,
McpServerRestartFailedError → 502, WorkspaceInitPathEscapeError
→ 400, WorkspaceInitSymlinkError → 400. Addresses #3260501148.
- initWorkspace boundary guard tests (2 added): symlink-at-target
rejected, contextFilename '../outside.md' rejected. Addresses
#3260501157.
- TrustGateError tests assert the typed class via `.toThrow(TrustGateError)`,
not just message text. Addresses #3260501165.
Also updates the existing fold-in 4 S2 broadcast test to reflect
the new no-duplicate semantics on the requesting session.
Typecheck clean across cli / sdk-typescript / core.
1615/1615 unit tests pass.
* fix(serve): fold-in 2 — copilot + wenshao review on #4297
Round-2 reviewer adoption on the same PR:
Critical fixes:
- `restartMcpServer` JSDoc documents `timeoutMs: 0` as "disable the
timeout entirely", but the `> 0` guard in `fetchWithTimeout`
rejected `0` and silently fell back to the 30s client default.
Loosened the guard to `>= 0` so `0` flows through to the
no-timeout branch via the existing truthiness check; NaN /
negative inputs still coerce to the client default. Addresses
duplicate reports from copilot (#3260577538) and wenshao
(#3260661833).
- TS2322 in the slow-fetch test stub: `resolveResponse` was typed
against `import('undici-types').Response` but assigned a
`(v: Response) => void`. Re-typed against the global `Response`
throughout. Caught only by tsc runs that include the test
files. Addresses #3260663072.
Test fidelity:
- Slow-fetch stub now observes `init.signal` and rejects on abort,
so a regression that drops the per-call `timeoutMs` override
will reliably fail the test instead of resolving after the
timer fired (false-negative coverage). Addresses #3260577600.
- New test pinning the `timeoutMs: 0` semantics: 1ms client
default + a stub that resolves after 50ms. Without the `>= 0`
fix, the call would abort at 1ms; with it, the explicit
`0` disables the timer and the call completes.
Bug fixes:
- `runQwenServe.contextFilenameForInit` previously called
`String(arr[0])` on the array branch, producing a literal
`"[object Object]"` filename for hand-edited bad data. Now
validates each element with `typeof === 'string'` and falls
back to `undefined` (so the bridge uses its
`getCurrentGeminiMdFilename()` default) when no string is
found. Addresses #3260577641.
Documentation drift:
- `Config.getDisabledTools()` JSDoc rewritten to describe the
mutable-via-`setDisabledTools()` semantics introduced by P2-2,
and the "registration-time only / no retroactive unregister"
contract that pairs with it. Old comment claimed the set was
frozen at construction. Addresses #3260577677.
Observability:
- `acpAgent` MCP-restart `loadSettings` failure now surfaces a
stderr line naming the server + the underlying error, instead
of silently swallowing it. The documented "toggle + restart"
workflow used to break with zero diagnostic when settings.json
was corrupted or unreadable. Addresses #3260663303.
Code organization:
- Moved `canonicalizeExistingAncestor` after `describeStatKind` so
the latter's JSDoc is no longer orphaned (TypeScript only
associates the last `/** ... */` block before a declaration).
Addresses #3260668618.
Typecheck clean across cli / sdk-typescript / core.
1616/1616 unit tests pass.
* fix(serve): fold-in 3 — read merged scope on MCP restart refresh
Critical bug from wenshao review (#3260725526) on PR #4297:
the P2-2 acpAgent re-read narrowed `Config.disabledTools` to
`SettingScope.Workspace` alone, dropping User / System scope
entries. The bootstrap Config received `merged.tools?.disabled`
(union of all scopes), so user-level / system-level disables
worked at boot — but the first `mcp restart` would replace the
in-memory set with the workspace scope alone, silently re-enabling
any tool that was disabled at a higher scope but absent from the
workspace file.
The asymmetry vs. the persist-write path is deliberate and
documented:
- Reads (here): merged — match the bootstrap Config snapshot,
preserve user/system policy.
- Writes (`runQwenServe.persistDisabledTools`): workspace scope —
don't bake higher-scope entries into the workspace file
(per-#4282 fold-in 1 H2 fix).
Two paths look alike but answer different questions.
Typecheck clean across cli / sdk-typescript / core.
1616/1616 unit tests pass.
* fix(test): fold-in 4 — wire timeoutMs:0 stub to init.signal
Critical follow-up from wenshao (#3260810242) on PR #4297:
the new `timeoutMs: 0` regression test (added in fold-in 2)
inherited the same flaw it was meant to prevent — the slow-fetch
stub didn't observe `init.signal`, so a regression that ignored
the `0` override would fire the AbortController at the 1ms client
default but the stub would keep the promise pending. The 50ms
`resolveResponse` would win, the test would still pass, and the
documented "0 disables timeout" contract would be unprotected.
Mirrored the listener pattern already used by the two sibling
tests in fold-in 2 — `init.signal.addEventListener('abort', () =>
reject(...))`. Now a regression that re-rejects `0` triggers the
abort, the stub rejects, the test fails.
8/8 restartMcpServer SDK tests pass; SDK typecheck clean.
* fix(serve): fold-in 5 — TOCTOU + setDisabledTools coverage
Two new critical reviews from wenshao on PR #4297:
C1 — TOCTOU between lstat and writeFile (#3260836305):
The `lstat(target)` symlink check and the subsequent `writeFile`
were two separate syscalls, leaving a race window where a local
attacker with workspace write access could substitute a symlink
between them. With `force: true`, `writeFile` would follow the
link and truncate an external target.
The `action === 'created'` path now uses `fs.open(target, 'wx')`
(O_WRONLY|O_CREAT|O_EXCL), which atomically refuses any
pre-existing inode (regular file, dir, OR symlink) at the target
path. EEXIST after the absence check most plausibly means a
race-created symlink, so we throw `WorkspaceInitSymlinkError(kind:
'target')` — same typed class the route maps to 400.
The `force: true` overwrite path retains the existing TOCTOU as a
documented limitation; closing it requires `O_NOFOLLOW`-aware open
which the post-PR18 `WorkspaceFileSystem` migration will provide.
C2 — P2-2 zero test coverage (#3260836302):
The `setDisabledTools` runtime sync was the only Wave-4 P2 fix
without a dedicated test. Added 5 Config-level tests:
- Initializes from `disabledTools` ConfigParameters
- Defaults to empty set when omitted
- `setDisabledTools` replaces the live snapshot
- Defensive copy: caller-set mutations don't leak into the live snapshot
- Accepts an empty set (clears live snapshot)
Plus a TOCTOU regression test in httpAcpBridge.test.ts that
spies fs.lstat / fs.readFile to simulate the race window:
pre-creates a symlink, makes lstat lie about it, asserts the
'wx' open catches the racing inode and throws the typed
`WorkspaceInitSymlinkError(kind: 'target')`.
1622/1622 unit tests pass; typecheck clean across cli /
sdk-typescript / core.
* fix(serve): fold-in 6 — count actual skips in broadcast alarm
DeepSeek review on #4297 (#3261079572):
`broadcastWorkspaceEvent` unconditionally subtracted 1 from the
`eligible` recipient count whenever `skipSessionId` was set, even
when the id matched zero live sessions (caller mistake, stale id,
or the matching session was just torn down between resolution and
broadcast). In a single-session workspace that's the difference
between `eligible = 0` (alarm suppressed) and `eligible = 1`
(alarm fires when the publish failed) — silently losing the
all-dropped breadcrumb the telemetry was meant to surface.
Today's call sites pass real session ids so the bug doesn't
manifest in practice, but the defensive shape is small: track
`skippedCount` inside the loop and subtract that, so the alarm
condition is self-consistent regardless of how the caller mis-uses
the param.
162/162 bridge tests pass; CLI typecheck clean.
* fix(serve): fold-in 7 — close overwrite TOCTOU, harden boot + diagnostics
Round-7 review on PR #4297. Three critical fixes + one suggestion
test, plus a regression test for the overwrite TOCTOU close.
C1 — force:true overwrite TOCTOU (#3262615446):
The fold-in 5 fix only closed the `'created'` action via 'wx';
the `'overwrote'` branch still used plain `fs.writeFile`, so a
local writer could swap the verified regular file to a symlink
between the lstat/readFile checks and the write and have the
forced overwrite truncate an external target. Switched to
`fs.open(target, O_WRONLY | O_TRUNC | O_NOFOLLOW)` — `O_NOFOLLOW`
makes open() fail with ELOOP on a symlink at the final component
even under race. ELOOP / ENOENT (race-deleted) translate to
`WorkspaceInitSymlinkError(kind: 'target')` so the route still
maps to a structured 400 instead of a generic 500.
C2 — settings.json corrupt blocks daemon boot (#3262625091):
`loadSettings(boundWorkspace)` at boot had no try/catch — a
corrupted, malformed, or temporarily unreadable settings file
threw synchronously and prevented daemon startup. Pre-PR this
never happened because settings were read lazily inside request
handlers. Wrapped in try/catch with stderr fallback so the daemon
keeps booting (with the bridge's default context filename) when
the file is broken.
C3 — malformed `tools.disabled` clears policy silently (#3262625101):
When `merged.tools?.disabled` is present but not an array
(boolean / string / object from a hand-edited settings.json), the
ternary `Array.isArray(...) ? ... : []` substituted an empty list
without firing the surrounding catch block. After an MCP restart
every disabled tool would silently re-register. Added an explicit
`!Array.isArray && !== undefined` check that stderr-logs the
malformed type before clearing — operators see the
misconfiguration instead of a stealth re-enable.
S1 — contextFilename extraction tested (#3262690842):
Lifted the inline `firstStringInArray` + branching into an
exported `extractContextFilename(value: unknown)` helper and
added `runQwenServe.test.ts` with 5 tests covering the four
branches the suggestion called out: non-empty string, array with
strings, array with no strings, non-string non-array.
Plus a TOCTOU regression test for the overwrite path that
verifies `O_NOFOLLOW` returns `WorkspaceInitSymlinkError(kind:
'target')` when the file is race-substituted with a symlink
behind the lstat/readFile mocks.
S2 (acpAgent restart-handler integration test #3262690845) is
deferred — Config-level coverage of `setDisabledTools` already
locks the load-bearing surface (5 tests in fold-in 5), and
adding a full acpAgent integration test requires heavy ext-method
plumbing. The new C3 stderr diagnostic plus existing tests give
us the regression signal we need without that scaffolding.
1627/1627 unit tests pass; typecheck clean across cli /
sdk-typescript / core / acp-bridge.
* fix(serve): fold-in 8 — split ELOOP / ENOENT diagnostic in overwrite path
qwen-latest review on PR #4297 (#3262861754):
The fold-in 7 ELOOP/ENOENT branch shared one error message that
said "swapped to a symlink." That's accurate for ELOOP (genuine
O_NOFOLLOW rejection — likely an attack race) but misleading for
ENOENT in the overwrite path: there `readFile` just succeeded
proving the file existed, so ENOENT means the file was DELETED
between the content check and the open — a benign race with a
concurrent writer (git checkout, editor save, lockfile rename),
NOT a symlink swap. An operator seeing the symlink language for
a benign delete would `ls -la`, see no symlink, and waste time
hunting an attack that didn't happen.
Split into two messages:
- ELOOP: "swapped to a symlink between the content check and the
overwrite — refusing to follow it"
- ENOENT: "deleted between the content check and the overwrite
(likely a concurrent writer) — refusing to recreate blindly"
Both still surface as `WorkspaceInitSymlinkError(kind: 'target')`
so the route maps to a structured 400; the class doubles as the
workspace-init race-condition bucket with kind='target' meaning
"target inode misbehaved at write time" generally.
Updated the existing fold-in 7 TOCTOU test to assert the ELOOP
message specifically, and added a new ENOENT race-delete test
that mocks lstat/readFile to land on the overwrote action against
a non-existent path — verifies the message says "deleted" and
NOT "swapped to a symlink."
170/170 bridge tests pass; CLI typecheck clean.
* fix(serve): fold-in 9 — route MCP restart through registry cleanup wrapper
gpt-5.5 critical review on PR #4297 (#3263088414):
The fold-in 5 P2-2 fix refreshed `Config.disabledTools` from merged
settings, but then called `manager.discoverMcpToolsForServer()`
directly — bypassing the `ToolRegistry.discoverToolsForServer`
wrapper that PURGES the server's existing `DiscoveredMCPTool`
entries (and `revealedDeferred` markers) plus its prompts before
rediscovery. Without the cleanup, `registerTool` only consulted
the refreshed `disabledTools` set for NEWLY-discovered tools —
entries already in the registry from the prior MCP boot kept
serving requests. Net effect: toggle-disable-then-restart
silently left the disabled tool live, breaking the documented
"toggle + restart" workflow that P2-2 was meant to fix.
Routed through `toolRegistry.discoverToolsForServer(serverName)`
which:
1. Removes existing `DiscoveredMCPTool` entries for this server
2. Drops their `revealedDeferred` reveal state
3. Removes the server's prompts via `removePromptsByServer`
4. THEN delegates to `manager.discoverMcpToolsForServer` for the
actual reconnect + rediscover
The pre-discovery budget / in-flight checks still go through the
`manager` reference (which is the same object the registry
wrapper would forward to) — so soft-skip semantics for
`budget_would_exceed`, `in_flight`, `disabled` are preserved.
CLI typecheck clean; 403/403 server + bridge tests pass.
* fix(serve): fold-in 10 — qwen-latest 05:45-round review on #4297
5 review threads from qwen-latest's late round on PR #4297 (now closed
in favor of #4313 against `daemon_mode_b_main`). 1 critical + 4
suggestions, all adopted.
C1 — extractContextFilename / getCurrentGeminiMdFilename divergence
(#3263954685): with `context.fileName: [' ', 'AGENTS.md']`, the
daemon parent's `extractContextFilename` (which skips empty entries)
wrote `AGENTS.md`, but the ACP child's `getCurrentGeminiMdFilename`
(which returned `arr[0]` unconditionally) read `''`. The init'd file
was orphaned. Aligned `getCurrentGeminiMdFilename` to skip empty
entries with the same semantics, falling back to
`DEFAULT_CONTEXT_FILENAME` when all entries are empty.
S2 — WorkspaceInitSymlinkError reused for non-symlink races
(#3263954690): the EEXIST race-create and ENOENT race-delete cases
were surfacing as `code: 'workspace_init_symlink'`, misleading
operators into hunting symlink attacks for benign concurrent-
modification windows. Split into a sibling `WorkspaceInitRaceError`
class (`kind: 'eexist' | 'enoent'`, HTTP code
`workspace_init_race`). The genuine symlink class stays for ELOOP,
lstat-detected target symlinks, and parent-realpath escapes.
S3 — fsConstants.O_NOFOLLOW defensive `?? 0` (#3263954697): matches
the existing codebase convention in
`core/src/utils/{sessionStorageUtils,gitDiff}.ts` and
`cli/src/ui/utils/customBanner.ts`. Functionally a no-op (JS
bitwise coerces undefined to 0) but consistent.
S5 — Parent-directory TOCTOU still open (#3263954707): O_NOFOLLOW
only protects the final path component; a local writer could swap
a real parent dir for a symlink between
`canonicalizeExistingAncestor` and `fs.open`. Added
`verifyParentWithinWorkspace` post-open helper that re-realpaths
`path.dirname(target)` and refuses with
`WorkspaceInitSymlinkError(kind: 'parent')` if the parent moved.
On the create path (where we just opened with `'wx'`), the failure
also unlinks the file we just made best-effort. Residual race
window narrowed from "between pre-check and open" to "between
post-open realpath and writeFile" — sub-millisecond, documented as
accepted Stage-1 trust posture.
S4 — broadcastWorkspaceEvent vs publishWorkspaceEvent stale comment
(#3263954688): the "now removed" comment was inaccurate (5 call
sites still use the closure). Replaced with an accurate
description of why both coexist (factory closure can't `this`-call
proxy member; closure also takes `skipSessionId` for persisted
approval-mode mirror) and a TODO marker for future helper extraction.
Two existing tests updated to assert the new `WorkspaceInitRaceError`
class for EEXIST / ENOENT scenarios (the symlink-class assertions
are preserved for ELOOP / lstat / parent cases).
1759/1759 unit tests pass; typecheck clean across all 4 packages.
* feat(acp-bridge): F1 — acp-bridge package self-sufficiency (#4175 mechanical lift + BridgeFileSystem seam) (#4319)
* refactor(acp-bridge): lift defaultSpawnChannelFactory to acp-bridge/spawnChannel (#4175 F1 step 1)
First mechanical lift of #4175 F1 (acp-bridge package self-sufficiency).
Moves the production spawn factory + its `killChild` helper +
`SCRUBBED_CHILD_ENV_KEYS` denylist + `KILL_HARD_DEADLINE_MS` constant
from `cli/src/serve/httpAcpBridge.ts` (~283 lines) to
`@qwen-code/acp-bridge/spawnChannel`. This unblocks
`channels/base/AcpBridge.ts` and `vscode-ide-companion`'s
acpConnection from each reimplementing the child lifecycle — they can
now consume the same primitive.
Backward compatible: `cli/src/serve/httpAcpBridge.ts` imports the
lifted factory and re-exports it, so existing references in
`cli/src/serve/index.ts:90` and the factory's own internal usage
(`opts.channelFactory ?? defaultSpawnChannelFactory`) keep resolving.
Bridge tests that mock `defaultSpawnChannelFactory` via
`BridgeOptions.channelFactory` are unaffected.
Side cleanups: drops `spawn` / `ChildProcess` / `Readable` / `Writable`
/ `ndJsonStream` / `MissingCliEntryError` imports from
httpAcpBridge.ts (all only used by the lifted spawn factory).
- 44/44 acp-bridge tests pass
- 174/174 cli httpAcpBridge tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor(acp-bridge): lift BridgeClient + permission types to acp-bridge/bridgeClient (#4175 F1 step 2)
Second mechanical lift of #4175 F1 (acp-bridge package self-sufficiency).
Moves `BridgeClient` class (~700 LOC) + `PendingPermission` interface +
`PermissionResolutionRecord` interface + `MAX_RESOLVED_PERMISSION_RECORDS`
constant + early-event capacity constants + `describeStatKind` and
`sliceLineRange` helpers from `cli/src/serve/httpAcpBridge.ts` to
`@qwen-code/acp-bridge/bridgeClient`.
Design choice for SessionEntry boundary: introduce a minimal
`BridgeClientSessionEntry` interface in bridgeClient.ts with only the
four fields BridgeClient actually reads from the factory's richer
`SessionEntry` (`sessionId`, `events`, `pendingPermissionIds`,
`activePromptOriginatorClientId`). The factory's `SessionEntry`
structurally satisfies it — TypeScript's structural typing enforces
the match at the `resolveEntry` callback signature, so no explicit
conversion is required and the bridge package stays free of daemon-host
session-bookkeeping types.
Cross-package writeStderrLine handling: inline the 3-line helper in
bridgeClient.ts (mirrors the spawnChannel.ts pattern from F1 step 1)
so acp-bridge has no reverse dependency on `cli/src/utils/stdioHelpers`.
httpAcpBridge.ts shrinks from 4406 LOC to 3647 LOC (-759 lines).
Removed ACP SDK imports that only BridgeClient consumed: `Client`,
`RequestPermissionRequest`, `WriteTextFileRequest`,
`WriteTextFileResponse`, `ReadTextFileRequest`, `ReadTextFileResponse`,
`SessionNotification`. Kept the ones the factory still uses
(`CancelNotification`, `PromptRequest`, `RequestPermissionResponse`,
`SetSessionModelRequest`, `SetSessionModelResponse`).
Backward compatible: httpAcpBridge.ts re-exports `BridgeClient`,
`BridgeClientSessionEntry`, `PendingPermission`,
`PermissionResolutionRecord`, and `MAX_RESOLVED_PERMISSION_RECORDS` so
the `ChannelInfo.client: BridgeClient` field declaration below + any
embedder reaching into these types keep resolving.
- 44/44 acp-bridge tests pass
- 174/174 cli httpAcpBridge tests pass
- 229/229 cli server tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor(acp-bridge): lift createHttpAcpBridge factory to acp-bridge/bridge (#4175 F1 step 3)
Third + final mechanical lift of #4175 F1 (acp-bridge package
self-sufficiency). Moves the `createHttpAcpBridge` factory closure
(~3000 LOC) + `ChannelInfo` + `SessionEntry` interfaces + factory-only
helpers (`canonicalizeExistingAncestor`, `verifyParentWithinWorkspace`,
`withTimeout`, `isServeDebugLoggingEnabled`, `writeServeDebugLine`,
`hasControlCharacter`) + factory constants (`DEFAULT_INIT_TIMEOUT_MS`,
`MCP_RESTART_TIMEOUT_MS`, `DEFAULT_MAX_SESSIONS`, `MAX_EVENT_RING_SIZE`,
`DEFAULT_PERMISSION_TIMEOUT_MS`, `DEFAULT_MAX_PENDING_PER_SESSION`,
`MAX_DISPLAY_NAME_LENGTH`) from `cli/src/serve/httpAcpBridge.ts` to
`@qwen-code/acp-bridge/bridge`.
`cli/src/serve/httpAcpBridge.ts` shrinks from 3647 LOC to 97 LOC — a
pure re-export shim that preserves every existing relative import
path (`./httpAcpBridge.js`) so `server.ts`, `runQwenServe.ts`,
`workspaceAgents.ts`, `workspaceMemory.ts`, `index.ts`, plus the bridge
test suite, keep resolving without any call-site changes.
The new `bridge.ts` reuses what was already in acp-bridge (errors,
types, options, status helpers, channel types, event bus, workspace
paths) via local relative imports — no reverse dependency on `cli`.
`writeStderrLine` is inlined at the top of `bridge.ts` (same pattern as
`spawnChannel.ts` + `bridgeClient.ts` from F1 steps 1-2) so the
package self-contained promise holds.
Cumulative F1 impact across the 3 mechanical lift steps:
- httpAcpBridge.ts: 4682 LOC → 97 LOC (-4585 lines; the original file
was 98% bridge core, 2% backward-compat re-exports)
- 3 new files in acp-bridge: spawnChannel.ts (~270 LOC), bridgeClient.ts
(~745 LOC), bridge.ts (~3515 LOC)
- All daemon-host concerns (env snapshot, daemon preflight cells)
remain in `cli/src/serve/daemonStatusProvider.ts` and reach the
bridge through the `BridgeOptions.statusProvider` seam frozen by
PR 22b/2.
- 735/735 cli serve tests pass across 17 files
- 174/174 cli httpAcpBridge tests pass
- 44/44 acp-bridge tests pass
- typecheck clean across acp-bridge + cli
`packages/cli/src/serve/httpAcpBridge.test.ts` (~6600 LOC) is
intentionally NOT moved in this commit — it currently imports
`createHttpAcpBridge` / `defaultSpawnChannelFactory` / `BridgeClient`
via the cli shim and keeps passing without changes. Moving it to
`acp-bridge/src/bridge.test.ts` is a follow-up worth tracking
separately so the production-code lift can land + be reviewed cleanly.
The `BridgeFileSystem` injection seam (originally bundled into F1 as
the 22b' scope) is also deferred to a follow-up so the mechanical lift
stays mechanical — design + implementation of the fs injection is its
own discussion.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(acp-bridge): add BridgeFileSystem injection seam (#4175 F1 step 5, 22b' scope)
Adds the `BridgeFileSystem` injection seam originally scoped as #4175
22b'. When a `BridgeFileSystem` is wired through
`BridgeOptions.fileSystem`, `BridgeClient.readTextFile` and
`BridgeClient.writeTextFile` delegate to it instead of running their
inline `fs.realpath` / `fs.writeFile` / `fs.readFile` proxy.
This unblocks production `qwen serve` plumbing PR 18's
`WorkspaceFileSystem` (TOCTOU guards, symlink-substitution checks,
trust gate, `.gitignore`, audit hooks) into the ACP fs methods —
closing the `ws.ts:613` follow-up thread that has been tracked since
PR 18 landed. The serve-side adapter that wraps `WorkspaceFileSystem`
+ the `runQwenServe` wiring are intentionally split into the
immediate-follow-up so this PR stays focused on the seam design.
Backward compatible: `fileSystem` is optional on `BridgeOptions`.
Tests, Mode A in-process consumers, channels (`packages/channels/base/
AcpBridge.ts`), and the VSCode IDE companion all keep working
unchanged — they omit the field and `BridgeClient` falls through to
the inline proxy that has been the Stage 1 default since #3889.
API:
- `BridgeFileSystem.readText(params: ReadTextFileRequest):
Promise<ReadTextFileResponse>`
- `BridgeFileSystem.writeText(params: WriteTextFileRequest):
Promise<WriteTextFileResponse>`
The interface mirrors ACP SDK request/response types directly so the
adapter does the minimum amount of translation (`{ path, content }`
↔ `WorkspaceFileSystem`'s `ResolvedPath` brand types + options bag).
- 735/735 cli serve tests pass (inline fallback path preserved)
- 44/44 acp-bridge tests pass
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): catch README + stale source comments up to F1 lift
Self-review fold-in: post-F1 the package README still said "PR 22a"
and listed `BridgeClient` / `createHttpAcpBridge` /
`defaultSpawnChannelFactory` under "What's not here yet" — both
contradicted by this PR. Updated:
- README lift-history table now shows PR 22a / 22b/1 / 22b/2 as
merged and F1 (this PR) as the slice that closes the bridge core
+ adds `BridgeFileSystem`. F3 PR 24 row aligned to the
feature-cohesive plan.
- "What's here today" now documents `spawnChannel`, `bridgeClient`,
`bridge`, `bridgeFileSystem` modules.
- "What's not here yet" section removed (its 2 bullets are both
resolved by F1).
- Subpath import list updated to enumerate all 14 subpaths.
- Backward-compat section updated to call out the 97-line shim and
the 6 consuming files that still import via `./httpAcpBridge.js`.
Source-comment line-number drift:
- `channel.ts:12` no longer claims `defaultSpawnChannelFactory` is
"still in cli/src/serve/httpAcpBridge.ts" — points to the lifted
location.
- `permission.ts:33` + `permission.ts:45` no longer reference
`httpAcpBridge.ts:1096-1106` / `httpAcpBridge.ts:1003` (file is
now 97 lines after F1). Updated to point at the structurally-
equivalent locations inside the lifted `bridgeClient.ts`.
- `permission.ts:7` no longer says first-responder still lives in
`cli/src/serve/httpAcpBridge.ts` — points at the bridgeClient.ts
location.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): adopt 3 Copilot review comments on F1 doc accuracy
Folds in 3 of 4 Copilot inline comments from #4319 review:
1. `bridgeClient.ts` writeTextFile preserveMode comment said "fall
through to umask defaults" for new files, but the code passes
`mode: preserveMode?.mode ?? 0o600` to `fs.writeFile`. Updated the
"BkwQW" comment + the inner catch-block comment to clarify that
new files actually get the `0o600` default applied at writeFile
time (NOT umask defaults — the explicit `mode` arg bypasses umask
for atomicity per the `Blehd` comment block).
2. `bridgeFileSystem.ts` JSDoc referenced
`cli/src/serve/bridgeFileSystemAdapter.ts` as if the file exists,
but it's deferred to the immediate F1 follow-up PR. Reworded as
"the immediate follow-up PR will land a serve-side adapter" so
reviewers don't grep for a non-existent file.
3. `bridgeOptions.ts` `fileSystem` field JSDoc had the same wording
issue ("Production `qwen serve` wires this to..."). Same fix — now
says "The immediate F1 follow-up will land a serve-side adapter"
so the deferred state is obvious.
Declined from this review round:
- Copilot inline #1 (`spawnChannel.ts:155` stderr forwarder drops
empty lines): pre-existing behavior since #3889. F1 lifted verbatim
— not a regression introduced here. Out of scope for a lift PR.
- github-actions bot summary: most items are pre-existing notes
(TOCTOU residual race, SCRUBBED_CHILD_ENV_KEYS allowlist concern,
sliceLineRange benchmark threshold) on code the F1 lift moved
verbatim. One ("httpAcpBridge.ts still has ~3700 LOC") is a false
positive — the file is 97 LOC after F1. Others are cosmetic
refactors (extract FIXME to tracking issue, ARCHITECTURE_DECISIONS
doc system, deprecation timeline) that aren't worth churning the
lift PR over.
- 44/44 acp-bridge tests pass
- typecheck clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): tighten BridgeFileSystem contract + re-export type from shim
Self-review + code-reviewer agent fold-in, two changes:
1. `cli/src/serve/httpAcpBridge.ts` shim now re-exports
`BridgeFileSystem` from `@qwen-code/acp-bridge/bridgeFileSystem`
so the immediate F1 follow-up adapter (in `cli/src/serve/`)
can import it via the established `./httpAcpBridge.js` path
like every other daemon-side bridge import does. Without this
the adapter would need to deep-import from acp-bridge while
every other serve file goes through the shim — inconsistent.
2. `BridgeFileSystem.readText` + `writeText` JSDoc now spells out
the two defensive gates the inline proxy carried (non-regular-
file rejection + 100 MiB buffered-size cap for reads;
write-then-rename atomicity + dangling-symlink walk-through +
mode preservation + `0o600` new-file default for writes). When
a `BridgeFileSystem` is injected, the inline path is FULLY
bypassed — without the contract spelled out, a future adapter
author could silently drop the `/dev/zero` / 500 MB log RSS
defenses the inline path established.
Note on F1 CI: this PR targets `daemon_mode_b_main` but the
`.github/workflows/ci.yml` `pull_request` trigger is scoped to
`branches: main / release/**`, so the main CI workflow (Lint /
Test on Linux/macOS/Windows / CodeQL) does NOT run on this PR.
This is a by-design side effect of the new feature-cohesive
branching strategy — `daemon_mode_b_main → main` periodic merges
will trigger the full CI matrix, providing safety net coverage
before any F-series work lands on `main`. Locally verified:
- 174/174 cli httpAcpBridge tests pass
- 44/44 acp-bridge tests pass
- 735/735 cli serve tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(acp-bridge): cover BridgeFileSystem injection seam + extract shared writeStderrLine (#4319 wenshao review)
Folds in wenshao review on #4319:
1. **[Critical]** zero test coverage for the F1 step 5 `BridgeFileSystem`
delegation branches in `BridgeClient.writeTextFile` /
`BridgeClient.readTextFile` and the factory's
`opts.fileSystem` → constructor positional-arg forwarding.
New `packages/acp-bridge/src/bridgeClient.test.ts` adds 6 tests
covering:
- writeTextFile delegates to injected fileSystem.writeText (inline
proxy fully bypassed; `fakeFs.writeText` called with the original
params; `readText` mock not invoked)
- writeTextFile invalid-path call succeeds purely via the mock
when fileSystem is injected (proof that the inline `fs.realpath`
path doesn't run)
- readTextFile delegates to injected fileSystem.readText
- readTextFile propagates injection errors to the caller
- inline-fallback regression guard: write actually hits disk via
the inline proxy when fileSystem is omitted (real tmp file
round-trip)
- same for read
Why these matter: the 7-arg `BridgeClient` constructor places
`fileSystem` at the tail as optional. A reordering — or dropping
the arg from `bridge.ts` factory's `new BridgeClient(..., opts.fileSystem)`
call — would silently bypass the adapter in production and the
inline `fs.writeFile` raw-path would run with no audit / trust /
TOCTOU coverage. The delegation tests would catch that because
the mock fileSystem would never be invoked.
2. **[Suggestion]** `writeStderrLine` was defined identically in
`bridge.ts:117` and `bridgeClient.ts:30` (22 call sites across the
two files). Both consumers live in the SAME `@qwen-code/acp-bridge`
package, so the original "no reverse-dep on cli" justification
doesn't apply within the package. Extracted to
`packages/acp-bridge/src/internal/stderrLine.ts` — a single source
of truth that future behavior changes (timestamp prefix, log
level, structured field) can edit once. `internal/` subpath is
intentionally not in `package.json`'s `exports`, keeping the
helper package-private. `spawnChannel.ts` deliberately does NOT
consume it (its stderr writes use `process.stderr.write(prefix +
line + '\n')` directly because each line carries its own
`[serve pid=… cwd=…]` line prefix).
- 6/6 new BridgeFileSystem-seam tests pass
- 50/50 acp-bridge total (44 existing + 6 new)
- 174/174 cli httpAcpBridge tests pass (no regression from refactor)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(acp-bridge): cover defaultSpawnChannelFactory env scrubbing + fix bridge.ts comment refs (#4319 wenshao round 2)
Folds in wenshao review on #4319 round 2 — 1 Critical + 2 Suggestions:
1. **[Critical] spawnChannel.ts has 0 unit tests, security-critical
paths untested.** Now that `defaultSpawnChannelFactory` is a public
export of `@qwen-code/acp-bridge`, channels + IDE consumers can't
rely on cli-package integration tests for env-scrubbing guarantees.
Refactored the inline env-scrubbing logic into a pure exported
helper `scrubChildEnv(source, scrubbed, overrides)`. Behavior is
byte-identical to the pre-extraction inline implementation; the
factory body now reads:
const childEnv = scrubChildEnv(
process.env, SCRUBBED_CHILD_ENV_KEYS, childEnvOverrides);
Added `packages/acp-bridge/src/spawnChannel.test.ts` with 12 tests
covering:
- shallow-clone (no aliasing into live process.env)
- QWEN_SERVER_TOKEN stripping
- non-scrubbed vars pass through
- override-add a new key
- override-replace an existing key
- override with undefined deletes the key (PR 14 fix#4247 wenshao R5)
- override CANNOT re-introduce a scrubbed key (defense in depth)
- override CANNOT undo the scrub by setting undefined for a scrubbed key
- override-apply-after-scrub ordering invariant
- empty overrides equals no overrides
- multi-key scrub for forward-compat (the WARNING comment on
SCRUBBED_CHILD_ENV_KEYS anticipates a future sandboxed-agent
mode expanding the denylist; this verifies the loop already
handles that)
The killChild SIGTERM→SIGKILL escalation + STDERR_LINE_CAP_CHARS
truncation are NOT covered yet — they require either real child
processes or extensive node:child_process mocking; both are
orthogonal to the env-scrubbing security guarantees wenshao
explicitly called out, and can land as a follow-up if anyone
wants the full surface tested.
2. **[Suggestion] bridge.ts comments referenced a "consolidated re-
export block earlier in this file" that doesn't exist in acp-bridge
(only in the cli shim).** Fixed both occurrences (~line 292, ~line
310) to point at the actual local import + the package barrel
re-export.
3. **[Suggestion] bridge.ts canonicalizeWorkspace re-export comment
referenced `./fs/paths.ts`.** Updated to mention the full lift
chain: extracted to `cli/src/serve/fs/paths.ts` in PR 18, then
lifted here to `./workspacePaths.ts` in PR 22b/1.
- 12/12 new spawn env-scrub tests pass
- 62/62 acp-bridge total (50 existing + 12 new spawn)
- 174/174 cli httpAcpBridge tests still pass (the factory's inline
env-scrubbing refactor preserves byte-identical behavior)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): fix 14-arg→7-arg typo in test docstring + simplify canonicalizeWorkspace re-export doc (#4319 wenshao round 3)
Folds in 2 of 3 wenshao Suggestions from #4319 round 3:
1. `bridgeClient.test.ts:20` JSDoc said "the 14-arg constructor's
positional slot" — typo I introduced when writing the test in
`fbc92bccf`. The same docstring correctly says "the constructor
takes 7 positional args" at line 25. Updated to "7-arg".
2. `bridge.ts:3461` `canonicalizeWorkspace` re-export JSDoc no longer
references the historical `cli/src/serve/fs/paths.ts` location.
Reads cleaner as a present-tense pointer to `./workspacePaths.ts`
(where the implementation actually lives now post-PR 22b/1).
Git history covers the lift chain; the docstring should describe
current state.
DECLINED + tracked separately:
- **[Critical]** `closeSession` + `killSession` use module-scoped
`channelInfo` instead of `channelInfoForEntry(entry)` — channel-
overlap edge case can kill the wrong channel. Wenshao explicitly
notes "pre-existing bug preserved by the lift" — F1's mechanical-
lift scope shouldn't carry behavior fixes, and the fix needs a
channel-overlap regression test to land safely. Tracked as #4325.
- 62/62 acp-bridge tests pass (no regression from doc tweaks)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): polish from second-pass self-review (cross-platform test + package metadata + dead tombstones)
Five small adoptions from a second-pass code-reviewer agent review on
F1 (no new external comments — pre-emptive cleanup before reviewer
returns):
1. **`bridge.ts:290-313`** — deleted two standalone "InvalidPermission
OptionError / WorkspaceInit* / McpServer* lifted to bridgeErrors"
tombstone comments. Pre-22b they were load-bearing (explained why
the class wasn't `class`-defined inline at that file location).
Post-F1 the symbols are imported at the top of the file and the
comments sit between unrelated code (`writeServeDebugLine` /
`MAX_DISPLAY_NAME_LENGTH` / `DEFAULT_INIT_TIMEOUT_MS`) with no
anchor. Dead doc — removed.
2. **`README.md`** — `spawnChannel` entry now lists `scrubChildEnv`
alongside `defaultSpawnChannelFactory` + `killChild` +
`SCRUBBED_CHILD_ENV_KEYS`. Channels / VSCode IDE consume the
package barrel so the helper should be visible in the inventory.
3. **`package.json:description`** — refreshed from the PR 22a wording
("EventBus, AcpChannel, in-memory channel, PermissionMediator
interface") to include F1 additions (`createHttpAcpBridge` /
`BridgeClient` / `defaultSpawnChannelFactory` / `BridgeFileSystem`).
Visible on `npm view`-style tooling + IDE hover so worth keeping
current.
4. **`bridgeClient.test.ts:92-115`** — swapped `/proc/no-such-file`
for `/this/dir/never/exists/file.txt` and reworded the comment.
`/proc/` is Linux-only; on macOS / Windows the inline proxy's
dangling-symlink fallback would write through to a path under
root rather than failing. Test passed regardless (mock assertion,
not real disk) but the comment overstated portability.
5. **`spawnChannel.test.ts:36`** — added a comment block explaining
why the test deliberately hand-rolls the SCRUBBED set instead of
importing the production `SCRUBBED_CHILD_ENV_KEYS`. The
decoupling is intentional (pure-function parameterized test +
forward-guard for future denylist expansion) but a naive reader
would think it's an oversight.
- 62/62 acp-bridge tests pass
- 174/174 cli httpAcpBridge.test.ts pass
- typecheck + eslint + pre-commit hooks clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(acp-bridge): bridge.ts security fold-in from #4297 review (3 issues)
Folds 3 unresolved review comments from the post-merge thread on #4297
(wenshao via qwen-latest agent) into F1 (#4319). All 3 touch
`acp-bridge/src/bridge.ts` — the same file F1 already moves the lifted
factory into — so consolidating here saves opening a separate
follow-up PR and keeps the security narrative in one reviewable
commit. The 2 cross-package fixes (`core/src/memory/const.ts` test
gap + `cli/src/serve/runQwenServe.ts` malformed-context fallback)
will land as their own small PRs after F1 merges.
#### Fix 1 (wenshao Critical, #4297 thread): `fs.unlink(target)`
arbitrary-file-deletion primitive in `verifyParentWithinWorkspace`
'create'-cleanup
After `fs.open(target, 'wx')` creates the empty file at the real
parent, an attacker with local workspace write access can swap the
parent directory for a symlink (`docs/` → `/etc`). The cleanup's
`fs.unlink(target)` re-resolves the TEXTUAL path through the
attacker's freshly-planted parent symlink, deleting whatever file
exists at the external location.
Fix: drop the `fs.unlink(target)` line. The 0-byte file at the
pre-race location is harmless (0 bytes, inside the workspace we'd
already verified) — leaving it over deleting an arbitrary external
file is the right safety trade. Comment block explains the
reasoning so future maintainers don't re-introduce the unlink.
#### Fix 2 (wenshao Critical): `O_TRUNC` arbitrary-file-truncation
primitive in workspace-init 'overwrite' branch
`O_TRUNC` causes the kernel to truncate the file to zero bytes AT
`open(2)` SYSCALL TIME — strictly before `verifyParentWithinWorkspace`
runs. A parent-symlink TOCTOU race between
`canonicalizeExistingAncestor` and this `open()` zeros the file at
the attacker-redirected location (arbitrary-file-truncation
primitive against any file the daemon UID can open). The pre-fix
code's own comment on `verifyParentWithinWorkspace` acknowledged
this as "Acceptable residual posture for the Stage-1 trust model";
wenshao pushed back that arbitrary-file-zeroing exceeds the
Stage-1 trust budget.
Fix: drop `O_TRUNC` from the open flags. Truncation moves to AFTER
`verifyParentWithinWorkspace` succeeds, via `fh.truncate(0)` on the
fd we already hold. fd-based truncate does NOT re-resolve the path
— an attacker swapping the parent symlink after we open can't
redirect the truncation.
#### Fix 3 (wenshao Suggestion): `canonicalizeExistingAncestor`
missing `ELOOP` catch
Circular symlinks in the parent path (`a -> b`, `b -> a`) cause
`fs.realpath` to fail with `ELOOP`. Without catching it, the error
propagates as an unstructured HTTP 500 instead of the typed
`WorkspaceInitSymlinkError` (HTTP 400) the route handler expects
from the workspace-init race-detection family.
Fix: add `'ELOOP'` to the caught error codes alongside `'ENOENT'`
and `'ENOTDIR'`. Walking up the parent chain when ELOOP hits at a
sub-component preserves the existing "walk to the deepest extant
ancestor" contract — the deepest realpath-able ancestor still
dictates the canonical prefix.
#### Why no new tests in this commit
- Fix 1 is a single-line removal: any regression that re-adds the
unlink would be caught by reviewing the diff; existing 174-test
`httpAcpBridge.test.ts` integration suite confirms the create-path
still works (file is created + closed correctly; only the
attacker-cleanup branch changes).
- Fix 2 is a structural move (truncate from open-time to post-verify);
the existing overwrite-init integration tests confirm the
end-to-end behavior is unchanged (file ends up empty after init).
Adding a TOCTOU race regression test requires controlled
filesystem-race simulation that exceeds reasonable test infra
scope for this PR.
- Fix 3 is a one-word addition to an error code list; the
`canonicalizeExistingAncestor` helper is module-private and the
integration test for circular-symlink → typed 400 would require
exporting it OR setting up a real circular-symlink workspace.
Both routes widen scope beyond the security fix itself; the
high-level behavior is verifiable by the existing route-error-
mapping test pattern + diff review.
A follow-up PR can add the integration tests once the security fix
itself has shipped; the immediate priority is closing the
arbitrary-file-deletion + arbitrary-file-truncation primitives.
- 62/62 acp-bridge tests pass
- 174/174 cli httpAcpBridge.test.ts pass
- typecheck + eslint clean
#### Refs
- Original review on #4297 (wenshao via qwen-latest agent), post-
merge, currently unresolvable on #4297 itself because that PR is
already MERGED.
- Other 2 #4297 review threads (`const.ts` test coverage,
`runQwenServe.ts` malformed-context observability) target files
outside F1's scope and will land as separate follow-up PRs.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: post-merge Codex P2 fold-in — MCP restart disabled-tools normalization + SDK timeout headroom (#4319)
Folds in 2 P2 findings from a Codex review run on `git diff main...HEAD`
of F1 PR #4319. Both are pre-existing in code merged into
`daemon_mode_b_main` before F1 was created (#4282 PR 17), but they're
tiny tactical fixes (~25 LOC + 1 LOC) on the same integration branch
the same reviewer (wenshao) already engages with, so folding into F1
saves an extra follow-up PR cycle.
#### Fix 1: normalize disabled tool names during MCP restart refresh
`packages/cli/src/acp-integration/acpAgent.ts:1563-1566`
The bootstrap path in `cli/src/config/config.ts:1426-1434` applies a
4-step normalization to `tools.disabled`:
1. typeof string filter
2. .trim()
3. drop empty after trim
4. dedupe via Set
The MCP-restart refresh path only did step 1, then stored the raw
strings. `ToolRegistry` checks disabled tools with EXACT
`Set.has(tool.name)`, so a tool disabled at boot as `' Foo '` (or
`'Foo\n'`) is no longer matched after `restartMcpServer` and gets
silently re-registered. This contradicts the documented "toggle +
restart" workflow that #4282 PR 17 advertised.
Fix: mirror the bootstrap normalization verbatim before
`setDisabledTools`. Adds 6 lines + a 7-line comment pointing at the
bootstrap reference for future maintainers.
#### Fix 2: add headroom to MCP restart SDK timeout
`packages/sdk-typescript/src/daemon/DaemonClient.ts:102`
The SDK's `MCP_RESTART_DEFAULT_TIMEOUT_MS` was EXACTLY 300_000ms, the
same ceiling the daemon's own `MCP_RESTART_TIMEOUT_MS` uses for the
upper bound on a single MCP rediscovery. For restarts that finish
(or fail with a typed `McpServerRestartFailedError` JSON envelope)
near 300s, the client `AbortSignal` could fire BEFORE the daemon had
finished serializing + transmitting the response, yielding a client
`TimeoutError` even though the daemon was still within its own
budget.
Fix: bump to 330_000ms (10% / 30s headroom over the daemon ceiling).
Comment updated to call out the race + the rationale for the
specific headroom value. Callers needing tighter caps still pass
their own `timeoutMs` to `restartMcpServer`.
#### Why folded into F1 vs separate follow-up PRs
These are post-merge findings on `#4282 PR 17` code, not F1-introduced
regressions. Normally we'd track as separate follow-up issues (mirror
of the #4325 / `channelInfo` decline). But:
- Both fixes are TINY (~25 LOC + ~2 LOC including comment); the bridge
security fold-in commit `7bd66c6e8` set the precedent of folding in
small same-branch issues when the cost-benefit favors closing them
immediately.
- Same reviewer (wenshao via qwen-latest agent) — won't be confused
by the scope expansion; in fact the original PR 17 commenter is
also the one who'd review the follow-up issue's fix.
- Both fixes target `daemon_mode_b_main`-only paths (MCP restart route
added by PR 17 lives on the integration branch).
- Saves opening 2 trivial follow-up issues that would just sit until
someone picks them up.
#### Verification
- sdk-typescript: 424/424 tests pass (no test hardcoded the old
300_000 default — only the constant declaration itself referenced it)
- cli acp-integration: 282/282 tests pass (no test exercised the
exact whitespace-bearing disabled-tools scenario, so no test
changes were strictly required; a regression test would belong in
a separate test-coverage PR alongside the const.ts test gap from
the #4297 unresolved-comment thread)
- typecheck clean across cli + sdk-typescript
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): wenshao review round 4 — 3 Suggestion fold-ins (#4319)
1. **bridge.ts:2270 stale line refs in `publishWorkspaceEvent` JSDoc**
— comment said `permission_resolved at line 1717` (actual: line 682)
and `broadcastWorkspaceEvent closure at ~line 2127` (actual: line
1281). Line numbers drifted across the lift commits. Replaced both
with function-name refs (`in resolvePending`, `declared above in
this factory body`) that survive future edits.
2. **`ws.ts:613` opaque references in bridgeFileSystem.ts:20 +
bridgeOptions.ts:267** — no `ws.ts` file exists in the repo; the
ref came from an internal review thread on PR 18 that future
readers can't locate. Replaced with a self-contained description
("post-PR-18 follow-up thread about BridgeClient's inline fs proxy
bypassing WorkspaceFileSystem (origina…
* feat(daemon): server-pushed followup_suggestion event for the webui (#4507)
* feat(sdk): add followup_suggestion daemon event type
Schema-only addition that lets the daemon push server-generated
follow-up suggestions ("what you might want to ask next") through the
per-session SSE bus. Zero runtime effect on its own — old daemons
just don't emit the event, and this commit doesn't change any
publisher; the bridge handler + ACP-child generator land in follow-up
commits.
Adds the new event taxonomy across the three layers:
- `events.ts`: `followup_suggestion` in `DAEMON_KNOWN_EVENT_TYPE_VALUES`,
`DaemonFollowupSuggestionData` interface, `DaemonFollowupSuggestionEvent`
envelope, `DaemonAssistEvent` union (new — reserved for future assist
hints like server-side speculation), `KnownDaemonEvent` extension,
`lastFollowupSuggestion` on `DaemonSessionViewState`,
`asKnownDaemonEvent` + `reduceDaemonSessionEvent` cases, and an
`isFollowupSuggestionData` predicate rejecting empty / malformed
payloads.
- `ui/normalizer.ts` + `ui/types.ts`: maps the daemon event to a
typed `DaemonUiFollowupSuggestionEvent` (`type: 'followup.suggestion'`).
- `ui/transcript.ts` + `ui/store.ts`: stores `lastFollowupSuggestion` on
`DaemonTranscriptSidechannelState` (no chat-stream block), exposes a
`selectLastFollowupSuggestion` selector, and adds a
`clearFollowupSuggestion()` store action mirroring `clearAwaitingResync`
so adapters can invalidate the suggestion on sendPrompt without a
wire round-trip.
- `ui/terminal.ts`: adds the new variant to the exhaustive switch so the
terminal renderer stays exhaustive.
- Public surface re-exports in `daemon/index.ts`, `daemon/ui/index.ts`,
and top-level `src/index.ts`.
Tests:
- `daemonEvents.test.ts` covers schema narrowing, malformed/empty-string
rejection via `unrecognizedKnownEventCount`, and reducer overwrite
semantics.
- `daemonUi.test.ts` covers normalizer happy path + malformed fallback,
transcript sidechannel storage (no block append), the
`clearFollowupSuggestion` store action, and the terminal renderer
line.
Wire contract is additive: old SDK consumers ignore unknown
`followup_suggestion` events via `asKnownDaemonEvent → undefined`.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(acp-bridge): publish followup_suggestion from extNotification
Recognize a new ACP child→bridge notification method
`qwen/notify/session/prompt-suggestion` and translate it into a
`followup_suggestion` SSE frame on the per-session bus. Mirrors the
existing `qwen/notify/session/mcp-budget-event` precedent in the same
handler.
Differences from `mcp-budget-event`:
- No early-event buffering: the new method only fires *after* a
prompt completes, never inside `newSession`. A missing entry means
the session has already closed, in which case we drop the
suggestion silently (best-effort UX).
- The wire `data` is the same shape as the inbound `params` minus
`v`; no `kind` discriminator (the method name is the
discriminator), so the routing logic is straight-line.
Empty or malformed payloads (missing sessionId / suggestion / promptId,
non-string fields, empty suggestion) are dropped at the handler
boundary — the daemon filters rejected suggestions server-side via
`getFilterReason()` and only emits when accepted, so empty strings on
the wire are protocol garbage and not worth a debug fallback.
The frame stamps `originatorClientId` from `activePromptOriginatorClientId`
when one is set (same pattern as `mcp-budget-event`).
Tests:
- Happy path: notification arrives, SSE frame fires with full payload
and monotonic id.
- Malformed-payload drops (missing fields / empty suggestion / wrong
types) produce no SSE frame.
- Post-close notification drops silently without throwing (no early
buffering means no resurrection of dead sessions).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(daemon+webui): generate and surface followup suggestions per turn
The activating change for the daemon follow-up suggestion pipeline.
Wires together the SDK schema (Commit 1) and the bridge handler
(Commit 2) so the daemon actually generates and pushes a server-side
suggestion after every clean assistant turn, and provides the webui
hook that consumes it.
## ACP child (Session.ts)
Adds a fire-and-forget IIFE at the end of `prompt()` (after
`#executePrompt` resolves with `stopReason === 'end_turn'`) that:
- Calls the existing `generatePromptSuggestion` from core with the
curated, 40-entry-tail conversation history (same shape as the
CLI's `AppContainer.tsx` integration).
- Forwards the result through the new
`qwen/notify/session/prompt-suggestion` extNotification when a
non-empty post-filter suggestion is produced.
- Logs filter-reason suppressions via the existing
`PromptSuggestionEvent` telemetry — keeps generator analytics
observable in the same stream regardless of in-process vs daemon
execution.
Guards mirror the CLI's path: only on `end_turn`, only when
`settings.merged.ui.enableFollowupSuggestions === true`, and never in
`ApprovalMode.PLAN`. The IIFE swallows its own errors — a failed
suggestion is invisible UX, and a throw here would propagate up
through `prompt()` and break the primary response path.
A new `followupAbort: AbortController | null` field is aborted at
the top of the next `prompt()` and inside `cancelPendingPrompt()`, so
a stale suggestion never lands after the user has moved on.
Tests cover: happy path (extNotification fires with the right
payload), feature disabled (no call), PLAN mode (no call),
suppressed result logs PromptSuggestionEvent, new prompt aborts
in-flight gen, cancelPendingPrompt aborts in-flight gen. The tests
use a partial `vi.mock` of `@qwen-code/qwen-code-core` to spy on
`generatePromptSuggestion` / `logPromptSuggestion` while preserving
the rest of the core surface for existing tests.
## Webui hook (useDaemonFollowupSuggestion)
A small hook that subscribes to the SDK store's
`lastFollowupSuggestion` sidechannel and drives the existing
`useFollowupSuggestions` controller. Returns `{ followupState,
onAcceptFollowup, onDismissFollowup, clear }` ready to wire into
`<InputForm followupState={...} ... />`.
Promo `lastPushedPromptIdRef` is what prevents the effect from
re-showing a suggestion after the user dismisses it locally — without
the gate, the React effect would see the still-present store value on
the next render and replay it.
Both accept and dismiss callbacks also clear the store via
`store.clearFollowupSuggestion()`, and `clear()` is exposed for
adapters to call just before `actions.sendPrompt(...)` so the prior
turn's ghost-text disappears immediately (no wire round-trip — the
daemon does not emit a "cleared" event on prompt boundaries; clients
self-invalidate).
## Sidechannel perf tweak (transcript.ts)
`cloneTranscriptState` now shares the `lastFollowupSuggestion`
reference between snapshots (the reducer assigns a new object when
updating, never mutates in-place). Reference stability across unrelated
dispatches lets `useSyncExternalStore` subscribers skip re-renders for
events that don't touch the suggestion — without this, the hook would
re-render once per assistant text delta in a streaming turn.
## Notes
- The webui package lacks an automated test runner in this repo
(no `test` script in `package.json`, not in root `vitest.config.ts`
`projects`). The hook is exercised end-to-end via the daemon
integration but has no dedicated unit-test file in this PR; that's
separate scaffolding work.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address wenshao review — followupAbort ordering + test mock + warn log
- Move followupAbort cleanup before the hadPrompt/hadCron guard in
cancelPendingPrompt() so it runs unconditionally (fixes window where
cancel during suggestion-only state would skip cleanup)
- Change generateMock from mockImplementation to mockImplementationOnce
chain so second prompt's suggestion call doesn't hang
- Split catch log: debug for aborted, warn for real errors
* fix(daemon): R4 review — add malformed-drop logging + originatorClientId test
- bridgeClient.ts: add writeStderrLine for malformed prompt-suggestion
drops (consistency with model-update/mcp-budget handlers)
- bridge.test.ts: add originatorClientId stamping test for
followup_suggestion events (parity with model_switched test)
* fix(daemon): align demux log format + rename test after logging addition
- bridgeClient.ts: normalize log key order to session=/type=/action=/reason=
matching existing [demux] lines for grep consistency
- bridge.test.ts: drop "silently" from test name since drops are now logged
* fix(daemon): remove dead originatorClientId spread from followup_suggestion
activePromptOriginatorClientId is cleared in bridge.ts .finally() when
the prompt resolves, but followup suggestion fires after prompt
completion — the field is always undefined in production. Remove the
conditional spread and the false-confidence test.
* fix(webui): re-export useDaemonFollowupSuggestion from package entry
The hook was only exported from src/daemon/index.ts but not from the
top-level src/index.ts — consumers importing from @qwen-code/webui
could not access it. Add the hook and its return type to the public
export list.
* fix(daemon): clear stale suggestions on new prompt + skip non-model end_turn
- transcript.ts: clear lastFollowupSuggestion when a new user prompt
starts (first user.text.delta), so peer clients in shared sessions
don't render stale ghost text from the prior turn
- Session.ts: skip suggestion generation when the last history entry
is not from the model (slash commands, blocked hooks return end_turn
without a model turn — no point running a suggestion LLM call against
stale history)
* fix(daemon): move getHistory into IIFE try-catch + add suggestion length cap
- Session.ts: move chat.getHistory(true) + role check + slice inside
the async IIFE's try-catch so structuredClone failures don't
propagate through prompt()
- bridgeClient.ts: cap suggestion string at 500 chars (defense-in-depth
at the SSE trust boundary)
- daemonUi.test.ts: restore A4 disambiguation test comments removed
during rebase conflict resolution
* fix(daemon): fix test regressions from P2 guards
- Session.test.ts: seed model-role history in followup-suggestion
beforeEach so the new lastEntry.role !== 'model' guard doesn't
early-return before generatePromptSuggestion is called
- daemonUi.test.ts: use correct session_update envelope for
user_message_chunk (it's a sessionUpdate discriminator, not a
top-level event type)
* fix(daemon): add debug log for role guard + extract suggestion length constant
- Session.ts: log when role !== 'model' guard skips suggestion
generation (observability for debugging missing suggestions)
- bridgeClient.ts: extract 500 → MAX_SUGGESTION_LENGTH constant
* fix(daemon): cross-client sync follow-up cleanup (epoch-reset resync, approval-mode serialization, catch-up indicator) (#4510)
* fix(serve): post-merge fixes for #4291 review (7 threads) (#4305)
* fix(serve): address qwen-latest review on merged #4291 (7 threads)
Seven post-merge findings from the qwen-latest review on #4291,
all real. Most are tightening fixes for issues introduced by the
earlier rounds of #4291 — the same security / DRY / observability
classes the original review surfaced, applied to surfaces that
weren't covered initially.
#1 (deviceFlow.ts:1179) — late-poll observer closure retained the
entire entry by reference (deviceCode/pkceVerifier BrandedSecrets +
cancelController) for the lifetime of the daemon if `provider.poll()`
never settled. Memory leak + indefinite secret retention. Destructure
the four fields the closure actually needs (deviceFlowId, providerId,
initiatorClientId, audit sink) so the entry is GC-eligible the
moment runPollTick returns.
#2 (server.ts) — `callerIsInitiator` was duplicated verbatim across
three locations: GET handler, toDeviceFlowStartResponseBody,
toDeviceFlowStateBody. The exact bug class #4291 was fixing was
"POST and GET diverged on the same redaction policy" — duplicating
the gate recreated the preconditions for divergence. Extracted to
shared `callerIsDeviceFlowInitiator(view, callerClientId)` helper
with the consolidated threat-model JSDoc. All three sites now call
the helper.
#3 (deviceFlow.ts:1110) — timeout callback constructed two separate
`DeviceFlowPollTimeoutError` instances (one for `signal.reason`, one
for the wrapper rejection). Each capture its own V8 stack trace,
and `signal.reason.stack` would diverge from the caught rejection's
stack — confusing for operators inspecting both. Build the sentinel
ONCE per timer fire and pass the same instance to both sites.
#4 (qwenDeviceFlowProvider.ts:273) — `Error.name` is a freely
assignable string property; a hostile fetch wrapper could set
`e.name = 'X\n[serve] FAKE LINE\x1b[31m'` to inject log lines or
ANSI sequences via the same vector we already closed for `oauthError`.
The non-OAuth catch path interpolated `${err.name}` raw. Apply the
same `sanitizeForStderr()` helper.
#5 (deviceFlow.ts:1551) — on the timeout path, `rawProviderError`
is undefined (deliberately, to skip the misleading
`provider.poll() threw (raw): ...` audit template), but that left
the audit hint field omitted entirely. Operators reading the
durable audit trail saw `errorKind: 'upstream_error'` with no signal
whether it was a hung IdP or a generic provider failure. Use
`result.hint` (which already carries the timeout-specific
`provider.poll() timed out after Nms; check IdP connectivity` text
built in the catch) so the audit matches the SSE event.
#6 (server.ts) — the `QWEN_SERVE_DEBUG` env-var check was inlined
in the GET route handler, duplicating the `isServeDebugMode()`
helper from `./debugMode.js` that workspaceAgents and
workspaceMemory already use. The inline copy also had a dead `?? ''`
fallback (the value is guaranteed truthy at that point per the
preceding check). Use the canonical helper.
#7 (deviceFlow.ts:1217) — late-rejection observer interpolated the
raw `lateErr.message` into the audit hint (truncated to 256 bytes,
but RFC 8628 `device_code` values fit comfortably in 256 bytes).
The provider's catch already uses the `name + length` redaction
pattern to prevent WAF-echoed `device_code`/PKCE leaks; the
registry layer was undoing that hardening because the same failure
settled late. Apply the same `name + length` pattern at the late-
rejection site.
Tests:
- Existing late-rejection test reseeded with a `device-code-secret-*`
substring inside the long detail; hard-negative-asserts the seeded
secret is absent from the audit + asserts the new
`Error (message N bytes; raw suppressed)` shape.
- Existing poll-timeout test now also asserts: hint IS defined on
the audit (not omitted), hint contains `'timed out after'` /
`'check IdP connectivity'`, and `signal.reason instanceof
DeviceFlowPollTimeoutError` (proves the single sentinel is
shared between abort and reject).
- New `sanitizes control characters in attacker-controlled
err.name` test in qwenDeviceFlowProvider.test.ts pins the round-4
#4 fix with a hostile `e.name` containing `\n` + `\x1b[31m...`.
cli serve 702/702 (was 686, +16 — additional tests imported via
the acp-bridge package lift on main); sdk 421/421; typecheck clean
across all 4 workspaces; eslint --max-warnings 0 clean on touched
files.
Refs: #4175, #4255, #4291🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address deepseek-v4-pro review on #4305 (4 threads)
Round-5 fold-in. Four findings from the deepseek-v4-pro review on
PR #4305 — all real, three are sister fixes for the same security
classes that #4305 already closed at adjacent surfaces.
#1 (deviceFlow.ts) — `pollTimedOut` race correctness. The flag was
set unconditionally inside the timer callback. If the provider
settled the wrapper at 29.9s, `finally` would call
`clearScheduled(pollTimer)` — but if the timer callback was already
queued for execution before the clear landed (a real possibility
in Node's event-loop ordering, even if not always observed in
practice), this branch could still run and incorrectly mark
`pollTimedOut`. Move the flag assignment to the catch block where
the settled cause is unambiguous via `instanceof
DeviceFlowPollTimeoutError`. New test pins the negative: provider
beats the timeout → no spurious `lost_late_poll_after_timeout`
audit even after ticking 2× the ceiling.
#2 (deviceFlow.ts) — late-rejection observer interpolated raw
`lateErr.name` into the audit hint without sanitization. Same
attacker-controlled vector closed at the provider layer for
`err.name` in round-4. Route through `sanitizeForStderr`.
#3 (deviceFlow.ts) — late-success observer interpolated
`latePollResult.kind` directly into the audit template. While the
typed shape is `'pending' | 'slow_down' | 'success' | 'error'`, a
non-conforming provider could return an arbitrary string. Same
log-injection vector. Route through `sanitizeForStderr`.
#4 (qwenDeviceFlowProvider.ts → deviceFlow.ts) —
`sanitizeForStderr` only stripped ASCII C0/C1 + DEL; bypass via
Unicode lookalikes:
- U+2028/U+2029: LINE/PARAGRAPH SEPARATOR (newline-equivalent in
most Unicode-aware terminals — most direct log-forging vector)
- U+200B–U+200F: zero-width chars + LRM/RLM
- U+202A–U+202E: bidirectional override controls
- U+FEFF: BOM / ZWNBSP
A malicious IdP returning `slow_down [serve] FAKE` in
`oauthError` would otherwise still forge log lines.
Architectural change: `sanitizeForStderr` was previously private to
`qwenDeviceFlowProvider.ts`. To address #2/#3, the registry layer
needs to call it too. Lifted into `deviceFlow.ts` (the foundation
module) and re-imported from the provider. Single source of truth;
the regex is now a module-level constant compiled once with explicit
`\uXXXX` escapes (via `String.raw` so the source is greppable, not
literal-Unicode-laden).
Tests:
- `does NOT attach late-poll observer when the provider beats the
timeout` — N1 race regression
- `sanitizes hostile latePollResult.kind in late-observer audit` — N3
- `sanitizes hostile lateErr.name in late-rejection observer audit` — N2
- `sanitizes Unicode lookalike controls (U+2028 LINE SEPARATOR,
bidi, ZWNBSP) in oauthError` — N4
cli serve 706/706 (was 702, +4 — all new round-5 tests); sdk
421/421; typecheck clean; eslint --max-warnings 0 clean on touched
files.
Refs: #4175, #4255, #4291, #4305🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address gpt-5.5 + qwen-latest review on #4305 round-5 (5 threads)
Round-6 fold-in. Five findings split between maintainability,
security hardening, and a real defensive bug.
#1 (qwenDeviceFlowProvider.test.ts) — gpt-5.5: round-5 #4 test
embedded U+2028 / U+200E / U+FEFF as literal characters in source.
Invisible in GitHub diffs / most editors; the negative
`not.toContain('')` looked like an empty-string check. Rewrote
the payload + assertions to use named `\uXXXX`-bound constants.
Also added a companion test exercising U+2066–U+2069 (round-6 #5
below).
#2 (deviceFlow.ts) — qwen-latest: the late-poll observer's
`void tracked.then(...)` was missing a terminal `.catch(() => {})`.
A synchronous throw inside either handler (e.g., a misbehaving
`audit.record`: backpressure, malformed payload, sink out-of-disk)
would reject the derived promise unhandled. On Node 22's default
`--unhandled-rejections=throw`, that crashes the daemon. Added the
terminal `.catch(() => {})` matching the persist-tracker pattern.
New test injects a poison audit sink that throws specifically on
the `lost_late_poll_after_timeout` call; asserts `flushAsync()`
resolves cleanly.
#3 (deviceFlow.ts) — qwen-latest: the `case 'error'` audit-record
hint interpolated `rawProviderError` (raw `err.message`) without
`sanitizeForStderr`. Per ES2019+ `JSON.stringify` no longer escapes
U+2028/U+2029 — those would still forge log lines downstream
through file/stdout audit sinks. Apply the same sanitizer used on
every other provider-controlled audit path. New test pins a hostile
provider message containing U+2028 + ANSI escape and asserts
neither survives.
#4 (deviceFlow.ts) — qwen-latest: the round-5 #1 comment claimed
"`DeviceFlowPollTimeoutError` isn't exported as a public DeviceFlow
contract", but it IS `export class` (the test file constructs it
directly for fixtures). With `pollTimedOut = true` keyed solely on
`instanceof`, a future provider that imports + throws the class
would spoof the registry's "I caused the timeout" signal —
attaching a phantom late-poll observer.
Fix: introduce a runtime brand `_isRegistryTimeout: boolean` on the
class (default `false`) plus an internal-only
`makeRegistryPollTimeoutError(ms)` helper that sets the brand to
`true`. The brand is set ONLY at the registry's race-timer
construction site. Both gates updated:
- `if (err instanceof X && err._isRegistryTimeout === true)` in
the catch (for `pollTimedOut`)
- `if (lateErr instanceof X && lateErr._isRegistryTimeout === true)`
in the late-rejection self-filter
A provider-thrown brand-false instance now flows through the
generic provider-throw audit path — correctly auditing the misuse
rather than silently swallowing it. Repurposed the original "no
double-audit when registry's own DeviceFlowPollTimeoutError is
late-rejected" test (which was actually exercising the brand-false
path) into the inverted assertion: brand-false provider throw IS
audited as a real failure. Removed the orphaned old assertion; the
brand-true happy path is implicitly covered by the hanging-provider
test (which exercises the registry-built timeout end-to-end).
#5 (deviceFlow.ts) — qwen-latest: `sanitizeForStderr` regex covered
U+202A–U+202E (bidi embedding/override) but missed U+2066–U+2069
(LRI/RLI/FSI/PDI). These are the primary CVE-2021-42574
("Trojan Source") attack vectors — a hostile IdP swapping U+2066
for U+202D achieves the same visual reordering and would have
bypassed the round-5 filter entirely. Extended the regex range and
JSDoc; new test exercises U+2066/U+2068/U+2069 in `oauthError` and
asserts none survive while substantive ASCII parts remain.
cli serve 713/713 (was 710, +3 round-6 tests + the round-5 #4
rewrite + the round-6 #5 companion); typecheck clean across all 4
workspaces; eslint --max-warnings 0 clean on touched files.
Refs: #4175, #4255, #4291, #4305🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): replace literal U+2028 with explicit escape in round-6 #3 test
PR #4312 review (Copilot): the round-6 #3 test (sanitizes
rawProviderError) regressed back to embedding a literal U+2028
character in source via `const U_2028 = ' '`. That's the same
maintainability anti-pattern round-6 #1 was fixing in the sister
test. Internal-consistency fix: switch to the explicit ` `
escape so the constant is greppable and reviewable in GitHub diffs.
Refs: #4291, #4305, #4312🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): post-merge P2 corrections from Codex review on #4282 (#4297)
* fix(serve): post-merge P2 corrections from Codex review on #4282
Follow-up to PR #4282 (Wave 4 PR 17) addressing four P2 issues
flagged by Codex's `/review` after the squash-merge to main:
P2-1 — Read the workspace context filename for init
`qwen serve` parent never goes through `loadCliConfig`, so the
process-global `getCurrentGeminiMdFilename()` stays on the default
`QWEN.md` even when the workspace configures
`context.fileName: 'AGENTS.md'`. `runQwenServe` now snapshots the
workspace's merged setting at boot and forwards via
`BridgeOptions.contextFilename`, so init writes the same file the
ACP child reads.
P2-2 — Restart MCP servers with a fresh disabledTools snapshot
`Config.disabledTools` was frozen at construction time;
`setWorkspaceToolEnabled` only updated settings.json. The
documented "toggle + restart" workflow re-registered just-disabled
tools because rediscovery still saw the bootstrap snapshot. Added
`Config.setDisabledTools()` plus a re-read at the ACP restart
handler so `discoverMcpToolsForServer` honors the latest set.
P2-3 — Match the SDK timeout to the daemon's restart budget
Bridge waits up to 300s for stdio MCP discovery; SDK helper used
the client-wide 30s default and aborted valid slow restarts.
Added a per-call `timeoutMs` plumbed through `fetchWithTimeout`,
defaulting `restartMcpServer` to 5 minutes.
P2-4 — Reject symlinked parent directories before init writes
`lstat(target)` only checked the final component; a symlinked
parent (e.g. `docs -> /tmp` with `context.fileName:
'docs/QWEN.md'`) would let `writeFile` follow the link and create
/ truncate outside `boundWorkspace`. Added
`canonicalizeExistingAncestor` (walks up through ENOENT to the
deepest extant ancestor, then `realpath`s) and verifies the
canonical parent stays within the canonical workspace.
5 new tests (4 bridge / 2 SDK):
- contextFilename snapshot honored
- parent-symlink escape rejected
- nested real subdir accepted
- restartMcpServer survives 1.2s response with 1s default timeout
- restartMcpServer honors a 50ms caller override
Typecheck clean across cli / sdk-typescript / core.
1604/1604 unit tests pass.
* fix(serve): fold-in 1 — address 16:32:44-round review on #4282
Follow-up addressing the 8 unresolved review threads opened on PR
shipping in this same #4297; addresses correctness gaps + missing
test coverage that would otherwise let regressions ride into main.
Behavior fix:
- broadcastWorkspaceEvent gains a `skipSessionId` parameter; when
`setSessionApprovalMode` runs with `persist:true`, the broadcast
skips the requesting session so it doesn't receive the same
`approval_mode_changed` event twice (once via session-scoped
publish + once via broadcast). The SDK reducer's
`approvalModeChangedCount` now increments by 1, not 2, on the
requesting client (peers still see 1 via the broadcast).
Addresses #3260501134.
Observability + posture:
- broadcastWorkspaceEvent now mirrors PR 16's publishWorkspaceEvent
member: per-entry success/failure accounting + an "ALL buses
dropped" stderr elevation. The previous local helper silently
swallowed every publish failure. Addresses #3260501126.
- WorkspaceInitPathEscapeError + WorkspaceInitSymlinkError typed
classes for the two boundary guards in initWorkspace, mapped to
HTTP 400 by sendBridgeError. Previous generic `Error` fell
through to the 500 handler, telling operators "daemon broken"
when the actual fix was workspace-config correction. Addresses
#3260501161.
Public surface symmetry:
- Re-export McpServerNotFoundError, McpServerRestartFailedError,
WorkspaceInitPathEscapeError, WorkspaceInitSymlinkError from the
serve barrel. External embeds matching these via `instanceof`
no longer need deep imports. Addresses #3260501163.
Test coverage:
- restartMcpServer bridge tests (5): success + event broadcast,
soft-skip + refused event, McpServerNotFoundError translation,
McpServerRestartFailedError translation, originator clientId
stamping. Addresses #3260501141.
- sendBridgeError mapping tests (4): McpServerNotFoundError → 404,
McpServerRestartFailedError → 502, WorkspaceInitPathEscapeError
→ 400, WorkspaceInitSymlinkError → 400. Addresses #3260501148.
- initWorkspace boundary guard tests (2 added): symlink-at-target
rejected, contextFilename '../outside.md' rejected. Addresses
#3260501157.
- TrustGateError tests assert the typed class via `.toThrow(TrustGateError)`,
not just message text. Addresses #3260501165.
Also updates the existing fold-in 4 S2 broadcast test to reflect
the new no-duplicate semantics on the requesting session.
Typecheck clean across cli / sdk-typescript / core.
1615/1615 unit tests pass.
* fix(serve): fold-in 2 — copilot + wenshao review on #4297
Round-2 reviewer adoption on the same PR:
Critical fixes:
- `restartMcpServer` JSDoc documents `timeoutMs: 0` as "disable the
timeout entirely", but the `> 0` guard in `fetchWithTimeout`
rejected `0` and silently fell back to the 30s client default.
Loosened the guard to `>= 0` so `0` flows through to the
no-timeout branch via the existing truthiness check; NaN /
negative inputs still coerce to the client default. Addresses
duplicate reports from copilot (#3260577538) and wenshao
(#3260661833).
- TS2322 in the slow-fetch test stub: `resolveResponse` was typed
against `import('undici-types').Response` but assigned a
`(v: Response) => void`. Re-typed against the global `Response`
throughout. Caught only by tsc runs that include the test
files. Addresses #3260663072.
Test fidelity:
- Slow-fetch stub now observes `init.signal` and rejects on abort,
so a regression that drops the per-call `timeoutMs` override
will reliably fail the test instead of resolving after the
timer fired (false-negative coverage). Addresses #3260577600.
- New test pinning the `timeoutMs: 0` semantics: 1ms client
default + a stub that resolves after 50ms. Without the `>= 0`
fix, the call would abort at 1ms; with it, the explicit
`0` disables the timer and the call completes.
Bug fixes:
- `runQwenServe.contextFilenameForInit` previously called
`String(arr[0])` on the array branch, producing a literal
`"[object Object]"` filename for hand-edited bad data. Now
validates each element with `typeof === 'string'` and falls
back to `undefined` (so the bridge uses its
`getCurrentGeminiMdFilename()` default) when no string is
found. Addresses #3260577641.
Documentation drift:
- `Config.getDisabledTools()` JSDoc rewritten to describe the
mutable-via-`setDisabledTools()` semantics introduced by P2-2,
and the "registration-time only / no retroactive unregister"
contract that pairs with it. Old comment claimed the set was
frozen at construction. Addresses #3260577677.
Observability:
- `acpAgent` MCP-restart `loadSettings` failure now surfaces a
stderr line naming the server + the underlying error, instead
of silently swallowing it. The documented "toggle + restart"
workflow used to break with zero diagnostic when settings.json
was corrupted or unreadable. Addresses #3260663303.
Code organization:
- Moved `canonicalizeExistingAncestor` after `describeStatKind` so
the latter's JSDoc is no longer orphaned (TypeScript only
associates the last `/** ... */` block before a declaration).
Addresses #3260668618.
Typecheck clean across cli / sdk-typescript / core.
1616/1616 unit tests pass.
* fix(serve): fold-in 3 — read merged scope on MCP restart refresh
Critical bug from wenshao review (#3260725526) on PR #4297:
the P2-2 acpAgent re-read narrowed `Config.disabledTools` to
`SettingScope.Workspace` alone, dropping User / System scope
entries. The bootstrap Config received `merged.tools?.disabled`
(union of all scopes), so user-level / system-level disables
worked at boot — but the first `mcp restart` would replace the
in-memory set with the workspace scope alone, silently re-enabling
any tool that was disabled at a higher scope but absent from the
workspace file.
The asymmetry vs. the persist-write path is deliberate and
documented:
- Reads (here): merged — match the bootstrap Config snapshot,
preserve user/system policy.
- Writes (`runQwenServe.persistDisabledTools`): workspace scope —
don't bake higher-scope entries into the workspace file
(per-#4282 fold-in 1 H2 fix).
Two paths look alike but answer different questions.
Typecheck clean across cli / sdk-typescript / core.
1616/1616 unit tests pass.
* fix(test): fold-in 4 — wire timeoutMs:0 stub to init.signal
Critical follow-up from wenshao (#3260810242) on PR #4297:
the new `timeoutMs: 0` regression test (added in fold-in 2)
inherited the same flaw it was meant to prevent — the slow-fetch
stub didn't observe `init.signal`, so a regression that ignored
the `0` override would fire the AbortController at the 1ms client
default but the stub would keep the promise pending. The 50ms
`resolveResponse` would win, the test would still pass, and the
documented "0 disables timeout" contract would be unprotected.
Mirrored the listener pattern already used by the two sibling
tests in fold-in 2 — `init.signal.addEventListener('abort', () =>
reject(...))`. Now a regression that re-rejects `0` triggers the
abort, the stub rejects, the test fails.
8/8 restartMcpServer SDK tests pass; SDK typecheck clean.
* fix(serve): fold-in 5 — TOCTOU + setDisabledTools coverage
Two new critical reviews from wenshao on PR #4297:
C1 — TOCTOU between lstat and writeFile (#3260836305):
The `lstat(target)` symlink check and the subsequent `writeFile`
were two separate syscalls, leaving a race window where a local
attacker with workspace write access could substitute a symlink
between them. With `force: true`, `writeFile` would follow the
link and truncate an external target.
The `action === 'created'` path now uses `fs.open(target, 'wx')`
(O_WRONLY|O_CREAT|O_EXCL), which atomically refuses any
pre-existing inode (regular file, dir, OR symlink) at the target
path. EEXIST after the absence check most plausibly means a
race-created symlink, so we throw `WorkspaceInitSymlinkError(kind:
'target')` — same typed class the route maps to 400.
The `force: true` overwrite path retains the existing TOCTOU as a
documented limitation; closing it requires `O_NOFOLLOW`-aware open
which the post-PR18 `WorkspaceFileSystem` migration will provide.
C2 — P2-2 zero test coverage (#3260836302):
The `setDisabledTools` runtime sync was the only Wave-4 P2 fix
without a dedicated test. Added 5 Config-level tests:
- Initializes from `disabledTools` ConfigParameters
- Defaults to empty set when omitted
- `setDisabledTools` replaces the live snapshot
- Defensive copy: caller-set mutations don't leak into the live snapshot
- Accepts an empty set (clears live snapshot)
Plus a TOCTOU regression test in httpAcpBridge.test.ts that
spies fs.lstat / fs.readFile to simulate the race window:
pre-creates a symlink, makes lstat lie about it, asserts the
'wx' open catches the racing inode and throws the typed
`WorkspaceInitSymlinkError(kind: 'target')`.
1622/1622 unit tests pass; typecheck clean across cli /
sdk-typescript / core.
* fix(serve): fold-in 6 — count actual skips in broadcast alarm
DeepSeek review on #4297 (#3261079572):
`broadcastWorkspaceEvent` unconditionally subtracted 1 from the
`eligible` recipient count whenever `skipSessionId` was set, even
when the id matched zero live sessions (caller mistake, stale id,
or the matching session was just torn down between resolution and
broadcast). In a single-session workspace that's the difference
between `eligible = 0` (alarm suppressed) and `eligible = 1`
(alarm fires when the publish failed) — silently losing the
all-dropped breadcrumb the telemetry was meant to surface.
Today's call sites pass real session ids so the bug doesn't
manifest in practice, but the defensive shape is small: track
`skippedCount` inside the loop and subtract that, so the alarm
condition is self-consistent regardless of how the caller mis-uses
the param.
162/162 bridge tests pass; CLI typecheck clean.
* fix(serve): fold-in 7 — close overwrite TOCTOU, harden boot + diagnostics
Round-7 review on PR #4297. Three critical fixes + one suggestion
test, plus a regression test for the overwrite TOCTOU close.
C1 — force:true overwrite TOCTOU (#3262615446):
The fold-in 5 fix only closed the `'created'` action via 'wx';
the `'overwrote'` branch still used plain `fs.writeFile`, so a
local writer could swap the verified regular file to a symlink
between the lstat/readFile checks and the write and have the
forced overwrite truncate an external target. Switched to
`fs.open(target, O_WRONLY | O_TRUNC | O_NOFOLLOW)` — `O_NOFOLLOW`
makes open() fail with ELOOP on a symlink at the final component
even under race. ELOOP / ENOENT (race-deleted) translate to
`WorkspaceInitSymlinkError(kind: 'target')` so the route still
maps to a structured 400 instead of a generic 500.
C2 — settings.json corrupt blocks daemon boot (#3262625091):
`loadSettings(boundWorkspace)` at boot had no try/catch — a
corrupted, malformed, or temporarily unreadable settings file
threw synchronously and prevented daemon startup. Pre-PR this
never happened because settings were read lazily inside request
handlers. Wrapped in try/catch with stderr fallback so the daemon
keeps booting (with the bridge's default context filename) when
the file is broken.
C3 — malformed `tools.disabled` clears policy silently (#3262625101):
When `merged.tools?.disabled` is present but not an array
(boolean / string / object from a hand-edited settings.json), the
ternary `Array.isArray(...) ? ... : []` substituted an empty list
without firing the surrounding catch block. After an MCP restart
every disabled tool would silently re-register. Added an explicit
`!Array.isArray && !== undefined` check that stderr-logs the
malformed type before clearing — operators see the
misconfiguration instead of a stealth re-enable.
S1 — contextFilename extraction tested (#3262690842):
Lifted the inline `firstStringInArray` + branching into an
exported `extractContextFilename(value: unknown)` helper and
added `runQwenServe.test.ts` with 5 tests covering the four
branches the suggestion called out: non-empty string, array with
strings, array with no strings, non-string non-array.
Plus a TOCTOU regression test for the overwrite path that
verifies `O_NOFOLLOW` returns `WorkspaceInitSymlinkError(kind:
'target')` when the file is race-substituted with a symlink
behind the lstat/readFile mocks.
S2 (acpAgent restart-handler integration test #3262690845) is
deferred — Config-level coverage of `setDisabledTools` already
locks the load-bearing surface (5 tests in fold-in 5), and
adding a full acpAgent integration test requires heavy ext-method
plumbing. The new C3 stderr diagnostic plus existing tests give
us the regression signal we need without that scaffolding.
1627/1627 unit tests pass; typecheck clean across cli /
sdk-typescript / core / acp-bridge.
* fix(serve): fold-in 8 — split ELOOP / ENOENT diagnostic in overwrite path
qwen-latest review on PR #4297 (#3262861754):
The fold-in 7 ELOOP/ENOENT branch shared one error message that
said "swapped to a symlink." That's accurate for ELOOP (genuine
O_NOFOLLOW rejection — likely an attack race) but misleading for
ENOENT in the overwrite path: there `readFile` just succeeded
proving the file existed, so ENOENT means the file was DELETED
between the content check and the open — a benign race with a
concurrent writer (git checkout, editor save, lockfile rename),
NOT a symlink swap. An operator seeing the symlink language for
a benign delete would `ls -la`, see no symlink, and waste time
hunting an attack that didn't happen.
Split into two messages:
- ELOOP: "swapped to a symlink between the content check and the
overwrite — refusing to follow it"
- ENOENT: "deleted between the content check and the overwrite
(likely a concurrent writer) — refusing to recreate blindly"
Both still surface as `WorkspaceInitSymlinkError(kind: 'target')`
so the route maps to a structured 400; the class doubles as the
workspace-init race-condition bucket with kind='target' meaning
"target inode misbehaved at write time" generally.
Updated the existing fold-in 7 TOCTOU test to assert the ELOOP
message specifically, and added a new ENOENT race-delete test
that mocks lstat/readFile to land on the overwrote action against
a non-existent path — verifies the message says "deleted" and
NOT "swapped to a symlink."
170/170 bridge tests pass; CLI typecheck clean.
* fix(serve): fold-in 9 — route MCP restart through registry cleanup wrapper
gpt-5.5 critical review on PR #4297 (#3263088414):
The fold-in 5 P2-2 fix refreshed `Config.disabledTools` from merged
settings, but then called `manager.discoverMcpToolsForServer()`
directly — bypassing the `ToolRegistry.discoverToolsForServer`
wrapper that PURGES the server's existing `DiscoveredMCPTool`
entries (and `revealedDeferred` markers) plus its prompts before
rediscovery. Without the cleanup, `registerTool` only consulted
the refreshed `disabledTools` set for NEWLY-discovered tools —
entries already in the registry from the prior MCP boot kept
serving requests. Net effect: toggle-disable-then-restart
silently left the disabled tool live, breaking the documented
"toggle + restart" workflow that P2-2 was meant to fix.
Routed through `toolRegistry.discoverToolsForServer(serverName)`
which:
1. Removes existing `DiscoveredMCPTool` entries for this server
2. Drops their `revealedDeferred` reveal state
3. Removes the server's prompts via `removePromptsByServer`
4. THEN delegates to `manager.discoverMcpToolsForServer` for the
actual reconnect + rediscover
The pre-discovery budget / in-flight checks still go through the
`manager` reference (which is the same object the registry
wrapper would forward to) — so soft-skip semantics for
`budget_would_exceed`, `in_flight`, `disabled` are preserved.
CLI typecheck clean; 403/403 server + bridge tests pass.
* fix(serve): fold-in 10 — qwen-latest 05:45-round review on #4297
5 review threads from qwen-latest's late round on PR #4297 (now closed
in favor of #4313 against `daemon_mode_b_main`). 1 critical + 4
suggestions, all adopted.
C1 — extractContextFilename / getCurrentGeminiMdFilename divergence
(#3263954685): with `context.fileName: [' ', 'AGENTS.md']`, the
daemon parent's `extractContextFilename` (which skips empty entries)
wrote `AGENTS.md`, but the ACP child's `getCurrentGeminiMdFilename`
(which returned `arr[0]` unconditionally) read `''`. The init'd file
was orphaned. Aligned `getCurrentGeminiMdFilename` to skip empty
entries with the same semantics, falling back to
`DEFAULT_CONTEXT_FILENAME` when all entries are empty.
S2 — WorkspaceInitSymlinkError reused for non-symlink races
(#3263954690): the EEXIST race-create and ENOENT race-delete cases
were surfacing as `code: 'workspace_init_symlink'`, misleading
operators into hunting symlink attacks for benign concurrent-
modification windows. Split into a sibling `WorkspaceInitRaceError`
class (`kind: 'eexist' | 'enoent'`, HTTP code
`workspace_init_race`). The genuine symlink class stays for ELOOP,
lstat-detected target symlinks, and parent-realpath escapes.
S3 — fsConstants.O_NOFOLLOW defensive `?? 0` (#3263954697): matches
the existing codebase convention in
`core/src/utils/{sessionStorageUtils,gitDiff}.ts` and
`cli/src/ui/utils/customBanner.ts`. Functionally a no-op (JS
bitwise coerces undefined to 0) but consistent.
S5 — Parent-directory TOCTOU still open (#3263954707): O_NOFOLLOW
only protects the final path component; a local writer could swap
a real parent dir for a symlink between
`canonicalizeExistingAncestor` and `fs.open`. Added
`verifyParentWithinWorkspace` post-open helper that re-realpaths
`path.dirname(target)` and refuses with
`WorkspaceInitSymlinkError(kind: 'parent')` if the parent moved.
On the create path (where we just opened with `'wx'`), the failure
also unlinks the file we just made best-effort. Residual race
window narrowed from "between pre-check and open" to "between
post-open realpath and writeFile" — sub-millisecond, documented as
accepted Stage-1 trust posture.
S4 — broadcastWorkspaceEvent vs publishWorkspaceEvent stale comment
(#3263954688): the "now removed" comment was inaccurate (5 call
sites still use the closure). Replaced with an accurate
description of why both coexist (factory closure can't `this`-call
proxy member; closure also takes `skipSessionId` for persisted
approval-mode mirror) and a TODO marker for future helper extraction.
Two existing tests updated to assert the new `WorkspaceInitRaceError`
class for EEXIST / ENOENT scenarios (the symlink-class assertions
are preserved for ELOOP / lstat / parent cases).
1759/1759 unit tests pass; typecheck clean across all 4 packages.
* feat(acp-bridge): F1 — acp-bridge package self-sufficiency (#4175 mechanical lift + BridgeFileSystem seam) (#4319)
* refactor(acp-bridge): lift defaultSpawnChannelFactory to acp-bridge/spawnChannel (#4175 F1 step 1)
First mechanical lift of #4175 F1 (acp-bridge package self-sufficiency).
Moves the production spawn factory + its `killChild` helper +
`SCRUBBED_CHILD_ENV_KEYS` denylist + `KILL_HARD_DEADLINE_MS` constant
from `cli/src/serve/httpAcpBridge.ts` (~283 lines) to
`@qwen-code/acp-bridge/spawnChannel`. This unblocks
`channels/base/AcpBridge.ts` and `vscode-ide-companion`'s
acpConnection from each reimplementing the child lifecycle — they can
now consume the same primitive.
Backward compatible: `cli/src/serve/httpAcpBridge.ts` imports the
lifted factory and re-exports it, so existing references in
`cli/src/serve/index.ts:90` and the factory's own internal usage
(`opts.channelFactory ?? defaultSpawnChannelFactory`) keep resolving.
Bridge tests that mock `defaultSpawnChannelFactory` via
`BridgeOptions.channelFactory` are unaffected.
Side cleanups: drops `spawn` / `ChildProcess` / `Readable` / `Writable`
/ `ndJsonStream` / `MissingCliEntryError` imports from
httpAcpBridge.ts (all only used by the lifted spawn factory).
- 44/44 acp-bridge tests pass
- 174/174 cli httpAcpBridge tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor(acp-bridge): lift BridgeClient + permission types to acp-bridge/bridgeClient (#4175 F1 step 2)
Second mechanical lift of #4175 F1 (acp-bridge package self-sufficiency).
Moves `BridgeClient` class (~700 LOC) + `PendingPermission` interface +
`PermissionResolutionRecord` interface + `MAX_RESOLVED_PERMISSION_RECORDS`
constant + early-event capacity constants + `describeStatKind` and
`sliceLineRange` helpers from `cli/src/serve/httpAcpBridge.ts` to
`@qwen-code/acp-bridge/bridgeClient`.
Design choice for SessionEntry boundary: introduce a minimal
`BridgeClientSessionEntry` interface in bridgeClient.ts with only the
four fields BridgeClient actually reads from the factory's richer
`SessionEntry` (`sessionId`, `events`, `pendingPermissionIds`,
`activePromptOriginatorClientId`). The factory's `SessionEntry`
structurally satisfies it — TypeScript's structural typing enforces
the match at the `resolveEntry` callback signature, so no explicit
conversion is required and the bridge package stays free of daemon-host
session-bookkeeping types.
Cross-package writeStderrLine handling: inline the 3-line helper in
bridgeClient.ts (mirrors the spawnChannel.ts pattern from F1 step 1)
so acp-bridge has no reverse dependency on `cli/src/utils/stdioHelpers`.
httpAcpBridge.ts shrinks from 4406 LOC to 3647 LOC (-759 lines).
Removed ACP SDK imports that only BridgeClient consumed: `Client`,
`RequestPermissionRequest`, `WriteTextFileRequest`,
`WriteTextFileResponse`, `ReadTextFileRequest`, `ReadTextFileResponse`,
`SessionNotification`. Kept the ones the factory still uses
(`CancelNotification`, `PromptRequest`, `RequestPermissionResponse`,
`SetSessionModelRequest`, `SetSessionModelResponse`).
Backward compatible: httpAcpBridge.ts re-exports `BridgeClient`,
`BridgeClientSessionEntry`, `PendingPermission`,
`PermissionResolutionRecord`, and `MAX_RESOLVED_PERMISSION_RECORDS` so
the `ChannelInfo.client: BridgeClient` field declaration below + any
embedder reaching into these types keep resolving.
- 44/44 acp-bridge tests pass
- 174/174 cli httpAcpBridge tests pass
- 229/229 cli server tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor(acp-bridge): lift createHttpAcpBridge factory to acp-bridge/bridge (#4175 F1 step 3)
Third + final mechanical lift of #4175 F1 (acp-bridge package
self-sufficiency). Moves the `createHttpAcpBridge` factory closure
(~3000 LOC) + `ChannelInfo` + `SessionEntry` interfaces + factory-only
helpers (`canonicalizeExistingAncestor`, `verifyParentWithinWorkspace`,
`withTimeout`, `isServeDebugLoggingEnabled`, `writeServeDebugLine`,
`hasControlCharacter`) + factory constants (`DEFAULT_INIT_TIMEOUT_MS`,
`MCP_RESTART_TIMEOUT_MS`, `DEFAULT_MAX_SESSIONS`, `MAX_EVENT_RING_SIZE`,
`DEFAULT_PERMISSION_TIMEOUT_MS`, `DEFAULT_MAX_PENDING_PER_SESSION`,
`MAX_DISPLAY_NAME_LENGTH`) from `cli/src/serve/httpAcpBridge.ts` to
`@qwen-code/acp-bridge/bridge`.
`cli/src/serve/httpAcpBridge.ts` shrinks from 3647 LOC to 97 LOC — a
pure re-export shim that preserves every existing relative import
path (`./httpAcpBridge.js`) so `server.ts`, `runQwenServe.ts`,
`workspaceAgents.ts`, `workspaceMemory.ts`, `index.ts`, plus the bridge
test suite, keep resolving without any call-site changes.
The new `bridge.ts` reuses what was already in acp-bridge (errors,
types, options, status helpers, channel types, event bus, workspace
paths) via local relative imports — no reverse dependency on `cli`.
`writeStderrLine` is inlined at the top of `bridge.ts` (same pattern as
`spawnChannel.ts` + `bridgeClient.ts` from F1 steps 1-2) so the
package self-contained promise holds.
Cumulative F1 impact across the 3 mechanical lift steps:
- httpAcpBridge.ts: 4682 LOC → 97 LOC (-4585 lines; the original file
was 98% bridge core, 2% backward-compat re-exports)
- 3 new files in acp-bridge: spawnChannel.ts (~270 LOC), bridgeClient.ts
(~745 LOC), bridge.ts (~3515 LOC)
- All daemon-host concerns (env snapshot, daemon preflight cells)
remain in `cli/src/serve/daemonStatusProvider.ts` and reach the
bridge through the `BridgeOptions.statusProvider` seam frozen by
PR 22b/2.
- 735/735 cli serve tests pass across 17 files
- 174/174 cli httpAcpBridge tests pass
- 44/44 acp-bridge tests pass
- typecheck clean across acp-bridge + cli
`packages/cli/src/serve/httpAcpBridge.test.ts` (~6600 LOC) is
intentionally NOT moved in this commit — it currently imports
`createHttpAcpBridge` / `defaultSpawnChannelFactory` / `BridgeClient`
via the cli shim and keeps passing without changes. Moving it to
`acp-bridge/src/bridge.test.ts` is a follow-up worth tracking
separately so the production-code lift can land + be reviewed cleanly.
The `BridgeFileSystem` injection seam (originally bundled into F1 as
the 22b' scope) is also deferred to a follow-up so the mechanical lift
stays mechanical — design + implementation of the fs injection is its
own discussion.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(acp-bridge): add BridgeFileSystem injection seam (#4175 F1 step 5, 22b' scope)
Adds the `BridgeFileSystem` injection seam originally scoped as #4175
22b'. When a `BridgeFileSystem` is wired through
`BridgeOptions.fileSystem`, `BridgeClient.readTextFile` and
`BridgeClient.writeTextFile` delegate to it instead of running their
inline `fs.realpath` / `fs.writeFile` / `fs.readFile` proxy.
This unblocks production `qwen serve` plumbing PR 18's
`WorkspaceFileSystem` (TOCTOU guards, symlink-substitution checks,
trust gate, `.gitignore`, audit hooks) into the ACP fs methods —
closing the `ws.ts:613` follow-up thread that has been tracked since
PR 18 landed. The serve-side adapter that wraps `WorkspaceFileSystem`
+ the `runQwenServe` wiring are intentionally split into the
immediate-follow-up so this PR stays focused on the seam design.
Backward compatible: `fileSystem` is optional on `BridgeOptions`.
Tests, Mode A in-process consumers, channels (`packages/channels/base/
AcpBridge.ts`), and the VSCode IDE companion all keep working
unchanged — they omit the field and `BridgeClient` falls through to
the inline proxy that has been the Stage 1 default since #3889.
API:
- `BridgeFileSystem.readText(params: ReadTextFileRequest):
Promise<ReadTextFileResponse>`
- `BridgeFileSystem.writeText(params: WriteTextFileRequest):
Promise<WriteTextFileResponse>`
The interface mirrors ACP SDK request/response types directly so the
adapter does the minimum amount of translation (`{ path, content }`
↔ `WorkspaceFileSystem`'s `ResolvedPath` brand types + options bag).
- 735/735 cli serve tests pass (inline fallback path preserved)
- 44/44 acp-bridge tests pass
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): catch README + stale source comments up to F1 lift
Self-review fold-in: post-F1 the package README still said "PR 22a"
and listed `BridgeClient` / `createHttpAcpBridge` /
`defaultSpawnChannelFactory` under "What's not here yet" — both
contradicted by this PR. Updated:
- README lift-history table now shows PR 22a / 22b/1 / 22b/2 as
merged and F1 (this PR) as the slice that closes the bridge core
+ adds `BridgeFileSystem`. F3 PR 24 row aligned to the
feature-cohesive plan.
- "What's here today" now documents `spawnChannel`, `bridgeClient`,
`bridge`, `bridgeFileSystem` modules.
- "What's not here yet" section removed (its 2 bullets are both
resolved by F1).
- Subpath import list updated to enumerate all 14 subpaths.
- Backward-compat section updated to call out the 97-line shim and
the 6 consuming files that still import via `./httpAcpBridge.js`.
Source-comment line-number drift:
- `channel.ts:12` no longer claims `defaultSpawnChannelFactory` is
"still in cli/src/serve/httpAcpBridge.ts" — points to the lifted
location.
- `permission.ts:33` + `permission.ts:45` no longer reference
`httpAcpBridge.ts:1096-1106` / `httpAcpBridge.ts:1003` (file is
now 97 lines after F1). Updated to point at the structurally-
equivalent locations inside the lifted `bridgeClient.ts`.
- `permission.ts:7` no longer says first-responder still lives in
`cli/src/serve/httpAcpBridge.ts` — points at the bridgeClient.ts
location.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): adopt 3 Copilot review comments on F1 doc accuracy
Folds in 3 of 4 Copilot inline comments from #4319 review:
1. `bridgeClient.ts` writeTextFile preserveMode comment said "fall
through to umask defaults" for new files, but the code passes
`mode: preserveMode?.mode ?? 0o600` to `fs.writeFile`. Updated the
"BkwQW" comment + the inner catch-block comment to clarify that
new files actually get the `0o600` default applied at writeFile
time (NOT umask defaults — the explicit `mode` arg bypasses umask
for atomicity per the `Blehd` comment block).
2. `bridgeFileSystem.ts` JSDoc referenced
`cli/src/serve/bridgeFileSystemAdapter.ts` as if the file exists,
but it's deferred to the immediate F1 follow-up PR. Reworded as
"the immediate follow-up PR will land a serve-side adapter" so
reviewers don't grep for a non-existent file.
3. `bridgeOptions.ts` `fileSystem` field JSDoc had the same wording
issue ("Production `qwen serve` wires this to..."). Same fix — now
says "The immediate F1 follow-up will land a serve-side adapter"
so the deferred state is obvious.
Declined from this review round:
- Copilot inline #1 (`spawnChannel.ts:155` stderr forwarder drops
empty lines): pre-existing behavior since #3889. F1 lifted verbatim
— not a regression introduced here. Out of scope for a lift PR.
- github-actions bot summary: most items are pre-existing notes
(TOCTOU residual race, SCRUBBED_CHILD_ENV_KEYS allowlist concern,
sliceLineRange benchmark threshold) on code the F1 lift moved
verbatim. One ("httpAcpBridge.ts still has ~3700 LOC") is a false
positive — the file is 97 LOC after F1. Others are cosmetic
refactors (extract FIXME to tracking issue, ARCHITECTURE_DECISIONS
doc system, deprecation timeline) that aren't worth churning the
lift PR over.
- 44/44 acp-bridge tests pass
- typecheck clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): tighten BridgeFileSystem contract + re-export type from shim
Self-review + code-reviewer agent fold-in, two changes:
1. `cli/src/serve/httpAcpBridge.ts` shim now re-exports
`BridgeFileSystem` from `@qwen-code/acp-bridge/bridgeFileSystem`
so the immediate F1 follow-up adapter (in `cli/src/serve/`)
can import it via the established `./httpAcpBridge.js` path
like every other daemon-side bridge import does. Without this
the adapter would need to deep-import from acp-bridge while
every other serve file goes through the shim — inconsistent.
2. `BridgeFileSystem.readText` + `writeText` JSDoc now spells out
the two defensive gates the inline proxy carried (non-regular-
file rejection + 100 MiB buffered-size cap for reads;
write-then-rename atomicity + dangling-symlink walk-through +
mode preservation + `0o600` new-file default for writes). When
a `BridgeFileSystem` is injected, the inline path is FULLY
bypassed — without the contract spelled out, a future adapter
author could silently drop the `/dev/zero` / 500 MB log RSS
defenses the inline path established.
Note on F1 CI: this PR targets `daemon_mode_b_main` but the
`.github/workflows/ci.yml` `pull_request` trigger is scoped to
`branches: main / release/**`, so the main CI workflow (Lint /
Test on Linux/macOS/Windows / CodeQL) does NOT run on this PR.
This is a by-design side effect of the new feature-cohesive
branching strategy — `daemon_mode_b_main → main` periodic merges
will trigger the full CI matrix, providing safety net coverage
before any F-series work lands on `main`. Locally verified:
- 174/174 cli httpAcpBridge tests pass
- 44/44 acp-bridge tests pass
- 735/735 cli serve tests pass
- typecheck clean across acp-bridge + cli
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(acp-bridge): cover BridgeFileSystem injection seam + extract shared writeStderrLine (#4319 wenshao review)
Folds in wenshao review on #4319:
1. **[Critical]** zero test coverage for the F1 step 5 `BridgeFileSystem`
delegation branches in `BridgeClient.writeTextFile` /
`BridgeClient.readTextFile` and the factory's
`opts.fileSystem` → constructor positional-arg forwarding.
New `packages/acp-bridge/src/bridgeClient.test.ts` adds 6 tests
covering:
- writeTextFile delegates to injected fileSystem.writeText (inline
proxy fully bypassed; `fakeFs.writeText` called with the original
params; `readText` mock not invoked)
- writeTextFile invalid-path call succeeds purely via the mock
when fileSystem is injected (proof that the inline `fs.realpath`
path doesn't run)
- readTextFile delegates to injected fileSystem.readText
- readTextFile propagates injection errors to the caller
- inline-fallback regression guard: write actually hits disk via
the inline proxy when fileSystem is omitted (real tmp file
round-trip)
- same for read
Why these matter: the 7-arg `BridgeClient` constructor places
`fileSystem` at the tail as optional. A reordering — or dropping
the arg from `bridge.ts` factory's `new BridgeClient(..., opts.fileSystem)`
call — would silently bypass the adapter in production and the
inline `fs.writeFile` raw-path would run with no audit / trust /
TOCTOU coverage. The delegation tests would catch that because
the mock fileSystem would never be invoked.
2. **[Suggestion]** `writeStderrLine` was defined identically in
`bridge.ts:117` and `bridgeClient.ts:30` (22 call sites across the
two files). Both consumers live in the SAME `@qwen-code/acp-bridge`
package, so the original "no reverse-dep on cli" justification
doesn't apply within the package. Extracted to
`packages/acp-bridge/src/internal/stderrLine.ts` — a single source
of truth that future behavior changes (timestamp prefix, log
level, structured field) can edit once. `internal/` subpath is
intentionally not in `package.json`'s `exports`, keeping the
helper package-private. `spawnChannel.ts` deliberately does NOT
consume it (its stderr writes use `process.stderr.write(prefix +
line + '\n')` directly because each line carries its own
`[serve pid=… cwd=…]` line prefix).
- 6/6 new BridgeFileSystem-seam tests pass
- 50/50 acp-bridge total (44 existing + 6 new)
- 174/174 cli httpAcpBridge tests pass (no regression from refactor)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(acp-bridge): cover defaultSpawnChannelFactory env scrubbing + fix bridge.ts comment refs (#4319 wenshao round 2)
Folds in wenshao review on #4319 round 2 — 1 Critical + 2 Suggestions:
1. **[Critical] spawnChannel.ts has 0 unit tests, security-critical
paths untested.** Now that `defaultSpawnChannelFactory` is a public
export of `@qwen-code/acp-bridge`, channels + IDE consumers can't
rely on cli-package integration tests for env-scrubbing guarantees.
Refactored the inline env-scrubbing logic into a pure exported
helper `scrubChildEnv(source, scrubbed, overrides)`. Behavior is
byte-identical to the pre-extraction inline implementation; the
factory body now reads:
const childEnv = scrubChildEnv(
process.env, SCRUBBED_CHILD_ENV_KEYS, childEnvOverrides);
Added `packages/acp-bridge/src/spawnChannel.test.ts` with 12 tests
covering:
- shallow-clone (no aliasing into live process.env)
- QWEN_SERVER_TOKEN stripping
- non-scrubbed vars pass through
- override-add a new key
- override-replace an existing key
- override with undefined deletes the key (PR 14 fix#4247 wenshao R5)
- override CANNOT re-introduce a scrubbed key (defense in depth)
- override CANNOT undo the scrub by setting undefined for a scrubbed key
- override-apply-after-scrub ordering invariant
- empty overrides equals no overrides
- multi-key scrub for forward-compat (the WARNING comment on
SCRUBBED_CHILD_ENV_KEYS anticipates a future sandboxed-agent
mode expanding the denylist; this verifies the loop already
handles that)
The killChild SIGTERM→SIGKILL escalation + STDERR_LINE_CAP_CHARS
truncation are NOT covered yet — they require either real child
processes or extensive node:child_process mocking; both are
orthogonal to the env-scrubbing security guarantees wenshao
explicitly called out, and can land as a follow-up if anyone
wants the full surface tested.
2. **[Suggestion] bridge.ts comments referenced a "consolidated re-
export block earlier in this file" that doesn't exist in acp-bridge
(only in the cli shim).** Fixed both occurrences (~line 292, ~line
310) to point at the actual local import + the package barrel
re-export.
3. **[Suggestion] bridge.ts canonicalizeWorkspace re-export comment
referenced `./fs/paths.ts`.** Updated to mention the full lift
chain: extracted to `cli/src/serve/fs/paths.ts` in PR 18, then
lifted here to `./workspacePaths.ts` in PR 22b/1.
- 12/12 new spawn env-scrub tests pass
- 62/62 acp-bridge total (50 existing + 12 new spawn)
- 174/174 cli httpAcpBridge tests still pass (the factory's inline
env-scrubbing refactor preserves byte-identical behavior)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): fix 14-arg→7-arg typo in test docstring + simplify canonicalizeWorkspace re-export doc (#4319 wenshao round 3)
Folds in 2 of 3 wenshao Suggestions from #4319 round 3:
1. `bridgeClient.test.ts:20` JSDoc said "the 14-arg constructor's
positional slot" — typo I introduced when writing the test in
`fbc92bccf`. The same docstring correctly says "the constructor
takes 7 positional args" at line 25. Updated to "7-arg".
2. `bridge.ts:3461` `canonicalizeWorkspace` re-export JSDoc no longer
references the historical `cli/src/serve/fs/paths.ts` location.
Reads cleaner as a present-tense pointer to `./workspacePaths.ts`
(where the implementation actually lives now post-PR 22b/1).
Git history covers the lift chain; the docstring should describe
current state.
DECLINED + tracked separately:
- **[Critical]** `closeSession` + `killSession` use module-scoped
`channelInfo` instead of `channelInfoForEntry(entry)` — channel-
overlap edge case can kill the wrong channel. Wenshao explicitly
notes "pre-existing bug preserved by the lift" — F1's mechanical-
lift scope shouldn't carry behavior fixes, and the fix needs a
channel-overlap regression test to land safely. Tracked as #4325.
- 62/62 acp-bridge tests pass (no regression from doc tweaks)
- typecheck + eslint clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): polish from second-pass self-review (cross-platform test + package metadata + dead tombstones)
Five small adoptions from a second-pass code-reviewer agent review on
F1 (no new external comments — pre-emptive cleanup before reviewer
returns):
1. **`bridge.ts:290-313`** — deleted two standalone "InvalidPermission
OptionError / WorkspaceInit* / McpServer* lifted to bridgeErrors"
tombstone comments. Pre-22b they were load-bearing (explained why
the class wasn't `class`-defined inline at that file location).
Post-F1 the symbols are imported at the top of the file and the
comments sit between unrelated code (`writeServeDebugLine` /
`MAX_DISPLAY_NAME_LENGTH` / `DEFAULT_INIT_TIMEOUT_MS`) with no
anchor. Dead doc — removed.
2. **`README.md`** — `spawnChannel` entry now lists `scrubChildEnv`
alongside `defaultSpawnChannelFactory` + `killChild` +
`SCRUBBED_CHILD_ENV_KEYS`. Channels / VSCode IDE consume the
package barrel so the helper should be visible in the inventory.
3. **`package.json:description`** — refreshed from the PR 22a wording
("EventBus, AcpChannel, in-memory channel, PermissionMediator
interface") to include F1 additions (`createHttpAcpBridge` /
`BridgeClient` / `defaultSpawnChannelFactory` / `BridgeFileSystem`).
Visible on `npm view`-style tooling + IDE hover so worth keeping
current.
4. **`bridgeClient.test.ts:92-115`** — swapped `/proc/no-such-file`
for `/this/dir/never/exists/file.txt` and reworded the comment.
`/proc/` is Linux-only; on macOS / Windows the inline proxy's
dangling-symlink fallback would write through to a path under
root rather than failing. Test passed regardless (mock assertion,
not real disk) but the comment overstated portability.
5. **`spawnChannel.test.ts:36`** — added a comment block explaining
why the test deliberately hand-rolls the SCRUBBED set instead of
importing the production `SCRUBBED_CHILD_ENV_KEYS`. The
decoupling is intentional (pure-function parameterized test +
forward-guard for future denylist expansion) but a naive reader
would think it's an oversight.
- 62/62 acp-bridge tests pass
- 174/174 cli httpAcpBridge.test.ts pass
- typecheck + eslint + pre-commit hooks clean
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(acp-bridge): bridge.ts security fold-in from #4297 review (3 issues)
Folds 3 unresolved review comments from the post-merge thread on #4297
(wenshao via qwen-latest agent) into F1 (#4319). All 3 touch
`acp-bridge/src/bridge.ts` — the same file F1 already moves the lifted
factory into — so consolidating here saves opening a separate
follow-up PR and keeps the security narrative in one reviewable
commit. The 2 cross-package fixes (`core/src/memory/const.ts` test
gap + `cli/src/serve/runQwenServe.ts` malformed-context fallback)
will land as their own small PRs after F1 merges.
#### Fix 1 (wenshao Critical, #4297 thread): `fs.unlink(target)`
arbitrary-file-deletion primitive in `verifyParentWithinWorkspace`
'create'-cleanup
After `fs.open(target, 'wx')` creates the empty file at the real
parent, an attacker with local workspace write access can swap the
parent directory for a symlink (`docs/` → `/etc`). The cleanup's
`fs.unlink(target)` re-resolves the TEXTUAL path through the
attacker's freshly-planted parent symlink, deleting whatever file
exists at the external location.
Fix: drop the `fs.unlink(target)` line. The 0-byte file at the
pre-race location is harmless (0 bytes, inside the workspace we'd
already verified) — leaving it over deleting an arbitrary external
file is the right safety trade. Comment block explains the
reasoning so future maintainers don't re-introduce the unlink.
#### Fix 2 (wenshao Critical): `O_TRUNC` arbitrary-file-truncation
primitive in workspace-init 'overwrite' branch
`O_TRUNC` causes the kernel to truncate the file to zero bytes AT
`open(2)` SYSCALL TIME — strictly before `verifyParentWithinWorkspace`
runs. A parent-symlink TOCTOU race between
`canonicalizeExistingAncestor` and this `open()` zeros the file at
the attacker-redirected location (arbitrary-file-truncation
primitive against any file the daemon UID can open). The pre-fix
code's own comment on `verifyParentWithinWorkspace` acknowledged
this as "Acceptable residual posture for the Stage-1 trust model";
wenshao pushed back that arbitrary-file-zeroing exceeds the
Stage-1 trust budget.
Fix: drop `O_TRUNC` from the open flags. Truncation moves to AFTER
`verifyParentWithinWorkspace` succeeds, via `fh.truncate(0)` on the
fd we already hold. fd-based truncate does NOT re-resolve the path
— an attacker swapping the parent symlink after we open can't
redirect the truncation.
#### Fix 3 (wenshao Suggestion): `canonicalizeExistingAncestor`
missing `ELOOP` catch
Circular symlinks in the parent path (`a -> b`, `b -> a`) cause
`fs.realpath` to fail with `ELOOP`. Without catching it, the error
propagates as an unstructured HTTP 500 instead of the typed
`WorkspaceInitSymlinkError` (HTTP 400) the route handler expects
from the workspace-init race-detection family.
Fix: add `'ELOOP'` to the caught error codes alongside `'ENOENT'`
and `'ENOTDIR'`. Walking up the parent chain when ELOOP hits at a
sub-component preserves the existing "walk to the deepest extant
ancestor" contract — the deepest realpath-able ancestor still
dictates the canonical prefix.
#### Why no new tests in this commit
- Fix 1 is a single-line removal: any regression that re-adds the
unlink would be caught by reviewing the diff; existing 174-test
`httpAcpBridge.test.ts` integration suite confirms the create-path
still works (file is created + closed correctly; only the
attacker-cleanup branch changes).
- Fix 2 is a structural move (truncate from open-time to post-verify);
the existing overwrite-init integration tests confirm the
end-to-end behavior is unchanged (file ends up empty after init).
Adding a TOCTOU race regression test requires controlled
filesystem-race simulation that exceeds reasonable test infra
scope for this PR.
- Fix 3 is a one-word addition to an error code list; the
`canonicalizeExistingAncestor` helper is module-private and the
integration test for circular-symlink → typed 400 would require
exporting it OR setting up a real circular-symlink workspace.
Both routes widen scope beyond the security fix itself; the
high-level behavior is verifiable by the existing route-error-
mapping test pattern + diff review.
A follow-up PR can add the integration tests once the security fix
itself has shipped; the immediate priority is closing the
arbitrary-file-deletion + arbitrary-file-truncation primitives.
- 62/62 acp-bridge tests pass
- 174/174 cli httpAcpBridge.test.ts pass
- typecheck + eslint clean
#### Refs
- Original review on #4297 (wenshao via qwen-latest agent), post-
merge, currently unresolvable on #4297 itself because that PR is
already MERGED.
- Other 2 #4297 review threads (`const.ts` test coverage,
`runQwenServe.ts` malformed-context observability) target files
outside F1's scope and will land as separate follow-up PRs.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: post-merge Codex P2 fold-in — MCP restart disabled-tools normalization + SDK timeout headroom (#4319)
Folds in 2 P2 findings from a Codex review run on `git diff main...HEAD`
of F1 PR #4319. Both are pre-existing in code merged into
`daemon_mode_b_main` before F1 was created (#4282 PR 17), but they're
tiny tactical fixes (~25 LOC + 1 LOC) on the same integration branch
the same reviewer (wenshao) already engages with, so folding into F1
saves an extra follow-up PR cycle.
#### Fix 1: normalize disabled tool names during MCP restart refresh
`packages/cli/src/acp-integration/acpAgent.ts:1563-1566`
The bootstrap path in `cli/src/config/config.ts:1426-1434` applies a
4-step normalization to `tools.disabled`:
1. typeof string filter
2. .trim()
3. drop empty after trim
4. dedupe via Set
The MCP-restart refresh path only did step 1, then stored the raw
strings. `ToolRegistry` checks disabled tools with EXACT
`Set.has(tool.name)`, so a tool disabled at boot as `' Foo '` (or
`'Foo\n'`) is no longer matched after `restartMcpServer` and gets
silently re-registered. This contradicts the documented "toggle +
restart" workflow that #4282 PR 17 advertised.
Fix: mirror the bootstrap normalization verbatim before
`setDisabledTools`. Adds 6 lines + a 7-line comment pointing at the
bootstrap reference for future maintainers.
#### Fix 2: add headroom to MCP restart SDK timeout
`packages/sdk-typescript/src/daemon/DaemonClient.ts:102`
The SDK's `MCP_RESTART_DEFAULT_TIMEOUT_MS` was EXACTLY 300_000ms, the
same ceiling the daemon's own `MCP_RESTART_TIMEOUT_MS` uses for the
upper bound on a single MCP rediscovery. For restarts that finish
(or fail with a typed `McpServerRestartFailedError` JSON envelope)
near 300s, the client `AbortSignal` could fire BEFORE the daemon had
finished serializing + transmitting the response, yielding a client
`TimeoutError` even though the daemon was still within its own
budget.
Fix: bump to 330_000ms (10% / 30s headroom over the daemon ceiling).
Comment updated to call out the race + the rationale for the
specific headroom value. Callers needing tighter caps still pass
their own `timeoutMs` to `restartMcpServer`.
#### Why folded into F1 vs separate follow-up PRs
These are post-merge findings on `#4282 PR 17` code, not F1-introduced
regressions. Normally we'd track as separate follow-up issues (mirror
of the #4325 / `channelInfo` decline). But:
- Both fixes are TINY (~25 LOC + ~2 LOC including comment); the bridge
security fold-in commit `7bd66c6e8` set the precedent of folding in
small same-branch issues when the cost-benefit favors closing them
immediately.
- Same reviewer (wenshao via qwen-latest agent) — won't be confused
by the scope expansion; in fact the original PR 17 commenter is
also the one who'd review the follow-up issue's fix.
- Both fixes target `daemon_mode_b_main`-only paths (MCP restart route
added by PR 17 lives on the integration branch).
- Saves opening 2 trivial follow-up issues that would just sit until
someone picks them up.
#### Verification
- sdk-typescript: 424/424 tests pass (no test hardcoded the old
300_000 default — only the constant declaration itself referenced it)
- cli acp-integration: 282/282 tests pass (no test exercised the
exact whitespace-bearing disabled-tools scenario, so no test
changes were strictly required; a regression test would belong in
a separate test-coverage PR alongside the const.ts test gap from
the #4297 unresolved-comment thread)
- typecheck clean across cli + sdk-typescript
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(acp-bridge): wenshao review round 4 — 3 Suggestion fold-ins (#4319)
1. **bridge.ts:2270 stale line refs in `publishWorkspaceEvent` JSDoc**
— comment said `permission_resolved at line 1717` (actual: line 682)
and `broadcastWorkspaceEvent closure at ~line 2127` (actual: line
1281). Line numbers drifted across the lift commits. Replaced both
with function-name refs (`in resolvePending`, `declared above in
this factory body`) that survive future edits.
2. **`ws.ts:613` opaque references in bridgeFileSystem.ts:20 +
bridgeOptions.ts:267** — no `ws.ts` file exists in the repo; the
ref came from an internal review thread on PR 18 that future
readers can't locate. Replaced with a self-contained description
("post-PR-18 follow-up thread about BridgeClient's inline fs prox…
* feat(daemon): server-side shell command execution for ! (bang) prefix (#4576)
* feat(daemon): server-side shell command execution for ! (bang) prefix
Add direct shell command execution in daemon mode, matching CLI semantics:
commands run immediately via ShellExecutionService without LLM involvement,
output streams to clients via SSE, and results are injected into LLM history
for context in subsequent turns.
- New POST /session/:id/shell route in daemon server
- Bridge executeShellCommand with streaming output via shell_output SSE events
- ACP extMethod sessionShellHistory for LLM history injection
- SDK client shellCommand() method and DaemonShellCommandResult type
- Web-shell ! handler calls server-side execution instead of wrapping as LLM prompt
- Channel adapters detect ! prefix and route through direct execution
- New user_shell_command / user_shell_result SSE event types
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: use typeof guard for shellCommand capability check
Replace `'shellCommand' in this.bridge` with `typeof === 'function'`
check for safer runtime capability detection.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: address wenshao review — 7 fixes
- Fix AnsiOutput serialization (AnsiToken[][] has no .text property)
- Align MAX_SHELL_OUTPUT_FOR_HISTORY with CLI's 10KB limit
- Add debug logging for failed history injection (was empty catch)
- Emit user_shell_result on ShellExecutionService.execute() failure
- Use dynamic backtick fencing in channel shell output
- Forward AbortSignal through DaemonChannelBridge.shellCommand
- Show "aborted" status instead of "code unknown" in normalizer
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(daemon): add session tasks snapshot endpoint (#4578)
Add a read-only daemon session task snapshot status method and HTTP route so clients can inspect background tasks without sending a prompt.
Expose the snapshot through the TypeScript SDK and intercept /tasks in web-shell before generic slash-command forwarding.
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): non-blocking POST /prompt — return 202 with promptId (#4585)
* feat(daemon): non-blocking POST /prompt — return 202 with promptId (#4582)
Decouple trigger from completion: POST /session/:id/prompt now returns
202 Accepted immediately with `{ promptId, lastEventId }`. Completion
is delivered via `turn_complete` / `turn_error` SSE events correlated
by promptId.
- Bridge publishes `turn_complete` and `turn_error` events after
sendPrompt settles (abort-cancelled prompts are suppressed)
- Bridge exposes `getSessionLastEventId()` so the server can snapshot
the cursor before enqueuing
- DaemonClient.prompt() transparently handles 202 by opening a
temporary SSE subscription and awaiting the matching turn event
- Web-shell observes `turn_complete` for passive session viewers
- Capability tag `non_blocking_prompt` advertised for feature detection
- Deadline enforcement preserved: timer aborts the prompt server-side,
surfaced through `turn_error` SSE event instead of HTTP 504
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* refactor(daemon): follow ACP pattern — unconditional 202, SDK event-source reuse
Revert the Prefer: respond-async dual-mode approach in favor of the
simpler ACP-consistent model:
Server:
- POST /prompt unconditionally returns 202 (no opt-in header needed)
- Remove emitPromptDeadline504 (deadline surfaced via turn_error SSE)
SDK DaemonClient:
- Add promptNonBlocking() for callers with existing SSE subscriptions
- Add matchTurnEvent() shared utility for turn event correlation
- prompt() retains temporary SSE fallback for standalone callers
- Export NonBlockingPromptAccepted, matchTurnEvent, isNonBlockingAccepted
SDK DaemonSessionClient:
- prompt() uses promptNonBlocking() when SSE subscription is active,
resolving via _pendingPrompts map (like ACP transport request routing)
- iterateEvents() intercepts turn_complete/turn_error and dispatches
to pending prompts before yielding to the consumer
- Falls back to DaemonClient.prompt() (temp SSE) when no subscription
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): plug abort-listener leak in DaemonSessionClient.prompt
When prompt() resolved via _dispatchTurnEvent (turn_complete SSE),
the abort listener on the caller's signal was never removed. Over a
long-lived session each prompt call accumulated another leaked
listener. Additionally, if the signal fired after resolution, the
stale handler called cancel() — potentially cancelling an unrelated
in-flight prompt.
Fix: wrap resolve/reject to removeEventListener on settlement.
Also: use typed DaemonTurnCompleteData instead of ad-hoc cast in
web-shell passive turn_complete handler.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): type guard in _dispatchTurnEvent, code coercion, passive turn_error
- Add type guard (turn_complete/turn_error only) in _dispatchTurnEvent
before extracting promptId. Without this, a future event type
carrying promptId in data would silently delete the pending entry
without resolving or rejecting the promise.
- Fix String(undefined) producing "undefined" in broadcastTurnError.
When err.code is undefined, 'code' in err is true but
String(undefined) yields the truthy string "undefined", bypassing
the conditional spread and stamping a misleading error code.
- Handle turn_error for passive observers in web-shell. Passive tabs
viewing a session that hits turn_error (agent crash, transport
failure) now dispatch assistant.done instead of staying stuck in
the thinking state indefinitely.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(web-shell,webui,sdk): context-usage API + daemon-react-sdk refactor + dialog UX (#4573)
* feat(web-shell,webui,sdk,cli): context-usage API + dialog UX improvements
- Add GET /session/:id/context-usage endpoint (SDK types, acp-bridge,
cli route, acpAgent handler with tests)
- Refactor webui daemon providers into session/ and workspace/ modules
with daemon-react-sdk subpath export
- Web-shell dialog UX: replace left back icon with right-side ESC close
button, fix keyboard scope so dialogs properly capture keys when input
is focused, blur editor when dialog opens
- Remove /stats subcommands and model dialog custom model (c key) feature
- Remove slash completion auto-submit behavior (align with CLI)
* fix(web-shell,webui,cli): address PR #4573 review issues + parallel agents display
Security fixes:
- Mermaid securityLevel reverted to 'strict', strip foreignObject/style from SVG sanitizer
- Shift+Tab no longer silently sets yolo mode (only approves current request)
- clientLifecycle uses sessionStorage for per-tab client ID isolation
Bug fixes:
- cancel() finally block guards setPromptStatus with session-ID check
- lastRecapBlockCountRef resets on session switch
- collectContextData wrapped in try/catch with field stripping
- useDaemonResource: request sequence counter prevents stale response overwrite
- ResumeDialog: shows error state when session list fails to load
- detachDaemonClient: adds keepalive:true for tab-close reliability
- server.test.ts: adds session_context_usage to EXPECTED_STAGE1_FEATURES
Performance:
- useSyncExternalStore selector hoisted via useCallback
Feature:
- Parallel agents merged display (ParallelAgentsGroup component)
Tests:
- clientLifecycle.test.ts (9 tests): sessionStorage, keepalive, detach behavior
- useDaemonResource.test.tsx (5 tests): stale response race condition coverage
- Markdown.test.ts: updated foreignObject/style assertions to expect stripping
* fix(web-shell): improve ask user question flow
Fix AskUserQuestion answer submission and rendering by forwarding answers through acp-bridge permission metadata while keeping arbitrary response fields filtered.
Improve the web-shell AskUserQuestion dialog: keep the submit tab in order, preserve custom input values, align cursor position with existing selections when switching tabs, and show selected/custom answers with a consistent underline state.
Show ask_user_question tool results without truncating the answer payload.
* fix(web-shell,webui,cli): address PR #4573 critical and suggestion review issues
Critical fixes:
- releaseSession: close session before detaching client to avoid orphaned sessions
- ParallelAgentsGroup: forward pendingApproval/onConfirm props so approvals render inside grouped agents
- fmtCategoryRow: guard against zero contextWindowSize division
Suggestion fixes:
- MemoryDialog: await reloadMemory() before showing success message
- useInputHistory: keep storageKeyRef in sync with prop changes
- App: reset lastRecapBlockCountRef on session switch to prevent auto-recap from silently failing
- App: log auto-recap errors instead of silently swallowing them
- acpAgent: log collectContextData failures instead of silent catch
* feat(web-shell): add daemon followup suggestions
* fix(web-shell): validate context-usage payload and restore question-text answer keys
- parseContextUsageMessage: add runtime check for usage.totalTokens before casting, prevent white-screen on malformed daemon payload
- AskUserQuestion buildResult: use q.question as answer key instead of numeric index, matching downstream consumers that match answers by question text
* fix(web-shell,webui): address remaining PR #4573 review issues
- sanitizeSvg: keep <style> (sanitize @import/external url()) and <foreignObject>
so mermaid diagrams render with correct theming and visible text labels
- mermaid: skip redundant mermaid.initialize() when theme unchanged
- newSession: abort in-flight prompts before resetting store
- ParallelAgentsGroup: i18n for hardcoded English strings
- vite.config: restore rollupTypes: true for NodeNext compatibility
- AskUserQuestion: restore q.question as answer key
* fix(web-shell,webui): fix mermaid error rendering, add detach logging, deduplicate session switch, and add tests
- Add suppressErrorRendering to mermaid.initialize() to prevent error SVGs from being injected into the DOM on render failure
- Replace silent catch on detachDaemonClient with console.warn for debuggability
- Extract startSessionSwitch() helper to deduplicate loadSession/resumeSession
- Update sanitizeSvg tests to match current behavior (foreignObject/style preserved)
- Add groupParallelAgents unit tests covering grouping, splitting, and edge cases
* fix(webui): resolve rebase conflicts with upstream daemon_mode_b_main
- Fix useDaemonFollowupSuggestion import path after DaemonSessionProvider move to session/
- Merge daemon/index.ts exports (keep followup suggestion + add SDK type re-exports)
- Restore lastEventId/setLastEventId in test MockSession interface
- Remove non-existent DaemonWorkspaceSkillDetail re-export
* fix(acp-bridge): validate answer value types in permission response metadata
Reject non-string values in the answers payload to prevent malformed
data from being forwarded through the permission mediator to the agent.
* fix(web-shell,webui): fix shell command output display, loading state, and detach timeout
- transcriptToMessages: create standalone tool_group for shell output
when previous message is not a tool_group (fixes silent drop of ! command output)
- actions: register sendShellCommand in activePromptsRef and manage
promptStatus lifecycle (fixes stuck loading after shell command)
- actions: wrap detachDaemonClient with withActionTimeout in releaseSession
to prevent indefinite hang when daemon is unresponsive
- ToolGroup: auto-expand bash/shell/execute_command tool output by default
- Add shell output tests for transcriptToMessages
* fix(webui): fix state_resync_required handling and catchingUp flag
- Differentiate state_resync_required by reason: epoch_reset resets store
and replays on same stream; ring_evicted preserves awaitingResync and
continues on same stream; other reasons keep original break+reconnect
- Clear awaitingResync on replay_complete so post-replay events flow
- Set catchingUp when activeSession.lastEventId is present, not only on
same-session reconnect (fixes resume catchingUp indicator)
* fix(web-shell,webui): add getTasks action and fix broken reference after rebase
- Add getTasks() to DaemonSessionActions interface and implement in actions.ts
- Fix App.tsx: actions.getTasks → sessionActions.getTasks (variable renamed
during refactor but this callsite was missed during rebase merge)
* fix(webui): fix releaseSession to use closeSession instead of detach
releaseSession was incorrectly calling detachDaemonClient with the
current client's ID, which only decremented attachCount without
actually closing the target session. Replace with
session.client.closeSession() (DELETE /session/:id) to properly
terminate the session. Also fix sendShellCommand to use a distinct
shellKey to avoid colliding with prompt AbortControllers.
* feat(webui): add non-blocking prompt settlement and passive turn event handling
- Add settleActivePromptFromTurnEvent to resolve/reject active prompts
from turn_complete/turn_error SSE events in the Provider event loop
- Add isPromptLifecycleTurnEvent filter to prevent turn events from being
dispatched to the transcript store as unrecognized debug events
- Add waitForAcceptedPromptCompletion in actions.ts to bridge the gap
between 202-accepted prompts and their eventual turn completion
- Extend ActivePrompt type with promptId, resolve/reject callbacks, and
pendingResult/pendingError for deferred settlement
- Add passive observer handling for turn_complete/turn_error so non-sender
tabs correctly end the streaming state
- Add tests for non-blocking prompt acceptance and early turn completion
---------
Co-authored-by: ytahdn <[email protected]>
* feat(sdk): add serve-bridge MCP server & rename mcp → daemon-mcp (#4555)
* feat(sdk): add MCP server bridge wrapping qwen serve HTTP API
Expose qwen serve's HTTP endpoints as MCP tools via a stdio-based
MCP server. This allows any MCP-compatible client (Claude Desktop,
Cursor, VS Code, etc.) to interact with a running qwen serve daemon
directly through the standard MCP protocol.
The bridge provides 31 tools covering session lifecycle, agent
interaction (prompt/cancel), workspace file operations, and
workspace configuration management. A standalone bin entry
(`qwen-serve-mcp`) is included for direct CLI usage.
* docs(sdk): add README for qwen-serve-bridge MCP server
Includes usage instructions, environment variables, MCP client
configuration examples, tool listing, session management notes,
and verification commands.
* chore(sdk): update copyright year to 2026 in serve-bridge files
* fix(sdk): correct file_stat/dir_list/glob endpoints and add process signal handling
- file_stat now calls GET /stat instead of readWorkspaceFile fallback
- dir_list now calls GET /list for proper directory listing
- glob now calls GET /glob for pattern matching
- Add daemonFetch() helper for raw HTTP calls to endpoints not in DaemonClient
- Add SIGINT/SIGTERM graceful shutdown in bin.ts
- Add unhandledRejection handler to prevent silent crashes
- Exit cleanly when stdin pipe closes (parent process gone)
* docs(sdk): add external usage instructions for qwen-serve-bridge
Document three configuration methods: npx (zero-install), global
install, and local path (dev). Clarify Node >=22 requirement and
add qwen serve startup options.
* fix(sdk): collect agent response text via SSE in prompt tool
The prompt endpoint only returns stopReason synchronously. Actual
response content is streamed via session SSE events. Now the prompt
tool subscribes to events in parallel, collects agent_message_chunk
texts, and returns the full response in the result.
* refactor(sdk): rename src/mcp to src/daemon-mcp
Rename the MCP utilities directory to better reflect its role as
daemon-specific MCP tooling. Update all import paths in index.ts,
Query.ts, and the bin entry in package.json.
* docs(sdk): update README paths after mcp → daemon-mcp rename
* test(sdk): add unit tests for serve-bridge MCP server
22 tests covering:
- Server creation and configuration
- Session state management (resolveSessionId, defaultSessionId)
- Auth headers and daemonFetch helper
- Error handler wrapper
- Tool registration counts (31 total, no duplicates)
- session_create sets defaultSessionId
- session_close clears defaultSessionId
- prompt tool SSE event collection
Also fix createSdkMcpServer.test.ts import paths after mcp → daemon-mcp rename.
* feat(sdk): implement persistent SSE connection for serve-bridge prompt
Replace per-prompt SSE subscription with a persistent connection that is
established at session_create and torn down at session_close. This
eliminates the 200ms delay and race condition that caused unreliable
response collection in Qoder.
- Add SessionEventStream/PromptCollector types and lifecycle helpers
- Rewrite prompt handler to use shared persistent stream
- Start SSE on session_create/load/resume, stop on session_close
- Update unit tests for new persistent SSE pattern
* fix(sdk): resolve P0 issues in serve-bridge MCP tools
1. prompt tool: return explicit timeout error instead of silently
returning empty response when SSE collection times out (30s)
2. health tool: remove unused `deep` parameter that was never passed
to the underlying DaemonClient.health() API
* refactor(sdk): improve daemon-mcp architecture (P1/P2 fixes)
P1 fixes:
- Split types.ts into types.ts (interfaces), sse.ts (SSE lifecycle),
helpers.ts (handler/resolveSessionId/daemonFetch) for separation of concerns
- Add fileStat/dirList/glob methods to DaemonClient, removing raw
daemonFetch usage from workspaceRead tools
- Move session_set_model and session_context from agent.ts to session.ts
for naming consistency
- Add error logging with stack traces in handler() wrapper
P2 fixes:
- Remove unused exports from formatters.ts (formatToolResult,
formatTextResult, mergeToolResults, isValidContentBlock)
- Fix copyright year to 2026 in tool.ts and createSdkMcpServer.ts
* fix(sdk): use bracket notation for process.env access in bin.ts
* fix(sdk): address PR review High-priority feedback
1. PromptCollector: add `resolved` flag to guard against double-resolve
race between _meta event and stopEventStream teardown
2. session_create: stop SSE for previous default session before creating
a new one to prevent connection leaks
3. bin.ts: include full stack trace in unhandledRejection handler for
production debugging
* fix(sdk): address Medium/Low review feedback for serve-bridge
- Add timeout behavior documentation to prompt tool description
- Fix README token documentation (remove misleading loopback claim)
- Add session TTL cleanup (30min idle timeout) to prevent SSE connection leaks
- Extract workspace_agents_manage switch cases into separate functions
- Track lastActivityMs on SessionEventStream for TTL-based cleanup
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(sdk): resolve P0 review issues — _meta check level & global scope security
- Fix _meta check: daemon emits _meta at update level, not inside content.
Previous code checked 'content._meta' which was always false, causing
every prompt to wait the full 30s timeout before returning.
- Security: restrict global scope writes by default. MCP bridge now blocks
workspace_memory_write and workspace_agents_manage with scope='global'
unless QWEN_BRIDGE_ALLOW_GLOBAL_SCOPE=true is set. Prevents cross-workspace
prompt injection via compromised MCP clients.
- Fix test: add missing lastActivityMs and allowGlobalScope to mock objects.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(sdk): resolve P1 review issues — SSE leak, error handling, concurrent guard
- session_load/session_resume: stop previous default session's SSE stream
before starting a new one (matching session_create behavior). Also add
workspaceCwd fallback for consistency.
- SSE catch block: log unexpected disconnections (skip AbortError from
intentional close) and resolve active collector in finally block so
prompt doesn't hang 30s on network failures.
- Concurrent prompt guard: reject second prompt on same session if one
is already in progress, preventing collector corruption.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(sdk): resolve P2 review issues — robustness and cleanup
- close(): abort all active SSE streams on server shutdown
- ReDoS: replace regex /\/+$/ with hand-rolled loop (matches DaemonClient)
- file_write: validate expected_hash required for replace mode
- prompt: clear setTimeout on normal resolve (prevent 30s timer leak)
- prompt: return timeout as distinct stop_reason with warning field
- prompt_cancel: resolve active collector so prompt returns immediately
- session_create: stop old SSE after new session confirmed (not before)
- session_close: close HTTP session before stopping SSE stream
- session_load/resume: add workspaceCwd fallback for consistency
- bin.ts: fix stale comment path (mcp → daemon-mcp)
- Remove dead code: authHeaders/daemonFetch (unused by any tool handler)
- workspaceWrite: add default case to switch, fix arrow-body-style lint
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(sdk): address final review — ordering, SSE safety, build, tests
- session_load/resume: move stopEventStream after API success (match
session_create pattern), prevents bridge becoming unusable on failure
- SSE finally: guard eventStreams.delete with identity check to prevent
deleting a newly created stream; clear defaultSessionId on disconnect
- prompt timeout: cancel daemon-side processing to prevent stale chunks
contaminating the next prompt
- session_close: wrap closeSession in try/finally so SSE always cleans up
- resolveSessionId: bump lastActivityMs so workspace operations reset TTL
- build: add esbuild entry for serve-bridge/bin.ts with shebang banner
- tests: add coverage for concurrent prompt guard, prompt_cancel resolve,
global scope rejection, file_write hash validation
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(sdk): address R6 review — security, SSE robustness, race conditions
- Guard session_set_approval_mode: block yolo/auto and persist without
allowGlobalScope opt-in (privilege escalation fix)
- Fix startEventStream stale entry: check abortCtrl.signal.aborted before
skipping re-creation of dead SSE connections
- Fix timedOut race condition: use collector.resolved to prevent false
timeout when _meta and timer fire in same microtask batch
- Add interrupted flag to PromptCollector: stopEventStream and SSE
finally block now mark collector as interrupted, prompt handler returns
distinct stop_reason:'interrupted' with warning
- Handle daemon error/fail SSE events: log to stderr and resolve collector
immediately instead of waiting for 30s timeout
- Move validateGlobalScope to write-only branches in workspace_agents_manage:
list/get operations no longer blocked by scope check
- Fix shutdown() to await server.instance.close() before process.exit
- Add tests for approval mode guard and read-only agents_manage
* fix(sdk): document _meta protocol contract assumption in SSE handler
* fix(sdk): address R7 review — interrupted consistency, auto-edit guard, cancel resilience
- Set interrupted=true before resolving collector on daemon error events
(consistent with finally block and stopEventStream)
- Return isError:true on interrupted path in prompt handler
(consistent with timeout path)
- Add auto-edit to restricted approval modes list
(same risk level as auto/yolo)
- Wrap prompt_cancel's client.cancel() in try/catch so collector
always resolves even if daemon is unreachable
* test(sdk): add regression tests for R7 fixes
- Assert prompt_cancel sets collector.interrupted = true
- Add auto-edit approval mode rejection test
* fix(sdk): harden bridge security and improve close lifecycle
- Guard workspace_tool_toggle behind allowGlobalScope
- Validate handleAgentUpdate requires at least one field to update
- Use SDK onclose lifecycle hook instead of monkey-patching close()
- Improve prompt tool description accuracy for timeout behavior
- Add tests for tool_toggle guard and agents_manage update validation
* fix(sdk): guard mcp_restart and fix agent update field validation
- Add allowGlobalScope guard to workspace_mcp_restart (consistent with
workspace_tool_toggle — restarting MCP servers is equally disruptive)
- Remove scope from hasField check in handleAgentUpdate (scope is a
routing parameter, not an update field — passing only scope would
POST an empty body to the daemon)
* fix(sdk): address doudouOUC review — imports, descriptions, error messages
- Remove runtime re-exports from types.ts; tool files now import
directly from sse.js/helpers.js to avoid circular dependency risks
- Add best-effort comment on SSE error event regex explaining limitations
- Rewrite prompt tool description to clarify 30s is post-response
collection timeout, not overall timeout
- Split approval mode error messages: distinguish dangerous-mode vs
persist-restricted cases
- Mark name parameter as (create only) in agents_manage schema
- Log close errors in shutdown instead of silently swallowing
---------
Co-authored-by: Claude Opus 4.6 <[email protected]>
* feat(telemetry): trace daemon prompt lifecycle (#4556)
* feat(telemetry): trace daemon prompt lifecycle
Connect qwen serve HTTP routes, ACP bridge dispatch, and ACP child prompt execution through OpenTelemetry context propagation. The daemon injects reserved qwen.telemetry metadata internally so clients do not need to pass trace context.
Closes#4554
Co-authored-by: Qwen-Coder <[email protected]>
* fix(telemetry): emit daemon bridge events as spans
Record bridge telemetry events as short daemon bridge spans when they fire outside an active request or prompt context, so asynchronous channel exits remain observable.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(telemetry): address wenshao review — 10 fixes
- recordDaemonHttpResponse: don't clobber ERROR with OK on non-5xx
- finish(): remove signal listeners synchronously before async telemetry shutdown
- extractDaemonTraceContext: reject all-zero IDs, include tracestate, set isRemote
- propagation.inject: wrap in try/catch for consistency
- injectPromptContext: move inside prompt.dispatch span for correct parent
- withDaemonSpan: guard on isTelemetrySdkInitialized()
- toOtelAttributes: remove identity function, pass attributes directly
- injectDaemonTraceContext: early-return when no active span (avoid empty _meta)
- emitDaemonLog: remove redundant event.timestamp attribute
- NOOP_BRIDGE_TELEMETRY: drop async, add short-circuit for missing keys
* fix(telemetry): remove TraceState constructor usage in manual fallback
TraceState is a type-only export from @opentelemetry/api (not a
runtime constructor). The manual fallback path now omits tracestate
since the primary propagation.extract path already handles it.
* fix(telemetry): address wenshao review round 3
- withDaemonSpan: pass undefined (not getSpan result) when SDK off
- stripReservedTraceMeta: skip copy when no reserved keys present
- sendBridgeErrorImpl: truncate error.message in emitDaemonLog
* fix(telemetry): address wenshao review round 4
- extractDaemonTraceContext: use ROOT_CONTEXT as extraction base to
prevent incorrect parent-child when agent has its own active span
- extractDaemonTraceContext (manual fallback): already has isRemote:true
and ROOT_CONTEXT from previous fix — confirmed consistent
- injectDaemonTraceContext: skip _meta assignment when original had no
_meta and no trace headers were injected (match NOOP behavior)
- withInteractionSpan: cancelled prompts get UNSET instead of OK so
dashboards can distinguish cancelled from successful
- emitDaemonLog: use OTel built-in timestamp field instead of custom
attribute
* fix(telemetry): address wenshao review round 5
- Import DAEMON_TRACEPARENT/TRACESTATE_META_KEY from core instead of
redeclaring locally in bridge.ts (drift risk)
- Add isTelemetrySdkInitialized() guard to event() in
createDaemonBridgeTelemetry for consistency with siblings
- Remove setStatus(ERROR, "HTTP 500") from recordDaemonHttpResponse
to avoid overwriting the descriptive error message already set by
recordDaemonError
---------
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): add request-level logging for serve routes (#4606)
* feat(daemon): add request-level logging for serve routes
Add access-log middleware and inline business-context logs to the daemon
server. Previously only 5xx errors were logged via sendBridgeError,
making it impossible to debug issues like "frontend says /recap returned
nothing" — the backend had zero trace of the request.
Changes:
- Access-log middleware: logs method, path, sessionId, clientId, status,
and durationMs for every completed request (excludes GET /health and
SSE /events to avoid noise)
- Inline logs for key routes: session spawn/attach, prompt enqueue,
cancel, recap (distinguishes null vs generated), shell command
completion, and SSE stream open/close with duration
- All logging gated on daemonLog existence (tests/embeds unaffected)
* feat(daemon): add full-chain logging for recap/prompt/cancel/shell
Extend request-level logging deeper into the call chain so operators can
trace a request from HTTP route through bridge → ACP child → core service.
- bridge.ts: log entry for sendPrompt, cancelSession,
executeShellCommand, and generateSessionRecap (entry + result) via
onDiagnosticLine (lands in daemon log file unconditionally)
- acpAgent.ts: log ext-method receipt and completion for recap handler
via debugLogger (lands in per-session debug file)
- sessionRecap.ts: add debugLogger.debug at every early-return path
(no geminiClient, history too short, empty dialog, empty model
response, tag extraction failed) so recap=null is always attributable
* fix(daemon): move access-log before auth, fix SSE exclusion, add load/resume log
- Move access-log middleware before bearerAuth and JSON parser so 401
auth rejections and malformed-body 400s are captured in the daemon log
- Fix /events exclusion: only suppress logging for successful SSE
streams (status 200); failed SSE handshakes (4xx) are still recorded
- Add inline log for POST /session/:id/load and /resume handlers
* fix(daemon): log 5xx at error level, remove unnecessary type casts
- Access-log middleware now uses error level for 5xx responses (was
info, making them invisible to level-filtered log queries)
- Remove unnecessary type casts on response.recap and result.exitCode
— TypeScript already infers the correct types from bridge methods
* fix(daemon): use space separator in access-log route field
Align with the existing convention used by sendBridgeError (e.g.
"POST /session/:id/recap") so grep/filtering across both access-log
and error-log entries works with a single pattern.
* fix(daemon): address wenshao review — dedup 5xx, reap log, prompt clientId+errName
- Remove middleware error-level for 5xx (sendBridgeError is authoritative;
middleware duplicating at error inflates alert counts)
- Add warn log when spawned session is immediately reaped due to client
disconnect before response delivery
- Add clientId to all prompt log lines (enqueued/completed/failed) for
consistency with other route logs
- Include err.name in prompt-turn-failed message so operators can
distinguish PromptDeadlineExceededError (routine) from
BridgeChannelClosedError (infra issue)
* fix(daemon): exclude heartbeat from access-log (high-frequency probe)
Heartbeat fires every 30s per active session — with 3 sessions that's
360 log lines/hour of noise drowning real signal. Same exclusion logic
as GET /health.
* feat(web-shell): add /delete command with batch delete support (#4603)
* feat(web-shell): add /delete command with batch delete support
Add a /delete slash command to the web-shell that allows users to
permanently delete session data files. Supports both single-session
and multi-select batch deletion with proper error handling.
Changes:
- Add POST /sessions/delete batch endpoint to daemon server
- Add deleteSessionsData() to SDK DaemonClient
- Add DeleteSessionDialog with multi-select (Space to toggle, Enter
to confirm) and search/filter support
- Add deleteSession/deleteSessions workspace actions and hooks
- Distinguish errors vs notFound in single-delete action (throw on
real errors, return false only for notFound)
- Surface failure reasons in batch delete (allFailed / partialFail
messages include first error detail)
- Normalize Error objects to string messages in server JSON response
- Add tests for server route, SDK client, and workspace provider
* fix(web-shell,cli): address PR review issues for batch delete
- Pass clientId to deleteSessionsData for ownership validation
- Add sessionIds max length (100) and deduplication
- Parallelize bridge.closeSession via Promise.allSettled
- Add server-side logging for close failures
- Reconcile selectedIds with search filter before delete
- Prune selectedIds when search query changes
- Fix notFound counting: only errors are failures
- Fix partial failure double toast: single error message
- Fix empty-state: show error message when load fails
- Fix hardcoded English "matches" → i18n key
- Remove dead targetSession parameter
- Align checkbox for current session ([-] instead of spaces)
- Add happy path test for batch delete
- Reload session list on notFound-only response
* fix(web-shell,cli): remove clientId ownership check for batch delete and improve UX
- Remove clientId validation from batch delete endpoint since workspace-level
access is sufficient authorization. The per-tab clientId check prevented
cross-tab deletion of active sessions without real security benefit (user
can bypass by resuming the session first).
- Wrap filtered sessions list in useMemo to stabilize reference and prevent
unnecessary keydown listener teardown/re-register on each render.
- Include notFound sessions in onDeleted callback so the toast correctly
reports the total count of cleaned-up sessions.
Generated with AI
* fix(web-shell,cli): address round-2 review — logging, dead code, tests
- Add comment documenting intentional no-clientId in batch delete
- Log removeSessions filesystem errors to stderr for debuggability
- Count notFound as success in deleteSession for proper UI reload
- Remove dead if (!deleteSessions) / if (!deleteSession) guards
- Fix partial-failure double-wrapped toast message
- Reset selectedIdx when exiting search mode via Enter
- Add 5 batch tests: mixed outcomes, max-100 cap, non-string
validation, dedup, and file preservation on error
Generated with AI
* fix(web-shell,cli): fix partial-failure toast and add 500 catch block test
- Revert partial-failure handler to use delete.partialFail i18n key
through onError only, removing contradictory onDeleted call
- Add test for removeSessions unexpected throw (500 catch block)
* refactor(cli): use static import for SessionService in batch delete test
---------
Co-authored-by: ytahdn <[email protected]>
* feat(serve): runtime MCP server add/remove (T2.8 #4514) (#4552)
* feat(sdk): add mcp_server_added daemon event type (T2.8 #4514)
Schema-only addition. New event fires on POST /workspace/mcp/servers
success including replace and same-fingerprint no-op, carrying
{name, transport, replaced, shadowedSettings, toolCount, originatorClientId}.
Also exports DAEMON_KNOWN_EVENT_TYPE_VALUES from the public SDK
surface so drift-insurance tests can assert on the known-event roster.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(sdk): add mcp_server_removed daemon event type (T2.8 #4514)
Counterpart to mcp_server_added. Fires on DELETE /workspace/mcp/servers/:name
that actually dropped an entry. Idempotent skip ('not_present') does NOT emit.
Payload {name, wasShadowingSettings, originatorClientId}.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(sdk): add runtime MCP add/remove request + result types (T2.8 #4514)
Discriminated unions for add/remove results so caller can narrow on
.skipped vs success. Add request mirrors the route body shape.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(core): add Config.addRuntimeMcpServer / removeRuntimeMcpServer (T2.8 #4514)
Runtime-only overlay map separate from this.mcpServers (settings layer).
Bypasses the initialized-guard on addMcpServers since the entire point is
post-init mutation. getMcpServers() cascade extension comes in the next
task.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(core): tighten Config.addRuntimeMcpServer JSDoc wording (T2.8 #4514)
"intentionally bypasses the guard" implied a suppressed if-throw; clarify
to "does not enforce the guard" since there is nothing to bypass.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(core): runtime MCP overlay in getMcpServers cascade (T2.8 #4514)
runtimeMcpServers Map is applied as the last (winning) layer over
extensions + this.mcpServers, then filtered by allowedMcpServers.
Shadow semantics for T2.8 fall out of merge order — runtime entries
override settings entries by name; removeRuntimeMcpServer un-shadows.
excludedMcpServers exclusion continues to flow through isMcpServerDisabled
(UI layer), unchanged from prior behaviour.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(core): McpClientManager.{add,remove}RuntimeMcpServer + budget/pool wiring (T2.8 #4514)
Adds runtime MCP server lifecycle on the manager:
- addRuntimeMcpServer: budget tryReserve → Config runtime overlay → pool acquire
- removeRuntimeMcpServer: Config drop → pool drain → budget release
Shadow-over-settings detected via getSettingsMcpServers raw-map accessor on
Config. Idempotent replace via fingerprint dedup at pool layer. Budget warn
mode returns skipped soft-refuse rather than spawning. New error classes:
McpBudgetWouldExceedError, McpServerSpawnFailedError, InvalidMcpConfigError.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(acp-bridge): add T2.8 error kinds (mcp_budget_would_exceed, mcp_server_spawn_failed, invalid_config) (#4514)
Mirrored on the SDK via DAEMON_ERROR_KINDS export. Bridge maps the matching
typed error classes (McpBudgetWouldExceedError, McpServerSpawnFailedError,
InvalidMcpConfigError) to these kinds in sendBridgeError (next task).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(acp-bridge): host-side {add,remove}RuntimeMcpServer methods + event fan-out (T2.8 #4514)
Bridge round-trips qwen/control/workspace/mcp/runtime-{add,remove} ACP
ext-methods and emits mcp_server_added / mcp_server_removed via
broadcastWorkspaceEvent. Soft-refuse (budget_warning_only) and idempotent
skip (not_present) paths do NOT emit events.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(acp-bridge): qwen/workspace/mcp/runtime-{add,remove} ext-methods (T2.8 #4514)
Child-side ACP handlers delegate to McpClientManager.{add,remove}RuntimeMcpServer.
Mirror /workspace/mcp/:server/restart registration pattern including typed-error
→ ACP error mapping (code field preserved for sendBridgeError mapping at the HTTP
layer in Task 10).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(serve): POST /workspace/mcp/servers route (T2.8 #4514)
Mutate-strict route validates name + config shape, parses + validates
X-Qwen-Client-Id, forwards to HttpAcpBridge.addRuntimeMcpServer. Errors
propagated from ACP via RequestError(data.errorKind) and mapped to HTTP
status in sendBridgeError: mcp_budget_would_exceed → 409,
mcp_server_spawn_failed → 502 (body includes exitCode/stderr/timeout),
invalid_config → 400, acp_channel_unavailable → 503.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(serve): DELETE /workspace/mcp/servers/:name route (T2.8 #4514)
Mutate-strict route validates :name path param (alphanumeric + _-,
≤ MAX_SERVER_NAME_LENGTH), parses + validates X-Qwen-Client-Id, forwards
to HttpAcpBridge.removeRuntimeMcpServer. Idempotent: missing entry returns
200 {skipped:true, reason:'not_present'}.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(serve): mcp_server_runtime_mutation capability tag (T2.8 #4514)
Always-on tag in SERVE_CAPABILITY_REGISTRY. Pre-flight check before
POST /workspace/mcp/servers — older daemons silently 404.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(sdk): DaemonClient.{add,remove}RuntimeMcpServer helpers (T2.8 #4514)
Thin wrappers around POST /workspace/mcp/servers and
DELETE /workspace/mcp/servers/:name. Mirrors restartMcpServer helper.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* docs(serve): document runtime MCP server mutation routes (T2.8 #4514)
POST /workspace/mcp/servers + DELETE /workspace/mcp/servers/:name
with shadow-over-settings semantics, ephemeral persistence,
mcp_server_runtime_mutation capability tag, and event emission.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(test): index-signature property access in acpAgent T2.8 test (#4514)
Pre-commit typecheck (cli workspace) flagged err.data.errorKind /
err.data.serverName needing bracket notation. Switch to data?.['errorKind']
to satisfy noPropertyAccessFromIndexSignature.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address 5 Critical review items from wenshao (T2.8 #4514)
C1: Flatten spawn_failed details at ACP layer (spread err.details, not
nest under data.details) so HTTP 502 body exposes exitCode/stderr/timeout.
C2: Add toolRegistry.removeMcpToolsByServer + removeMCPServerStatus +
stopHealthCheck to removeRuntimeMcpServer (mirrors removeServer cleanup).
C3: Bridge throws error with data.errorKind='acp_channel_unavailable' instead
of SessionNotFoundError so sendBridgeError maps to documented 503.
C4: Require X-Qwen-Client-Id header on POST/DELETE runtime MCP routes —
return 400 missing_client_id instead of coercing to empty string.
C5: Remove releaseSlotName in standalone replace path — budget slot carries
over to the new entry, preventing accounting leak.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(core+cli): address round 4-6 Critical review items (T2.8 #4514)
- Replace flow: add toolRegistry.removeMcpToolsByServer + stopHealthCheck
before disconnecting old entry (fixes stale tool + timer leak)
- Spawn-failure catch: add toolRegistry.removeMcpToolsByServer +
stopHealthCheck (fixes orphaned tools from partial discover)
- Strip `trust` field from config in acpAgent ext-method handler
(security: prevents runtime-added servers from bypassing permission gates)
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address rounds 5-7 review items — build, security, correctness (T2.8 #4514)
Build breakers (Critical):
- events.ts: add missing /** JSDoc opener for DaemonMcpServerAddedData
- events.ts: add missing `: undefined` arm in followup_suggestion ternary
- events.ts: close isFollowupSuggestionData function body (missing ); })
Security (Critical):
- acpAgent: strip authProviderType, includeTools, excludeTools, cwd from
runtime-added server configs (prevents SSRF via cloud creds leak and
arbitrary cwd spawn)
- mcp-client-manager: reject servers in excludedMcpServers blocklist
- acpAgent: add Array.isArray guard to config validation
Correctness:
- mcp-client-manager: identity-check on pooledConnections.delete in remove
(prevents concurrent add+remove race deleting NEW pool entry)
- mcp-client-manager: add client.disconnect() in catch block for
standalone path (prevents transport/process leak)
- mcp-client-manager: add consecutiveFailures, isReconnecting,
dropRefusalEntry cleanup in removeRuntimeMcpServer
- mcp-client-manager: emit mcp-client-update on spawn failure cleanup
- mcp-client-manager: extract exitCode from error when available
- mcp-client-manager: fix replaced=true → false for same-fingerprint
idempotent re-add (no transport was torn down)
- server.ts: whitelist error fields in sendBridgeError responses
(prevent unbounded internal ACP data spread)
- bridge.ts: remove dead try/catch in addRuntimeMcpServer (all branches
just re-threw)
- bridge.ts: add try/catch to removeRuntimeMcpServer for error mapping
- bridge.ts: narrow AddOk.transport to literal union type
SDK / DX:
- DaemonClient: add timeoutMs param to addRuntimeMcpServer (default 330s,
matching restartMcpServer — prevents 30s SDK timeout vs 5min bridge)
- mcp-client-manager: add debugLogger.info at method entry
Docs:
- qwen-serve.md: clarify replaced:true vs replaced:false semantics
* fix(serve): strip env field, add status cleanup and name validation (T2.8 #4514)
Security:
- Strip `env` from runtime-added MCP server configs (prevents
NODE_OPTIONS/LD_PRELOAD injection via HTTP body)
Correctness:
- Add `removeMCPServerStatus(name)` in spawn-failure catch block
(prevents stale CONNECTING entry in status registry)
Hardening:
- Add name validation (charset + length) to ACP ext-method handlers
for both add and remove (matches HTTP route validation)
* fix(serve): strip oauth/headers, reject __proto__ names, fix remove timeout (T2.8 #4514)
Security:
- Strip `oauth` and `headers` from runtime-added configs (prevents
credential exfiltration via OAuth flow and header injection)
- Reject `__proto__`, `constructor`, `prototype` as server names
(prevents prototype pollution when name becomes object key)
SDK:
- Add timeoutMs to removeRuntimeMcpServer (match add's 330s default)
Docs:
- Remove `env` from POST example (stripped by daemon since 66dc4ce1c)
- Document stripped fields list
* fix(serve): strip type field, add __proto__ rejection to HTTP routes (T2.8 #4514)
Security:
- Strip `type` from runtime config (prevents SDK transport routing bypass)
- Add __proto__/constructor/prototype rejection to HTTP POST route
(ACP handlers already had this; HTTP routes were missing it)
Docs:
- Add includeTools, excludeTools, type to stripped-fields list
* fix(serve): add name validation + __proto__ guard to DELETE route (T2.8 #4514)
* fix(serve): remove dead code in DELETE route validation (T2.8 #4514)
* fix(serve): restore MAX_SERVER_NAME_LENGTH in DELETE, add __proto__ to POST (T2.8 #4514)
* fix(serve): split validation into precise error messages + add test coverage (T2.8 #4514)
Split combined regex + reserved-name validation into separate checks with
distinct error messages on both POST and DELETE routes. Added tests for
__proto__/constructor/prototype rejection on POST, and MAX_SERVER_NAME_LENGTH +
reserved-name rejection on DELETE.
* feat(daemon): add POST /session/:id/btw endpoint for side questions (#4610)
* feat(daemon): add POST /session/:id/btw endpoint for side questions
Support /btw (side question) via daemon HTTP, allowing daemon clients
(web-shell, IDE plugins) to run tool-free, single-turn LLM queries
against the session's conversation context without blocking the main
prompt stream.
- Extract buildBtwPrompt + buildBtwCacheSafeParams to core/utils/btwUtils
- Add sessionBtw ext-method to SERVE_CONTROL_EXT_METHODS
- Add generateSessionBtw to HttpAcpBridge interface and implementation
- Handle ext-method in acpAgent with 55s timeout self-guard
- Add REST endpoint with AbortController wired to client disconnect
- Register session_btw capability
- Expand btwCommand supportedModes to include 'acp' with sync fallback
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: address wenshao review — lint, perf, logging, fallback consistency
- Use Array<Promise<unknown>> syntax (eslint array-type rule)
- Use getHistoryTail() instead of full clone + slice (perf)
- Add debug logging to catch block in buildBtwCacheSafeParams
- Fall back to getCacheSafeParams() in acpAgent (consistency with CLI)
- Add ACP mode test branches for null text and missing cache params
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: address wenshao review round 2 — listener cleanup, logger, clone, length cap
- Clean up abort listener on happy path (prevent leak with long-lived signals)
- Move createDebugLogger('btw') to module level (match codebase convention)
- structuredClone generationConfig to match getCacheSafeParams contract
- Add 4096 char max length validation on question field
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: extract BTW_CHILD_TIMEOUT_MS constant with coupling comment
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): bound btw question length and order session validation before abort
- acpAgent sessionBtw: enforce 4096-char cap on `question`, matching the HTTP
route so direct ACP clients (Streamable HTTP/WebSocket) can't bypass it and
consume unbounded LLM tokens
- bridge generateSessionBtw: validate channel/isDying before the signal.aborted
short-circuit so a dead session throws SessionNotFoundError (404) instead of
returning {answer: null} (200), matching the generateSessionRecap ordering
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(telemetry): add client_id attribute and permission route spans to daemon telemetry (#4628)
Add qwen-code.client_id span attribute to daemon HTTP request spans and
bridge prompt.dispatch spans. Add telemetry coverage for permission vote
routes (POST /session/:id/permission/:requestId, POST /permission/:requestId).
Add addDaemonRequestAttribute helper for post-rebase promptId enrichment.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(telemetry): add tool spans and session.id to daemon/ACP path (#4630)
* feat(telemetry): add tool spans and session.id to daemon/ACP path
Add interaction-level and tool-level OTel spans to the daemon's ACP
Session.ts, closing the observability gap described in #4602.
Changes:
- session-tracing.ts: emit session.id on llm_request, tool, and
tool.execution spans via getCurrentSessionId()
- Session.ts runTool(): wrap tool lifecycle in startToolSpan /
runInToolSpanContext / endToolSpan; wrap invocation.execute() in
startToolExecutionSpan / endToolExecutionSpan
- Session.ts #executePrompt: emit logConversationFinishedEvent at
turn end (inside withInteractionSpan, after #handleStopHookLoop)
- Session.ts #executeCronPrompt: wrap body in withInteractionSpan
so cron tool calls also get proper trace hierarchy
* fix(telemetry): address Copilot review — cron abort status + exec span cancellation
- Cron path getResultStatus now checks ac.signal.aborted so aborted
cron runs record turn_status='cancelled' instead of 'ok'
- Tool execution span success path now checks abortSignal.aborted,
aligning with coreToolScheduler cancellation semantics
* fix(telemetry): correct session.id, span outcomes, conversation_finished coverage
Address wenshao + Copilot review on the daemon/ACP telemetry path.
- session-tracing.ts: derive session.id for llm_request/tool/tool.execution
spans from the per-session parent span context (resolveSessionId) instead of
the process-global getCurrentSessionId(). A daemon hosts many sessions in one
process, so the global cross-stamped child spans with whichever session last
initialized telemetry while the interaction span carried the correct id.
Falls back to the global for the single-session CLI path. [wenshao Critical]
- Session.ts #executePrompt: move logConversationFinishedEvent into a finally
wrapping the whole turn loop so cancelled / no-stream / API-error / rate-limit
terminal paths also emit (previously only the clean stop-hook path did).
Emitted for all approval modes — an intentional divergence from the CLI's
YOLO-only gating, since daemon turns run autonomously regardless of mode.
[wenshao Critical + Suggestion, Copilot turnCount]
- Session.ts #executeCronPrompt: emit conversation_finished on every terminal
cron path (clean / abort / caught error). [wenshao Critical]
- Session.ts runTool success path: reflect toolResult.error and cancellation in
logToolCall / recordToolResult / the tool span instead of hardcoding success,
so soft tool failures are no longer mislabeled as successful. [Copilot]
- Session.ts tool-confirmation Cancel: route through earlyErrorResponse so
spanError carries the cancellation reason (was the generic 'tool error') and
the declined call is recorded. [wenshao Suggestion]
- Session.ts startToolSpan: dual-emit the legacy call_id alias like
CoreToolScheduler for backwards-compat dashboards. [Copilot]
* test(telemetry): cover session.id propagation, conversation_finished, tool outcome
Address wenshao's no-test-coverage CHANGES_REQUESTED on the daemon/ACP
telemetry changes.
- session-tracing.test.ts: assert tool / llm_request / tool.execution spans
derive session.id from the owning interaction context (not the process-
global) including a multi-session isolation case and the CLI global
fallback.
- Session.test.ts: assert conversation_finished is emitted on the normal turn
AND on the error/throw path (the path that previously dropped it), and that
a soft tool failure (toolResult.error) is recorded with status 'error'.
* fix(telemetry): annotate withInteractionSpan result param to avoid implicit any
The interaction-span getResultStatus callback relied on generic inference
of T from the turn-loop return type; under the branch's pre-existing
upstream type errors that inference degrades to any, surfacing a
noImplicitAny error at the callback. Annotate the param explicitly so it
no longer depends on inference. (wenshao verification report)
* fix(telemetry): distinguish error from cancelled in interaction/tool outcomes
Address wenshao review round 2 (telemetry-accuracy suggestions).
- session-tracing.ts: extend InteractionSpanResultStatus to 'ok' | 'error' |
'cancelled' and have withInteractionSpan's finally set SpanStatusCode.ERROR
when getResultStatus reports 'error' on a non-throwing path. Guarded so a
thrown error's specific message is not overwritten by the generic one.
- Session.ts #executeCronPrompt: map caught cron errors to 'error' (was
'cancelled'), so turn_status dashboards no longer miss cron API failures.
- Session.ts runTool success path: compute aborted/status/succeeded once
before emitResult so the client-facing success flag matches telemetry on
abort-induced cancellation (previously emitResult used !toolResult.error).
- Session.ts runTool error paths: errorResponse and the catch-block
recordToolResult now label aborted calls 'cancelled' instead of 'error'.
Tests: withInteractionSpan 'error' status -> span ERROR, and thrown-error
message preserved.
* feat(daemon): clamp oversized inline media on the prompt path (#4646)
* feat(daemon): clamp oversized inline media on the prompt path
Replace inline image/audio/blob payloads exceeding a configurable byte
ceiling (QWEN_CODE_MAX_INLINE_MEDIA_BYTES, default 10MB) with a sanitized
text placeholder via clampInlineMediaPart, wired into
Session.#resolvePrompt so oversized daemon media cannot blow up request
size or token budget. Also advertise audio:true in the HTTP daemon
promptCapabilities to match acpAgent and the actual #resolvePrompt
handling.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): keep fileUri non-null in resolvePrompt path-spec map
clampInlineMediaPart returns the genai Part type, widening the resolved
parts union so fileData.fileUri is optional; assert it where resource_link
file paths are collected (that branch always sets fileUri).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): clamp readManyFiles binary parts on the @file path
The readManyFiles result path pushed non-string contentParts (binary
files from @file references) directly into processedQueryParts without
clamping, bypassing the inline media size guard this PR introduces.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(web-shell): UI improvements, subagent rendering, and scroll-follow rewrite (#4655)
* feat(web-shell): improve UI components and message formatting
- Refine dialog styles, editor layout, and welcome header
- Add tool formatting utilities with tests
- Update message list, shortcuts panel, and agent dialog
- Improve markdown rendering and tool chrome styles
- Enhance input history hook and i18n support
* feat(web-shell): improve /tools, /skills, agents dialog and compact mode
- /tools: show simple list by default, /tools desc opens detail dialog
- /tools, /skills: insert user message before showing results
- AgentsDialog: add onMessage callback for success feedback, add Ctrl+D
shortcut for delete in manage mode, show shortcut hint in detail view
- AgentsDialog create form: add arrow key hint in footer
- ToolsDialog: hide show-details and disable buttons
- DialogPrimitives: enlarge item prefix indicator, add shortcut style
- Fix compact mode dispatching duplicate status messages
- Update i18n descriptions to align with CLI behavior
* feat(web-shell): virtual scrolling, rendering perf, and Shift+Tab approval mode cycling
- Introduce @tanstack/react-virtual for virtualized message list scrolling,
reducing DOM node count for long conversations
- Add WeakMap-based JSON stringify cache and reference equality fast path
in MessageItem memo comparator
- Add useShallowMemo/useStableArray hooks to stabilize pendingApproval,
floatingTodos, and floatingAgents references
- Add Shiki code highlighting LRU cache (128 entries) with synchronous
cache-hit path
- Add custom areToolLinePropsEqual comparator for ToolLine memo and narrow
useEffect deps in ToolGroup
- Align Shift+Tab with CLI: cycle approval modes (plan → default →
auto-edit → auto → yolo) instead of direct allow_always submission
- Auto-approve pending permission on mode change: yolo approves all,
auto-edit approves edit tools only (via toolCall.kind from daemon event)
- Add toolKind field to PermissionRequest extracted from toolCall.kind
- Add auto mode status bar indicator with warning color
- Show auto mode entry notice in message area
- Remove mouse hover interaction on ToolApproval to avoid confusion
with keyboard selection
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* feat(web-shell,webui,sdk): subagent rendering, scroll, and transcript fixes
- Synthesize tool.update in normalizer for Agent permission_request to fix
orphaned sub-tool blocks when daemon skips emitStart
- Rewrite transcriptToMessages to match agent completions by callId instead
of stack order, fixing parallel agent merge/cancel/background scenarios
- Add background agent detection: keep status as pending with no endTime
for agents launched with run_in_background or status:'background'
- Handle cancelled/canceled agent status with proper rawOutput enrichment
(status + reason fields) and display as failed in UI components
- Improve scroll-to-bottom: track programmatic vs user scrolls, use
followBottomSignal from submit, fix auto-scroll sticking on user scroll-up
- Add isNavigating to useInputHistory so ArrowUp/Down prioritizes history
browsing over autocomplete dropdown
- Render Agent tools inline in ToolGroup with summary line (type, description,
tool count, elapsed, tokens, cancellation reason) and expandable SubAgentPanel
- Support sub-tool approval matching: recurse into subTools tree to find
pending approval targets within nested agents
- Add i18n keys for approval options and request.cancelled (EN + ZH)
- Bump base font size from 12px to 14px in App and Markdown
- Add maxBlocks config prop to DaemonSessionProvider
- Increase ActiveAgentsPanel MAX_VISIBLE from 5 to 10
- Add virtualizer getItemKey and useAnimationFrameWithResizeObserver
- Extensive test coverage for transcript conversion edge cases
* refactor(web-shell): rewrite scroll-follow logic with 6 clear rules
Replace the previous scroll implementation (5 overlapping effects,
4 fragile refs, rAF-based programmaticScroll flag) with a clean,
predictable design driven by 6 documented rules:
1. Default follow-bottom on content height changes via single
useLayoutEffect on virtualizer totalSize
2. Scroll-up pauses follow (direction detection in onScroll)
3. Scroll-back-to-bottom (< 30px) resumes follow
4. New user message forces follow on
5. Session restore: suppress scroll during catchingUp, scroll
once on replay_complete transition
6. Short content (no scrollbar): scrollToBottom is a no-op
- Remove followBottomSignal state and handleEditorSubmit wrapper
from App.tsx; pass connection.catchingUp to MessageList instead
- Consolidate from 5 effects to 3, from 4 refs to 3
- Add detailed block comment documenting all 6 rules and the
implementation structure
* fix(web-shell): stabilize daemon transcript rendering
* fix(web-shell): refine agent rendering feedback
* fix(web-shell): address review feedback
* chore(sdk): bump browser bundle size limit to 105KB
The daemon browser SDK bundle grew to ~103KB due to normalizer
enhancements for permission-based subagent rendering.
* fix(web-shell): address review feedback
* fix(web-shell): address review feedback
* fix(webui): avoid duplicate ask user question prompt
* fix(web-shell): sync package lockfile
---------
Co-authored-by: ytahdn <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* fix(infra): enforce SDK/server MCP-restart timeout coupling (#4330) (#4658)
* feat(telemetry): per-prompt traceId for bounded, renderable traces (#4661)
* feat(telemetry): per-prompt traceId — each interaction is a trace root
Previously all spans within a session shared one traceId derived from
SHA-256(sessionId). Long sessions produced unbounded traces that ARMS
and Jaeger could not render. This change makes each interaction span a
trace root with a fresh SDK-generated traceId. Cross-prompt correlation
uses the session.id span attribute (already present on interaction spans,
now stamped on all spans via SessionIdSpanProcessor).
Key changes:
- startInteractionSpan uses ROOT_CONTEXT instead of session root
- withInteractionSpan defaults to ROOT_CONTEXT when no parentContext
- SessionIdSpanProcessor stamps session.id on every exported span
- resolveParentContext / getParentContext simplified (no session root fallback)
- debugLogger falls back to deriveTraceId(sessionId) for log-line grep
- LogToSpanProcessor unchanged (naturally adapts)
- createSessionRootContext marked @deprecated
Closes#4554 (per-prompt traceId sub-item)
* fix: address wenshao review — cache deriveTraceId, remove vestigial try/catch
* fix: guard SessionIdSpanProcessor.onStart with try/catch, clear cache in resetDebugLoggingState
* fix(daemon): btw cross-session leak + timeout + input cap + permission requestId cardinality (#4666)
* fix(daemon): btw cross-session leak + timeout + input cap + permission requestId cardinality
- Remove getCacheSafeParams() fallback that borrows another session's
history when current session has no chat (cross-session leak)
- Fix unreachable timeout branch: check childSignal.aborted instead of
DOMException instanceof (never matched in all Node versions)
- Add BTW_MAX_INPUT_LENGTH (4096) guard on slash-command entry point
(route/ACP already had it; slash command bypassed)
- Use non-curated getHistoryTail(40, false) for btw (read-only, saves
curation overhead)
- Validate permissionRequestId against CLIENT_ID_RE + MAX_CLIENT_ID_LENGTH
before writing to span attribute (unbounded cardinality + control-char
injection risk)
Co-Authored-By: Qwen Code <[email protected]>
* fix: address wenshao review — revert curated flag, parameterize error msg, add length test
- Revert getHistoryTail curated flag to true: extractCuratedHistory
filters invalid model responses (empty parts/text) that would cause
API errors in the btw fork
- Use template literal with BTW_MAX_INPUT_LENGTH in acpAgent error
message instead of hardcoded "4096"
- Add test for question length exceeding BTW_MAX_INPUT_LENGTH in
btwCommand
Co-Authored-By: Qwen Code <[email protected]>
* fix: use BTW_MAX_INPUT_LENGTH in HTTP btw route, add debug log for null cacheSafeParams
- server.ts POST /session/:id/btw: replace hardcoded 4096 with
BTW_MAX_INPUT_LENGTH constant (third entry point missed in prior commit)
- acpAgent.ts: add debugLogger.debug when buildBtwCacheSafeParams
returns null (fresh session / post-compaction observability)
Co-Authored-By: Qwen Code <[email protected]>
---------
Co-authored-by: Qwen Code <[email protected]>
* feat(telemetry): expand daemon telemetry route coverage (#4682)
* feat(telemetry): expand daemon telemetry route coverage and fix trailing-slash handling
- Add telemetry spans for previously uncovered routes: recap, btw, model,
shell, detach, approval-mode, metadata (PATCH), sessions/delete,
workspace/init, and workspace MCP routes (restart, add, delete)
- Fix trailing-slash mismatch: normalize req.path before matching so
requests like `/session/abc/prompt/` produce spans (Express routes them
but the old regex missed them)
- Fix workspace sessions regex: `.+` → `[^/]+` to prevent cross-segment
over-matching
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(telemetry): add missing workspace auth and tools routes
Add telemetry spans for device-flow auth and tool enable routes
that were missed in the initial expansion.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): auto-recover transcript on ring_evicted resync (#4702)
* fix(core): explicitly set stream: false in non-streaming requests (#4703)
* fix(daemon): compacted session replay for long-session recovery (#4694)
* fix(daemon): compacted session replay for long-session recovery
Replace unbounded raw-event replay with turn-boundary compaction.
On each turn_complete, streaming chunks merge into single events,
tool call sequences fold to final state, transient signals drop.
loadSession returns O(turns) compacted events instead of
O(streaming_tokens) raw events.
Key decisions:
- Synchronous snapshot() eliminates watermark vs async-read race
- Slot-based compaction preserves event ordering across types
- liveJournal carries raw events for current incomplete turn
- resume only returns lastEventId (no replay payload)
- All new fields optional for backward compatibility
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor: extract mergeTextSlot helper + add integration tests
Address review suggestions:
- Extract shared mergeTextSlot() for agent_message_chunk/thought_chunk
- Add 4 EventBus+CompactionEngine integration tests covering
snapshotReplay(), liveJournal, and close lifecycle
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: update bridge test assertions for new replay fields
Add compactedReplay/liveJournal/lastEventId to toEqual assertions
in load/resume/attach bridge tests.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: use EVENT_SCHEMA_VERSION constant instead of hardcoded v:1
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: verify SDK replay fields in tests + guard ingest on publish
- Update load/resume test mocks to return lastEventId/compactedReplay/liveJournal
- Verify replaySnapshot population and SSE cursor from server watermark
- Wrap compactionEngine.ingest() in try/catch to maintain BX9_p contract
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: update stale comment and test title for new watermark semantics
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(web-shell): complete inline terminal command UI (#4710)
* fix(web-shell): refine input and tool display
* fix(web-shell): align permission approval display
* feat(web-shell): add inline insight progress, slash command UI, and auto-scroll fix
- Parse insight protocol JSON from ACP session into typed messages
(insight_progress / insight_ready) and render inline progress bar
with spinner matching CLI display
- Consolidate multiple progress updates to show only the latest;
hide progress bar once the report is ready
- Add slash command message rendering: /stats, /model, /memory,
/mcp, /agents, /btw, /status, /user-shell with dedicated cards
- Fix auto-scroll breaking when tool cards, SubAgent panels, or
TodoList cards appear by adding scroll cooldown mechanism
- Extend daemon SDK with agent management and MCP workspace APIs
- Add slash command completions with inline descriptions
* fix(web-shell): align inline command panels
* fix(web-shell): constrain btw panel height
* fix(web-shell): address PR review feedback
- Add insight_error protocol type to stop spinner on generation failure
- Fix insight_ready id duplication with per-segment counter
- Add useEffect cleanup for McpStatusMessage panel active dispatch
- Extend MCP OAuth authenticate timeout to 10 minutes
- Add TODO for process-wide metrics limitation in stats
- Fix AbortController misleading try/finally in ACP agent generation
- Add appendLocalUserMessage to /btw and /bug handlers
- Add popup blocker check for /bug window.open
- Add try/catch + dispatchActionError to getStats()
- Replace raw addEventListener with useDelayedGlobalKeyDown in MCP panel
- Return generic error in workspaceAgents 500 response
- Align description length validation (4096 chars) at HTTP layer
- Restore isUserShell to use isShellToolName() for expand button
- Use per-server try/catch in /mcp to allow partial failure
- Remove unimplemented /mcp completion subcommands
- Translate btw.empty to Chinese
- Increase virtualizer overscan from 5 to 20
* fix(web-shell): expose CLI version in daemon capabilities
The web-shell previously used a hardcoded version constant.
Pass the resolved CLI package version through the capabilities
envelope so clients can display the actual daemon version.
* fix: address PR review feedback for web-shell and webui
- Fix window.open returning null due to noopener flag (App.tsx)
- Use Buffer.byteLength for description length check (workspaceAgents.ts)
- Remove stale MCP subcommands from EN slash tree (slashCompletion.ts)
- Increase MCP action timeout from 30s to 5min (workspace/actions.ts)
- Add counter to insight_error id for uniqueness (transcriptToMessages.ts)
- Remove duplicate error reporting in /stats handler (App.tsx)
- Fix CSS variable name --color-error to --error-color (MessageItem.tsx)
- Remove duplicate echo in /btw command (App.tsx)
---------
Co-authored-by: ytahdn <[email protected]>
* feat(telemetry): enrich llm_request span with response metadata and error details (#4693)
Add 6 new attributes to qwen-code.llm_request OTel spans that were
previously only available in log events (ApiResponseEvent), closing
the observability gap that blocked cross-system debugging (e.g.
correlating qwen-code traces with DashScope request logs).
New span attributes (with GenAI semconv duals where applicable):
- response_id / gen_ai.response.id — provider request ID
- finish_reason / gen_ai.response.finish_reasons — model stop reason
- thoughts_token_count / gen_ai.usage.reasoning_tokens — reasoning tokens
- subagent_name — originating subagent
- error_type / error.type — structured error classification
- error_status_code — HTTP status from provider errors
Implementation details:
- Extend LLMRequestMetadata with 6 new optional fields
- Track lastFinishReason and lastError as closure variables in the
streaming path (consolidatedResponse is try-scoped, inaccessible
from finally)
- Capture subagentName eagerly at method entry to avoid AsyncLocalStorage
context loss in setTimeout/finally
- Update all 5 endLLMRequestSpan call sites with appropriate field subsets
- gen_ai.response.finish_reasons emitted as string[] per OTel semconv
* fix: add missing TelemetryRuntimeConfig methods and remove obsolete test (#4730)
- Add isInteractive() and getOutboundCorrelationPropagateTraceContext()
to TelemetryRuntimeConfig interface (required by sdk.ts)
- Add implementations in createDaemonTelemetryRuntimeConfig
- Remove httpAcpBridge.test.ts (tests moved to acp-bridge/bridge.test.ts)
These fixes were applied in the initial merge resolution but lost when
the merge commit was recreated with proper two-parent structure.
* fix: add missing isForkSubagentEnabled from main merge (#4731)
Add isForkSubagentEnabled() to Config class and fork-subagent.ts,
brought in by main but lost during merge conflict resolution.
* fix(daemon): isolate parallel subAgent text streams in transcript reducer (#4689)
* feat(web-shell): polish embedded terminal interactions (#4759)
Co-authored-by: ytahdn <[email protected]>
* fix(web-shell): 修复 ring-eviction 重连逻辑 (#4752)
* fix(bridge): extract detailed error from JSON-RPC error objects in turn_error
ACP SDK rejects prompt failures with a plain JSON-RPC error object
({ code: -32603, message: "Internal error", data: { details: "..." } })
instead of an Error instance. broadcastTurnError used String(err) for
non-Error values, producing "[object Object]" in turn_error events.
- Add extractErrorMessage/extractErrorCode helpers that read
data.details from JSON-RPC error objects before falling back to
message or String()
- Remove "Prompt failed" prefix from sendPrompt error dispatch in
webui actions so the raw error message is shown
- Prevent duplicate error display in web-shell by marking errors
already dispatched by sendPrompt with _alreadyDispatched sentinel
* fix(web-shell): improve auto-scroll, thinking rendering, model picker UX, and ring-eviction resync
- Fix auto-scroll breaking when TodoPanel or ActiveAgentsPanel appears/disappears.
Remove early return in handleScroll Rule 2 so Rule 3 (near-bottom check) always
runs, preventing container-resize-induced scrollTop clamping from permanently
disabling follow mode. Add ResizeObserver on the scroll container to snap back
to bottom on resize while following.
- Render thinking content as Markdown instead of raw pre-formatted text, with
proper styling for paragraphs, lists, blockquotes, and code blocks.
- Model picker keyboard navigation now wraps around; removed hover-driven
selection to avoid fighting arrow-key navigation.
- Session picker dialog layout fixes: prevent text overflow with flex/min-width
constraints and nowrap on badges.
- Ring-eviction resync now reloads the full session snapshot (compactedReplay +
liveJournal) instead of continuing on a partial SSE tail, ensuring the
transcript is fully rebuilt after a gap.
- Add test for compacted replay subagent content staying scoped to its parent
agent instead of overflowing to the top-level transcript.
* fix(webui): keep parented subagent replay content nested
* fix(webui): address daemon session review feedback
* fix(daemon): finalize replay and subagent text state
* fix(webui): harden replay snapshot recovery
* chore(sdk): update daemon browser bundle budget
* fix(webui): avoid duplicate replay snapshot injection
* fix(webui): harden replay snapshot recovery
* fix(webui): settle replay recovery edge cases
* fix(webui): address remaining review followups
* fix(webui): preserve replay tail on truncation
* fix(webui): keep replay snapshots complete
* fix(webui): ignore unbound replay prompt settlements
---------
Co-authored-by: ytahdn <[email protected]>
* fix(daemon): preserve parentToolCallId in compaction engine for parallel subagent streams (#4765)
* fix(daemon): preserve parentToolCallId in compaction engine for parallel subagent streams
TurnBoundaryCompactionEngine.mergeTextSlot merged all consecutive
agent_thought_chunk / agent_message_chunk events into a single slot
regardless of parentToolCallId, destroying per-subagent attribution.
When 9+ parallel subagents streamed concurrently, the compacted replay
contained garbled text with no parentToolCallId — the downstream
transcript reducer (fixed in #4689) could not route blocks to the
correct subagent tool call.
- Add parentToolCallId-aware dual-path merging: subagent chunks use an
indexed lookup (textSlotIndex) to merge by (kind, parentToolCallId)
even when interleaved; top-level chunks preserve the original
consecutive-only merge to maintain text segmentation around tool calls.
- Evict textSlotIndex entries when a same-parent tool_call arrives,
mirroring the transcript reducer's clearActiveText(parentToolCallId)
so compacted replay block segmentation matches live behavior.
- Defensive backfill: ensure parentToolCallId survives in the compacted
event's _meta even if the last chunk's _meta lost it.
- Harden seed() to clear in-flight state (slots, indexes, liveJournal).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): rename misleading test to match actual behavior
Copilot review correctly noted the "defensive backfill" test name
was inaccurate — it actually tests that chunks without
parentToolCallId separate into the top-level path.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address wenshao review — bracket notation, eviction scope, backfill tests
- Use bracket notation for _meta access in test helpers (TS4111 fix)
- Move textSlotIndex eviction into the new-tool-only branch so
tool_call_update does not over-segment subagent text
- Add tests for meta backfill and tool_call_update non-eviction
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(daemon): add seed() slot cleanup coverage per wenshao review
Verify that seed() clears in-flight slots, liveJournal, and index
maps so stale pre-seed data does not leak into post-seed compaction.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address wenshao review round 3 — remove fallback, reword comment, add thought eviction test
- Remove dead parentToolCallId fallback in tool eviction (emitters
always use _meta), aligning with mergeTextSlot extraction
- Reword eviction comment to be self-describing
- Add thought slot eviction test coverage
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor(daemon): remove unreachable meta backfill, rename tests
The defensive parentToolCallId backfill in compactCurrentTurn was
unreachable: the routing invariant in mergeTextSlot guarantees that
any chunk reaching the subagent path has parentToolCallId in _meta,
so slot.lastMeta always contains it. Remove the dead code and rename
tests to describe what they actually verify.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(daemon): optimize ACP child lifecycle — skip relaunch, preheat, idle keep-alive (#4751)
* feat(daemon): optimize ACP child lifecycle — skip relaunch, preheat, idle keep-alive (#4748)
Three optimizations to reduce daemon cold start latency and improve
session throughput:
1. Skip unnecessary relaunchAppInChildProcess for ACP children by
setting QWEN_CODE_NO_RELAUNCH=true, eliminating a redundant
grandchild process spawn. Memory args (--max-old-space-size)
are passed directly with container-aware cgroup detection.
2. Pre-spawn ACP child at daemon boot via bridge.preheat(), so the
first session doesn't pay cold-start latency. Fire-and-forget
with fallback to lazy spawn on failure.
3. Add --channel-idle-timeout-ms flag to keep ACP child alive after
last session closes, avoiding cold restart on reconnect. Default
0 (immediate kill) preserves backward compatibility.
Also adds daemon-vs-CLI benchmark test suite and report.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address Copilot review — preheat idle bug, TS cast, JSDoc
- Fix preheat() immediately killing the preheated channel when
channelIdleTimeoutMs=0 (default). Preheat now leaves the channel
alive for the first session; idle timer is only armed by session
close paths.
- Cast process.constrainedMemory via typed intermediate to avoid
tsc errors on @types/node versions without the declaration.
- Add JSDoc to ServeOptions.channelIdleTimeoutMs.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address wenshao review — TS errors, await semantics, preheat idle
- Remove unused __dirname + fileURLToPath (TS6133)
- Fix body?.code → body?.['code'] for index signature (TS4111)
- Fix lastEventId: '0' → 0 type mismatch (TS2322)
- Restore await semantics for channel kill in timeout=0 path
- Preheat conditionally arms idle timer when channelIdleTimeoutMs > 0
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address wenshao review — idle timer logging, remove default, add unit tests
- Add stderr breadcrumb before idle timer kills channel, distinguishing
idle-timeout reap from unexpected SIGTERM/crash
- Remove `default: 0` from --channel-idle-timeout-ms to match sibling
options (prompt-deadline-ms, writer-idle-timeout-ms) that use
undefined-when-unset
- Export getAcpMemoryArgs for direct testing
- Add unit tests: channelIdleTimeoutMs lifecycle (immediate kill,
warm channel reuse during idle window), preheat (channel reuse,
shutdown guard), getAcpMemoryArgs (boundary conditions, 16GB cap)
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address wenshao review round 2 — preheat test safety, cache memory args
- Skip preheat when bridge is test-injected (deps.bridge) to avoid
in-flight ensureChannel blocking test shutdown
- Cache getAcpMemoryArgs() result — os.totalmem() and cgroup reads
are constant for the daemon's lifetime
- Correct preheat savings estimate in benchmark report (0-0.5s
depending on session arrival timing, not 0.3-0.5s)
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* chore: move benchmark report to DingTalk doc
Report moved to:
https://alidocs.dingtalk.com/i/nodes/YMyQA2dXW7gYo6Mzc5nYdp7GWzlwrZgb🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(test): increase CLI cold start benchmark timeout
The -p mode startup profiler test runs 6 iterations of full CLI
initialization (~20s each), exceeding the previous 105s timeout.
Increase to 210s.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* refactor: simplify preheat call — drop unnecessary Promise.resolve() wrapper
bridge.preheat() is async, so synchronous throws are already wrapped
in a rejected promise. The Promise.resolve().then() indirection added
no safety and confused readers about what edge case it guarded.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): compare against V8 heap limit, not hardcoded 2048MB threshold
On Node 22+, the default V8 heap limit is ~4.2GB, not ~2GB. The
previous `targetMB > 2048` check would set --max-old-space-size to
a value lower than the default on 5-8GB hosts, causing a regression.
Now compares against the actual V8 heap_size_limit via
v8.getHeapStatistics(), matching the approach used by
getNodeMemoryArgs() in gemini.tsx.
Also adds --max-sessions 0 to warm session and memory baseline
benchmark tests to prevent session_limit_exceeded on heavy mode.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address wenshao review — idle timer fake-timer tests, reuse assertions, boot validation
- Add vi.useFakeTimers() tests verifying channel kill after idle expiry
and timer cancellation on new session arrival
- Add factory call counters to idle keep-alive and preheat tests to
prove channel reuse (not respawn)
- Add handle.killed assertion to immediate-kill test
- Remove noisy stderr log on default timeout=0 path
- Add channelIdleTimeoutMs boot-time validation in runQwenServe
- Fix getAcpMemoryArgs test to not assume os.totalmem() matches
process.constrainedMemory() in container environments
- Update benchmark description to reflect preheat behavior
* fix(daemon): address wenshao review round 4 — context in kill log, preheat+idle test
- Add context parameter to killChannelWithLog/startIdleTimer so
kill-failure logs include the sessionId that triggered the kill
- Add factoryCalls assertion to preheat "no-op after shutdown" test
- Add preheat + channelIdleTimeoutMs interaction test (fake timers):
preheat arms idle timer, first session cancels it, closeSession
re-arms it, channel killed after expiry
* fix(daemon): use 'idle timeout' context in timer-expiry kill log
The idle timer callback captured the arming context (e.g. closeSession
"abc123") instead of identifying the idle-timeout expiry as the cause.
* chore: remove redundant and dead comments across codebase (#4776)
* chore: remove redundant and dead comments across codebase
Remove comments that restate code, commented-out debug leftovers,
and verbose restatements across 11 files. "Why" comments and
business-rule explanations are retained. No functional changes.
Files changed:
- ControlDispatcher.ts: commented-out HookController scaffolding
- sharedTokenManager.ts: commented-out console.debug
- sandbox.ts: commented-out stdout pipe blocks → concise comments;
empty if-block with commented-out warn removed
- ideContext.ts: 3 "what" comments restating code
- ide-client.ts: 3 redundant comments, catch comment condensed
- mcp-tool.ts: permission rule, isMCPToolError, error check comments
- settings.ts: ENOENT/validation/env-override restatements
- github.ts: checkout/ref restatements condensed
- validation.ts: 15 validation step labels
- languageCommand.ts: section headers restating function calls
- arenaCommand.ts: regex restatement
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* chore(cli): remove stale hook controller comments
---------
Co-authored-by: 衍星 <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
* refactor(daemon): simplify code and strip PR/commit references from comments (#4774)
* feat(telemetry): add daemon OTel metrics and structured log records (#4749)
* feat(telemetry): add daemon OTel metrics and structured log records
Adds 11 OTel metric instruments to the daemon serve path, covering:
- HTTP request count/latency by route and status class
- Session lifecycle (spawn/close/die) counter
- Channel lifecycle (spawn/exit) counter
- Prompt queue wait and end-to-end duration histograms
- Bridge error counter with normalized error type allowlist
- Cancel request counter
- ObservableGauges for active sessions, SSE connections, heap usage
Key design decisions:
- ObservableGauge (not UpDownCounter) for gauge-like values — immune to
+1/-1 drift across complex lifecycle paths
- Error type normalization via allowlist (19 known types + 'unknown')
prevents unbounded cardinality
- Explicit histogram bucket boundaries tuned for daemon latency profiles
- Bridge decoupled via BridgeTelemetry.metrics optional sub-object
- emitDaemonLog generalized with optional eventName/severityNumber
- service.instance.id added to Resource for process incarnation detection
- Pre-shutdown forceFlushMetrics for best-effort final metric export
Closes#4554 §6.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): address Copilot review on daemon metrics
- service.instance.id now serves as a fallback default rather than
unconditional override, so operators can set a stable instance id
via telemetry.resourceAttributes
- channelLifecycle('spawn') log no longer carries the misleading
'expected' attribute (only meaningful for 'exit' events)
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): address wenshao review — deduplicate interface + shutdown die metric
- BridgeTelemetryMetrics now re-exports DaemonBridgeTelemetryMetrics
from core instead of duplicating the interface definition
- Add sessionLifecycle('die') in bridge shutdown loop so sessions
alive at daemon shutdown are counted in the lifecycle counter
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): address Codex review — isDying channel + test mock diag
- channelExitExpected now checks info.isDying in addition to
shuttingDown, so deliberate channel kills from closeSession/
killSession are correctly recorded as expected=true
- Add diag stub to the @opentelemetry/api mock in daemon-metrics
tests for robustness
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): address wenshao CHANGES_REQUESTED — 5 fixes
- [Critical] forceFlushMetrics: void → await to prevent race with
shutdownTelemetry tearing down the metric reader mid-flush
- registerDaemonGaugeCallbacks: add idempotency guard (gaugesRegistered)
to prevent duplicate ObservableGauge callbacks on re-entry
- activeSseCount: add double-fire guard to prevent negative counter
from abnormal close events
- Non-null assertions (!) → optional chaining (?.) on all recording
functions for resilience against SDK misconfiguration
- expected ?? true vs !expected severity logic: use explicit
expected === false to avoid contradictory signals when undefined
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): address wenshao R2 — TS1308, flush timeout, gauge test
- [Critical] Fix TS1308: await inside non-async Promise executor.
Restructured to .then() chain so forceFlushMetrics completes
before bridge.shutdown() starts, without requiring async executor.
- forceFlushMetrics: add 5s timeout via Promise.race to prevent
indefinite blocking on unreachable OTLP collector.
- Add idempotency test for registerDaemonGaugeCallbacks.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): clear timeout timer after forceFlushMetrics race settles
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): address remaining wenshao suggestions
- sessionLifecycle('die') no longer emits ERROR severity — unexpected
exits are already covered by channelLifecycle('exit', false) WARN
- gaugesRegistered = true moved to end of registerDaemonGaugeCallbacks
for consistency with initializeDaemonMetrics and retry resilience
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(telemetry): address wenshao review round 4
- Add flush.catch() in forceFlushMetrics to prevent unhandled rejection
when timeout wins the Promise.race (sdk.ts)
- Fix log body inconsistency: use expected ?? true to match attribute
(runQwenServe.ts)
- Guard channelLifecycle('exit') with handshakeComplete flag to prevent
exit count exceeding spawn count on handshake failures (bridge.ts)
* fix(telemetry): reduce forceFlushMetrics timeout from 5s to 2s
Keeps worst-case shutdown budget under Kubernetes default 30s grace
period. Healthy daemon flushes in <100ms; 2s is sufficient headroom.
* refactor(telemetry): use direct function references for pass-through metric wrappers
* feat(web-shell): organize slash command completion (#4792)
Co-authored-by: ytahdn <[email protected]>
* refactor(serve): extract DaemonWorkspaceService from AcpSessionBridge (issue #4542, 方案 C) (#4563)
* feat(web-shell): add daemon dev launcher (#4799)
Co-authored-by: ytahdn <[email protected]>
* feat(cli): enable /remember, /forget, /dream in ACP mode (#4819)
* feat(cli): enable /remember, /forget, /dream in ACP mode
These three memory-related slash commands return `submit_prompt` or
`message` action types which are fully supported by the ACP session
handler. Adding `acp` to their `supportedModes` allows web-shell
clients to invoke them via `POST /session/:id/prompt` passthrough.
Changes:
- /remember: add supportedModes (zero handler changes needed)
- /forget: add supportedModes + wrap memory manager calls in try-catch
so filesystem/model errors surface as user-friendly messages instead
of raw JSON-RPC errors
- /dream: add supportedModes + document that onComplete callback
(dream metadata tracking) is not invoked in ACP mode
Known limitation: /dream's onComplete (writeDreamManualRun) is silently
skipped in ACP — the auto-dream scheduler may not know a manual dream
already ran. Accepted because eagerly calling it would record completion
before consolidation actually finishes.
Refs #4514
* fix: address wenshao review — eager writeDreamManualRun + toEqual assertions
- Call writeDreamManualRun eagerly before returning submit_prompt so
auto-dream dedup works correctly in ACP mode (timestamp is slightly
early but acceptable for scheduler min_hours check)
- Switch supportedModes test assertions from toContain to toEqual per
codebase convention (catches accidental mode additions)
Refs #4514
* fix: address wenshao review round 2
- dreamCommand: add try-catch for error resilience in ACP; make eager
writeDreamManualRun conditional on executionMode === 'acp' to avoid
double-write in interactive mode and cancel-semantics regression
- rememberCommand: add explicit if (!config) guard (consistency with
dream/forget; avoids silent fallthrough in ACP)
- Add config:null test for rememberCommand
- Split dream test into interactive (no eager write) vs ACP (eager write)
Refs #4514
* fix: fire-and-forget recordDream in ACP mode to avoid blocking prompt
Refs #4514
* fix: add argumentHint to /remember and /forget for ACP command palette
Without argumentHint, ACP clients advertise these commands as taking no
input, so users can't provide the required text argument.
Refs #4514
* fix: split ACP/interactive return paths in dreamCommand, add rejection test
- ACP mode returns without onComplete (eliminates double-execution risk
if someone later propagates onComplete in handleCommandResult)
- Add test for writeDreamManualRun rejection (verifies .catch prevents
unhandled promise rejection)
- Add return value + no-onComplete assertions to ACP test
Refs #4514
* feat(serve): add HTTP rewind endpoints for daemon/web-shell (issue #4514 T3.2) (#4820)
* feat(serve): add HTTP rewind endpoints for daemon/web-shell (issue #4514 T3.2)
Expose session rewind as structured HTTP API so web-shell and SDK
clients can rewind a session's conversation and files to a previous
turn without relying on TUI-only dialog interaction.
API surface:
- GET /session/:id/rewind/snapshots — list rewindable turns with diff stats
- POST /session/:id/rewind — execute file restore + conversation truncation
Leverages the existing Session.rewindToTurn() for conversation
truncation and FileHistoryService.rewind() for file restore. Extends
the existing 'rewindSession' ACP extMethod to also support promptId
parameter and file history rewind.
Error handling:
- 409 SessionBusyError when a prompt is running
- 400 InvalidRewindTargetError when the target turn is compressed or
does not exist
- 404 SessionNotFoundError for unknown sessions
Cross-client SSE event 'session_rewound' published on success with
originatorClientId for echo suppression.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): update tests, align turnIndex semantics, restore comment
Fixes from final audit:
- acpAgent.test.ts: add filesChanged/filesFailed to expected response,
add newSession call before invalid-turnIndex test
- server.test.ts: add session_rewind to expected feature lists
- acpAgent.ts: make snapshot turnIndex 0-based (consistent with
rewind response targetTurnIndex)
- server.ts: restore accidentally deleted comment on
RestoreInProgressError handler
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): use snapshot array position for turnIndex, add errorKind to format errors
Two Codex review fixes:
1. After a rewind, Session.turn remains monotonic so promptId suffixes
no longer correspond to actual turn positions. Use the snapshot's
index in FileHistoryService.getSnapshots() instead of parsing the
suffix — the array is always in sync with the current conversation.
2. Format validation errors (invalid prefix, non-numeric suffix) now
carry errorKind: 'invalid_rewind_target' so the bridge maps them
to 400 instead of falling through to 500.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address wenshao review — filesFailed in event, error surfacing, telemetry route
Fixes from wenshao's CHANGES_REQUESTED review:
1. Add filesFailed to session_rewound SSE event payload so
subscribers can detect partial file restoration failures
2. Surface file rewind errors in filesFailed array instead of
silently swallowing them
3. Add SESSION_ID_RE validation to sessionRewindSnapshots handler
4. Add 'rewind' to resolveDaemonTelemetryRoute regex
5. Update DaemonSessionRewoundData type and isSessionRewoundData
guard to include filesFailed
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): add debugLogger to file rewind catch, deduplicate response extraction
wenshao R3 fixes:
1. Add debugLogger.error for file-history rewind failures so oncall
has log breadcrumbs for partial-rewind incidents
2. Extract response fields once and reuse in both event + return
3. Fix rewound boolean: false when filesFailed is non-empty
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(cli): enable /directory command in ACP mode (#4826)
* feat(cli): enable /directory command in ACP mode
Refactor /directory (show/add) from addItem-based output to returning
MessageActionReturn so it works in ACP mode (web-shell).
Changes:
- Add supportedModes: ['interactive', 'acp'] to parent + both subcommands
- Add argumentHint to add subcommand for command palette
- Add parent action returning usage hint for bare /directory invocation
- Refactor show: return message instead of addItem
- Refactor add: collect all outputs into messages array, return single
message (messageType: 'error' if any errors, 'info' otherwise)
- Add try-catch outer wrapper for unexpected errors
- Simplify pathsToAdd parsing (remove no-op split-join)
- Update existing .tsx tests to assert on return values instead of addItem
- Add new .ts test file with 11 tests covering ACP paths
Known limitations:
- Mixed success+error returns use messageType: 'error' for the whole
message (single MessageActionReturn can't express mixed severity)
- Cross-session: directory add is session-scoped, other sessions see
the change after restart (pre-existing architectural property)
Refs #4514
* fix: address Copilot review — usage hint format and conditional QWEN.md message
1. Usage hint now shows comma-separated format: `<path>[,<path>,...]`
2. QWEN.md files success message only emitted when memory refresh actually runs
* fix: address wenshao review — partial-success warning, gemini try-catch, test consolidation
1. Use messageType 'warning' for partial success (some paths added, some failed)
instead of 'error' which throws in ACP mode via Session.ts
2. Wrap gemini.addDirectoryContext() in its own try-catch to prevent losing
accumulated success messages on failure
3. Consolidate duplicate .test.ts into .test.tsx, add space-in-path test,
add settings.setValue assertion for mixed-result scenario
4. Delete redundant directoryCommand.test.ts
* fix: add missing test coverage for gemini try-catch and null-config guards
1. Add test for addDirectoryContext() rejection → messageType 'warning' + error message
2. Restore null-config tests for both show and add subcommands (lost during consolidation)
* feat(serve): add hooks diagnostic HTTP/ACP surface (issue #4514 T3.9) (#4822)
* feat(serve): add hooks diagnostic HTTP/ACP surface (issue #4514 T3.9)
Add read-only endpoints for hook configuration status, enabling remote
clients (web-shell, SDK consumers) to query workspace and session hooks.
- GET /workspace/hooks — config-sourced hooks (user/project/extensions)
- GET /session/:id/hooks — runtime session hooks (skill-registered)
Wiring: status types + idle factory (acp-bridge), bridge interface +
impl, ACP agent builders + extMethod dispatch, workspace-service facade,
REST routes, capability tags, SDK types + client methods, barrel exports.
Slash command /hooks enabled for ACP mode (text output via listCommand).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(sdk): use DaemonHookEventName for DaemonHookEntry.eventName
Copilot review feedback: DaemonHookEventName was defined but not used
on the entry type, so SDK consumers got plain `string` without
autocomplete/narrowing. Now uses the forward-compat union type.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address wenshao review on hooks endpoints
- Fix HookEventName import to type-only (ESLint consistent-type-imports)
- Add workspace_hooks + session_hooks to EXPECTED_STAGE1_FEATURES test array
- Set initialized: false in catch block (was true, contradicted errors cell)
- Add try/catch to buildSessionHooksStatus (matching workspace pattern)
- Consolidate HOOK_MATCHER_KINDS + HOOK_EVENT_DESCRIPTIONS into
IDLE_HOOK_EVENTS (single source of truth, exported from status.ts)
- Use conditional spread for session hook matcher field (consistency)
- Bump SDK browser bundle size limit 106KB → 108KB for new hook types
- Add fakeBridge stubs for getWorkspaceHooksStatus/getSessionHooksStatus
- Add hooks types to serve barrel exports
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): correct test feature array ordering for hooks capability tags
Codex review caught that workspace_hooks and session_hooks in
EXPECTED_STAGE1_FEATURES would appear before conditional tags in the
EXPECTED_REGISTERED_FEATURES spread, mismatching the registry
declaration order. Filter them from the spread and append at the
correct position (after non_blocking_prompt, matching the registry).
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* test(serve): add supertest assertions for hooks diagnostic routes
Add FakeBridgeOpts + call counters for workspaceHooksImpl / sessionHooksImpl
and happy-path supertest assertions for GET /workspace/hooks and
GET /session/:id/hooks, matching the pattern of existing diagnostic endpoints.
* fix(test): wire hooks dispatch in queryWorkspaceStatus and fix event description
queryWorkspaceStatus in fakeBridge was missing the
qwen/status/workspace/hooks case, causing it to fall through to idle()
which returns all 18 events. Also fixes description string to match
IDLE_HOOK_EVENTS ('Before tool execution', not 'Before a tool is executed').
* fix(sdk): use route placeholder in sessionHooks failOnError label
Aligns with the codebase convention of using ':id' placeholder instead
of interpolating the actual sessionId value into error labels.
* feat(serve): add extensions diagnostic HTTP/ACP surface (issue #4514 T3.9) (#4832)
* feat(serve): add extensions diagnostic HTTP/ACP surface (issue #4514 T3.9)
Add read-only `GET /workspace/extensions` endpoint exposing installed
extension status with capability summaries. Follows the hooks pattern:
status types + idle factory in acp-bridge, builder in acpAgent, workspace-
service facade, REST route, SDK client method, and capability tag.
- ServeExtensionEntry with id, name, version, isActive, capabilities
(mcpServerCount, skillCount, etc.), redacted source URL
- /extensions slash command enabled in ACP/non_interactive mode with
text-based list subcommand
- DaemonClient.workspaceExtensions() SDK helper
- workspace_extensions capability tag (always-on)
* fix(cli): address Copilot review on extensions list command
- Remove install hint from empty-state message (install is interactive-only)
- Cache Object.keys(ext.mcpServers) count to avoid duplicate computation
* chore: remove stale issue reference from section comment
* fix(cli): guard interactive-only extension subcommands in ACP mode
parseSlashCommand descends into subCommands without checking
supportedModes, so /extensions install and /extensions explore could
execute in ACP mode despite declaring interactive-only. Add runtime
mode guards to installAction, exploreAction, and listAction (manage
dialog) to prevent side effects in non-interactive modes.
* fix(cli): address wenshao review on extensions command
- Fix TS2322: use string literal 'info'/'error' instead of MessageType
enum for SlashCommandActionReturn messageType field
- Wrap user-facing strings in t() for i18n consistency
* fix: rename _args to args in listAction (wenshao review)
Parameter is used — passed to listTextAction. Remove misleading
underscore-prefix convention.
* fix: resolve TS7030 inconsistent return paths in extensionsCommand
exploreAction and installAction return a message object on the
non-interactive guard but void on other paths. Add explicit
return undefined at function end to satisfy noImplicitReturns.
* fix: add try/catch around getExtensions() in listTextAction
Defensive error handling consistent with the ACP builder pattern.
* feat(serve): add /settings slash command for web-shell (#4816)
* feat(serve): add GET/POST /workspace/settings for web-shell settings dialog
Add full-stack settings CRUD across daemon API, SDK, React hooks, and
web-shell UI, closing the /settings gap tracked in #4514 T3.9.
Daemon: GET/POST /workspace/settings with showInDialog allowlist,
server-side type validation, conditional workspace_settings capability,
and settings_changed event broadcasting.
SDK: DaemonClient methods, types, event normalization
(settings_changed → workspace.settings.changed).
React: useDaemonSettings hook with event-driven reload via
settingsVersion signal in DaemonSessionProvider.
Web-Shell: SettingsDialog with category grouping, scope switching,
inline editing, sub-dialog delegation, restart notifications, and
full i18n (EN + ZH-CN).
* fix(web-shell): address Copilot review on SettingsDialog type safety
- Use explicit boolean comparison (=== true) instead of truthiness for unknown values
- Fix Number('') = 0 bug: reject empty/whitespace input before Number conversion
- Use Number.isFinite for client-side validation (matches server-side)
* chore: trigger bot re-check after PR body template update
* fix(serve): fix test drift and default value fallback in settings API
- Add workspace_settings conditional capability branch to server.test.ts
drift-insurance test (prevents CI failure)
- Fall back to schema default when effective value is undefined in
GET /workspace/settings (fixes first-toggle bug for default-true booleans)
* fix(serve): address wenshao review — scope restriction, restart message, and hardening
- Restrict POST /workspace/settings to workspace scope only (remove user scope)
- Fix requiresRestart message being cleared by useEffect (track restartPending state)
- Remove explicit reload() — let SSE event-driven reload handle it (fixes double reload)
- Add busyKey guard to prevent double-submit during save
- Add string max length validation (1024 chars)
- Sanitize error messages — don't leak filesystem paths in HTTP responses
- Remove corruptedPath from GET response — only return recovered boolean
- Extract shared getAllowedKeys() to deduplicate filter logic
- Replace scopeToEnum with explicit SCOPE_MAP
- Separate persist and broadcast try/catch blocks
- Add settings_changed case to asKnownDaemonEvent and reducer
- Add workspace_settings to EXPECTED_REGISTERED_FEATURES test array
* fix(serve): address wenshao review round 2
- Define DaemonSettingsChangedEvent type and add to KnownDaemonEvent union
- Add workspace.settings.changed case to terminal.ts and transcript.ts exhaustive switches
- Move restartPending useState declaration before useEffect that references it
- Fix scope error message to match VALID_WRITE_SCOPES contents
* refactor(serve): simplify settings code per review agents
- formatValue now calls resolveValue instead of duplicating scope lookup
- Collapse intermediate groups memo into single rows memo
- Pass cached allowedKeys to buildSettingsResponse (avoid per-GET recomputation)
- Remove dead user entry from SCOPE_MAP (only workspace is accepted)
* fix(serve): align workspace_settings position in EXPECTED_REGISTERED_FEATURES
Move workspace_settings to match its registry declaration order (after
workspace_tool_toggle, before workspace_init). Filter and re-insert
workspace_init, workspace_mcp_restart, session_recap, session_btw to
maintain Object.keys order alignment.
* fix(serve): address wenshao R3 review — scope guard, restartPending reset, error context
- Disable editing in user scope (handleAction returns early when scope !== 'workspace')
- Reset restartPending at start of handleSetValue to allow message auto-clear
- Add key/scope/workspace context to persist and broadcast error logs
- Replace SCOPE_MAP[scope]! non-null assertion with explicit guard
* fix(serve): address wenshao R4 review — scope type, edit click guard, bundle limit
- Narrow SDK scope type to 'workspace' only (server rejects 'user')
- Guard handleAction against clicks during edit mode (prevents data loss)
- Dismiss editMode when clicking a different setting row
- Bump MAX_DAEMON_BROWSER_BUNDLE_BYTES to 107*1024 for new exports
* fix(serve): address wenshao R5 — actions.ts scope type, selectedIdx init
- Narrow actions.ts setWorkspaceSetting scope to 'workspace' (missed in R4)
- Initialize selectedIdx to 0 instead of 1 for empty-settings safety
* fix(web-shell): show read-only message when acting in user scope
Addresses R5 suggestion: Tab-toggled user scope silently no-ops on
action attempts. Now shows "User-scope settings are read-only" message.
* fix(web-shell): address wenshao R6 — scope type literal, restartPending preservation
- Pass literal 'workspace' to setValue (fixes tsc build failure)
- Only clear restartPending/message when new save doesn't require restart
* fix(web-shell): address R7+R8 review — restartPending, busyKey click guard, selectedIdx
- Remove else-branch that unconditionally cleared restartPending when
saving a non-restart setting (R7 Critical)
- Add busyKey guard to onClick handler matching keyboard handler (R7)
- Fix selectedIdx=0 highlighting category header on mount — effect now
advances to first setting row (R7)
- Use ref for selectedIdx in useDelayedGlobalKeyDown to avoid
re-registering listener on every arrow key press (R8)
- Bump MAX_DAEMON_BROWSER_BUNDLE_BYTES to 112*1024 with margin (R8 Critical)
* fix(serve): address post-approval suggestions — editMode stuck, type cast, approvalMode deny-set
- Clear editMode when setting disappears from rows during SSE reload
- Use isRecord guard instead of unsafe type cast in normalizeSettingsChanged
- Add SECURITY_SENSITIVE_SETTINGS deny-set to block tools.approvalMode
from generic write path (must go through trust-gated session route)
- Remove tools.approvalMode from SUB_DIALOG_KEYS (no longer in list)
* fix(daemon): enable auto-title generation for ACP (daemon) sessions (#4836)
The automatic session title generation was silently disabled for all
daemon sessions. The guard in `maybeTriggerAutoTitle` checks
`config.isInteractive()`, which returns false for the ACP child process
because it is spawned with pipe stdio (`process.stdin.isTTY === false`).
This guard was originally added to prevent headless one-shot CLI runs
(`qwen -p "do something"`) from wasting fast-model tokens on a title
that no one would ever see. However, daemon sessions are long-lived and
user-resumable — they appear in the session list and benefit from
semantically meaningful titles.
The fix allows ACP mode (`config.getExperimentalZedIntegration()`) to
bypass the `isInteractive()` check while still blocking true headless
CLI runs. After this change, the first assistant reply in a daemon
session will trigger LLM-based title generation (3-7 words, sentence
case) using the configured fast model, just as it does for interactive
TUI sessions.
Generated with AI
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(webui): expose focused daemon hooks (#4834)
* refactor(web-shell): own daemon message conversion
* fix(webui): improve transcript tool rendering
* fix(webui): pass thinking source to Markdown and conditionally apply styles
The thinking block content no longer applies the default `.content` styles,
allowing the thinking body to render with its own layout.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(webui): optimize /tools desc panel layout
- Switch to two-line layout: tool name on first line, status and
description summary on second line
- Disable mouse hover highlight to prevent hover from fighting
keyboard navigation for focus; support click to expand/collapse
- Show expanded description inline below tool item with accent
border for visual distinction
- Remove duplicate summary row in header
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* feat(web-shell): expose WelcomeHeader as a customizable prop
Add renderWelcomeHeader to WebShellProps and the customization context,
allowing parent apps to replace the default welcome header with a custom
renderer while receiving version, cwd, model, and mode props.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* feat(web-shell): add compactThinking prop to collapse thinking blocks
When enabled, thinking blocks are visually collapsed to ~5 lines with
a gradient fade-out mask. A toggle button allows expanding/collapsing
the full content. Uses CSS max-height + overflow detection via ref
to handle Markdown-rendered content (tables, code blocks, etc.)
correctly.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* feat(webui): expose focused daemon state hooks
* fix(webui/web-shell): review fixes and remove DaemonSubAgentRun
- Remove DaemonSubAgentRun type, selectDaemonSubAgentRuns selector,
useDaemonSubAgentRuns hook and related helpers/tests/exports
- Fix compactThinking: use ResizeObserver for overflow detection,
separate mask from max-height so gradient only shows when content
actually overflows, add aria-expanded/aria-label to toggle button
- Fix Markdown className emitting class="" for thinking source
- Unify isAskUserQuestionBlock logic with isAskUserQuestionToolName
- Fix getTodoPriority double invocation per item in selectors and
transcriptToMessages
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell): fallback empty tool header extras
* fix(web-shell): address daemon review regressions
* fix(web-shell): address follow-up daemon review
* fix(web-shell): hide pending permissions from transcript
---------
Co-authored-by: ytahdn <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(serve): add POST /session/:id/branch for session forking (#4812)
* feat(serve): add POST /session/:id/branch for session forking (#4514 T3.1)
Adds a dedicated HTTP route that forks a live session's JSONL transcript
and loads the fork via resume semantics (no history replay). Remote
clients can now programmatically branch sessions without the interactive
dialog the CLI /branch command requires.
Key design decisions:
- Uses resume (not load) to avoid flooding SSE with full history replay
- Source session must be idle (409 if prompt active via `promptActive` flag)
- ACP extMethod pattern for the fork operation (flush + forkSession + title)
- Validates originator via resolveTrustedClientId before event emission
- Cross-client events on source bus + workspace-wide fan-out
- Extracts computeUniqueBranchTitle to core for reuse
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address audit findings — cleanup paths and early validation
- Fix#1: Add detachClient branch for attached sessions in !res.writable
cleanup (mirrors restoreSessionHandler pattern)
- Fix#3: Move resolveTrustedClientId validation before restoreSession
to prevent orphaned live sessions if client ID becomes invalid
- Fix#2: Clean up orphan JSONL in acpAgent when post-fork title
operations fail (removeSession on catch)
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): add BranchWhilePromptActiveError re-export to acpSessionBridge shim
Without this re-export, server.ts fails to compile because it imports
from './acpSessionBridge.js' which did not forward the new error class.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): cap branch name parameter at 200 chars
Prevents unbounded name input from exceeding SESSION_TITLE_MAX_LENGTH
after computeUniqueBranchTitle appends the " (Branch N)" suffix.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): handle empty baseName when existing title is exactly "(Branch)"
The regex stripping "(Branch N)" suffix could produce an empty string
when the title itself was just "(Branch)". Now falls back to sessionId
prefix in that case.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: resolve merge conflicts with daemon_mode_b_main and remove trailing blank line
Rebase onto latest daemon_mode_b_main which added session_rewind and
SessionBusyError features. Keep both rewind and branch additions.
Fix trailing blank line in sessionService.ts (wenshao nit).
* fix(serve): address wenshao review round 5
- Serialize branch with promptQueue to close TOCTOU race
- Wrap sessionBranch ext method with runWithAcpRuntimeOutputDir
- Guard promptActive against sync exceptions before .finally()
- Add best-effort orphan JSONL cleanup on restore failure
- Strip control characters from branch name parameter
- Replace duplicated computeUniqueBranchTitle with core import
- Add session_branch to capability test assertion arrays
* fix(serve): chain branchSession onto promptQueue, log cleanup errors, drop dead forkedFrom field
- Chain branchSession onto entry.promptQueue (same pattern as sendPrompt)
to prevent concurrent prompt dispatch during the fork window
- Log cleanup errors in bridge catch block and acpAgent removeSession
instead of silently swallowing
- Remove dead forkedFrom field from agent return value (bridge constructs
its own forkedFrom object, never reads the agent's)
* fix(serve): use broadcastWorkspaceEvent for session_branched, enforce title length limit
- Replace manual for-of loop with broadcastWorkspaceEvent helper for
session_branched fan-out (adds per-session try/catch)
- Truncate baseName in computeUniqueBranchTitle to ensure final title
stays within SESSION_TITLE_MAX_LENGTH after suffix append
* feat(daemon): add POST /session/:id/language for runtime language switching (#4705)
* feat(daemon): add POST /session/:id/language for runtime language switching
Add a dedicated HTTP endpoint for switching UI language and LLM output
language without polluting the session transcript. The endpoint flows
through three layers (server route → bridge → ACP extMethod handler)
following the same pattern as approval-mode and model switching.
When syncOutputLanguage is true, the handler updates output-language.md,
persists settings, and refreshes system prompts across all active
sessions so the next LLM call immediately uses the new language.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): derive language allowlist from SUPPORTED_LANGUAGES + add debug logging
- Replace hardcoded LANGUAGE_CODES array in server.ts with dynamically
derived list from SUPPORTED_LANGUAGES, ensuring new languages added
to the i18n module are automatically accepted by the API.
- Add debugLogger.warn calls for settings persistence failures in the
ACP handler instead of silently swallowing errors.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address review findings for language switch API
- Add sessionOrThrow() call for session existence validation (doudouOUC)
- Wrap setLanguageAsync in try-catch with structured error (doudouOUC)
- Wrap updateOutputLanguageFile in try-catch to prevent partial state (wenshao)
- Return resolved language code instead of echoing "auto" verbatim (wenshao)
- Add refreshed field to language_changed SSE event payload (wenshao)
- Add language to telemetry route regex (wenshao)
- Add FakeBridge setSessionLanguage and 6 server route tests
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): persist original language param to preserve auto-detection
When language is "auto", persist the literal "auto" to settings instead
of the resolved concrete locale. This ensures auto-detection via
detectSystemLanguage() is re-evaluated on daemon restart rather than
being permanently pinned to whatever locale was resolved at switch time.
The response still returns the resolved language via getCurrentLanguage().
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): add defense-in-depth language validation in ACP handler
Mirror the LANGUAGE_CODES allowlist from the HTTP route into the ACP
extMethod handler, so direct extMethod callers are also validated.
Follows the same pattern as the approval-mode handler.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): report accurate refreshed status from language switch
Only set refreshed=true when at least one session refresh succeeded.
Log the count of failed sessions for diagnostics.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): align SSE event outputLanguage nullability with HTTP response
Add ?? null guard to outputLanguage in the language_changed SSE event
payload, matching the HTTP response path. Without this, an undefined
value would be silently omitted by JSON.stringify instead of being
explicitly null.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): skip refresh on file write failure + improve refreshed semantics
- Guard session refresh with fileWriteOk: if updateOutputLanguageFile
fails, skip refreshHierarchicalMemory (stale file would be re-read)
and return outputLanguage: null to signal the failure.
- Fix refreshed edge cases: true when zero sessions (nothing to do),
true only when ALL sessions succeed (failedCount === 0).
- Add debug log to bridge event publish catch block.
- Add res.body assertion and 500 error path test.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): register session_language in capabilities registry
Add session_language to SERVE_CAPABILITY_REGISTRY so SDK clients can
detect runtime language switching support via GET /capabilities.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* test(daemon): assert 500 response body in language route test
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): gate outputLanguage settings persist on file write success
Move settings.setValue('general.outputLanguage') inside the fileWriteOk
guard so settings and file stay in sync when the file write fails.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): keep model & approval-mode state consistent across clients sharing a session (#4613)
* feat(daemon): bridge side-channel state layer — A1 follow-up + A2 + A5 (#4511)
* fix(daemon): address review on side-channel state consistency
- inject session_snapshot up front on fresh SSE connections (not only on resume)
- reconcile only after a roundtrip that landed; guard generation TOCTOU with
one bounded re-run and log skip/correct/fail transitions
- drop unencodable reconciliation_failed bus event in favor of operator log
(client path already covered by state_resync_required)
- bridgeClient mode fallback emits previous/persisted; dual-emit session_update
uses the canonical nested data.update shape
- validate modeId at the setMode boundary; reject unknown modes
- SDK session_snapshot validator type-checks currentModelId/currentApprovalMode
- tests: fresh-connection snapshot + reconciliation drift/match/failure/roundtrip-failure
* fix(daemon): address second-round review on side-channel state layer
- applyModelServiceId: gate reconcile behind a `succeeded` flag so a
rejected create/attach-time roundtrip can't pair a corrective
model_switched with the model_switch_failed it just published; mirrors
setSessionModel / setSessionApprovalMode.
- in-session mode demux: validate currentModeId against the known
approval-mode enum (lockstep with Session.setMode) before it fans out
to SSE clients / the SDK reducer.
- in-session mode demux: suppress the legacy session_update dual-emit on
the exit_plan_mode path via a `legacyFrameSent` flag — sendUpdate
already published that frame, so dual-emitting delivered it twice. The
setMode path (no sendUpdate) keeps its dual-emit.
- reconcile: emit a `reason=roundtrip_failed` skip log on all three
failure paths so the skipped reconcile is greppable.
- SDK: add session_snapshot to RESYNC_PASSTHROUGH_TYPES so a client that
reconnects past ring eviction recovers currentModelId / approvalMode
from the full-state frame instead of staying stale until loadSession.
- tests: approvalMode reconcile drift + roundtrip-fail, generation rerun,
unknown-mode enum drop, dual-emit shape + suppression, setMode
extNotification + unknown-modeId rejection.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* test(daemon): assert currentApprovalMode flows into the A5 snapshot
The existing A5 snapshot tests only seed currentModelId, leaving the
publishApprovalModeChanged -> entry.currentApprovalMode -> snapshot
pipeline uncovered at the bridge level. Add a test that promotes an
in-session mode change before subscribing and asserts the snapshot
carries the non-null currentApprovalMode.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* docs(bridge)+test(cli): clarify mode-update handler comment & cover legacyFrameSent
- bridgeClient.ts: the A2 comment claimed handleInSessionModeUpdate
"mirrors handleInSessionModelUpdate exactly", but it diverges with enum
validation and the legacy dual-emit. Reword to state the shared
suppression pattern plus the two additions.
- Session.test.ts: add coverage for sendCurrentModeUpdateNotification
asserting the extNotification carries legacyFrameSent: true, so a
regression dropping it (double legacy frame to the IDE companion) is
caught.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4613 round-5 review — cache seeding, peer sync, contract cleanup
- bridge: seed snapshot caches (currentModelId/currentApprovalMode) from
newSession/loadSession responses so a cold attach reports real state
instead of null/null, with KNOWN_APPROVAL_MODES enum backstop
- bridge: enum-validate the reconcile approvalMode branch and drop unknown
modes with a logged reason
- bridge: on a persisted approval-mode change, mirror the new workspace
default into every peer SessionEntry cache so their GET status /
session_snapshot stop reporting the pre-change mode
- bridge/bridgeClient: remove try/catch wrappers around EventBus.publish()
per its documented never-throws contract; drop misleading "bus closed"
comments
- cli/Session: log dropped advisory extNotifications via debugLogger.debug
instead of swallowing silently
- bridge.test: add failure-gating coverage for applyModelServiceId — a
rejected attach-time model apply must not trigger reconcile (no status read)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4613 round-5 review nits — stale comments and cache doc
- bridge: document that setSessionModel caches the raw model id and
relies on the immediately-following reconcileAfterRoundtrip to
correct any raw-vs-canonical drift (the bridge layer lacks access
to the CLI's formatAcpModelId which requires authType)
- bridge: fix stale reconcile-catch comment that referenced
state_resync_required (long-lived SSE connections don't reconnect)
- bridgeClient.test: update stale "7-arg constructor" comment to
reflect the current 8-arg constructor
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4613 round-6 review — bundle cap, test gaps, assertions
- sdk: bump MAX_DAEMON_BROWSER_BUNDLE_BYTES from 100 KiB to 105 KiB to
accommodate session_snapshot type/validator/reducer additions (+1.2 KiB)
- bridge: remove redundant entry! non-null assertions (already narrowed
by if-guard at line 2708)
- bridge: document setSessionModel raw-id cache + reconcile correction
- bridge.test: add seedSnapshotCaches cold-attach test (newSession
response seeds model+mode without intermediate notifications)
- bridge.test: add peer cache sync test (persisted mode change updates
peer snapshot)
- bridge.test: add unknown-mode-drop test (reconcile drops agent-
returned modes not in KNOWN_APPROVAL_MODES)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4613 round-6 follow-up — fix false-positive test, add resync passthrough test
- bridge.test: rewrite unknown-mode-drop test to trigger approvalMode
reconcile (via setSessionApprovalMode) instead of model reconcile
(via modelServiceId), which never entered the approvalMode branch
— the original was a false positive (F8E2h)
- bridge.test: fix misleading params.mode cast in peer-cache-sync test;
status RPC sends {sessionId} not {mode} — return fixed 'yolo' (F8E2o)
- sdk daemonEvents.test: add session_snapshot passthrough-during-resync
test (RESYNC_PASSTHROUGH_TYPES membership regression guard) (F8SOq)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4613 round-6 follow-up — positive reconcile assertion
Add statusReads counter to the unknown-mode-drop test so it positively
asserts that reconcile actually executed (status RPC was called), not
just that no corrective event appeared. Without this, a future refactor
disabling reconcileAfterRoundtrip would make the test pass vacuously.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4613 round-6 follow-up — fix false-positive test, add resync passthrough test
- bridge.test: restore missing closing braces for extractErrorCode
describe/it blocks (lost during rebase conflict resolution)
- sdk build.js: bump MAX_DAEMON_BROWSER_BUNDLE_BYTES from 106 to
107 KiB (actual bundle is 108595 bytes = ~106.1 KiB)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): validate agent approval-mode response + typeof guard on model reconcile
- bridge: validate setSessionApprovalMode extMethod response against
KNOWN_APPROVAL_MODES before publishing/broadcasting; drop with log
if agent returns unknown mode (closes trust-boundary gap where
handleInSessionModeUpdate and reconcile had guards but this path
did not)
- bridge: add typeof === 'string' guard to model reconcile branch
so a non-string agent response (e.g. number) cannot pollute the
cache and break downstream session_snapshot validation
- bridge: add writeStderrLine to seedSnapshotCaches drop branches
for operator observability parity with reconcile's drop logging
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): fix unknown-mode succeeded flag + restore HAZARD comment
- bridge: leave succeeded=false when agent returns unknown approval
mode — skips pointless reconcile that would re-drop the same value
- bridge: restore channel-overlap HAZARD comment on closeSession's
channelInfoForEntry call (lost during reaper code removal)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): restore missing delimiters in events.ts (rebase artifact)
Three sites where session_snapshot was inserted immediately after
session_rewound lost the preceding block's closing delimiter during
rebase conflict resolution: type alias (missing >;), asKnownDaemonEvent
case (missing : undefined;), and reducer case (missing };).
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): remove reaper scope creep + fix events.ts delimiters (rebase artifacts)
- bridge: remove session-reaper code (closeSessionImpl, startSession-
Reaper, stopSessionReaper, constants) inadvertently included during
rebase conflict resolution — not part of this PR's scope
- events.ts: restore 2 missing delimiters (isSessionBranchedData
closing brace, session_rewound type/case closers) lost when
session_snapshot was inserted adjacent to session_branched blocks
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): throw on unknown agent approval-mode response instead of silent success
When the agent returns a mode not in KNOWN_APPROVAL_MODES, throw
instead of returning a misleading success response. The previous
behavior sent 200 OK echoing the requested mode while the cache
and SSE bus still showed the old value — a three-way state divergence.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(serve): add per-tier HTTP rate limiting for daemon (issue #4514 T3.4) (#4861)
* feat(serve): add per-tier HTTP rate limiting for daemon (issue #4514 T3.4)
Token-bucket rate limiter with continuous drip refill, opt-in via
--rate-limit flag. Three tiers: prompt (10/min), mutation (30/min),
read (120/min). Health, heartbeat, SSE, and /acp endpoints are exempt.
- rateLimit.ts: core middleware with fail-open, bucket cap (10k),
GC sweep (timer + request-count), sampled logging, graceful shutdown
- types.ts: 5 new ServeOptions fields
- capabilities.ts: rate_limit conditional feature tag
- server.ts: middleware wiring between bearerAuth and express.json,
deep health hit counts, app.locals lifecycle exposure
- runQwenServe.ts: shutdown dispose + setDraining
- serve.ts: CLI flags, env var fallbacks, boot validation
- server.test.ts: capability fixture update for rate_limit
- rateLimit.test.ts: 25 unit tests covering bucket mechanics, tier
resolution, key extraction, fail-open, draining, reset, callbacks
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): address wenshao review on rate limiting
- Add onError callback for fail-open observability (catch block + bucket overflow)
- Fix env var priority: CLI --no-rate-limit now overrides QWEN_SERVE_RATE_LIMIT
- Remove sampledLog.clear() from sweep to preserve suppressed counts
- Add sampledLog.clear() to dispose() for shutdown cleanup
- Add typed accessors setRateLimiter/getRateLimiter (replace raw string key)
- Wire onError callback through server.ts daemonLog
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(serve): let --no-rate-limit override env var
Remove default:false from yargs so argv['rate-limit'] is undefined
when neither flag is passed. Use ?? for env var fallback so
--no-rate-limit (explicit false) wins over QWEN_SERVE_RATE_LIMIT=1.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(test): add daemon connection stress test + refactor perf harness (#4862)
* feat(test): add daemon connection stress test + refactor perf harness (issue #4514 T3.4)
Extract shared helpers from baseline/benchmark tests into dedicated
modules and add a new mock-ACP connection stress test suite.
Refactoring (PR1 scope):
- _daemon-harness.ts: export gitHead(), makeTempWorkspace(), sleep(),
ScenarioResult, lastSeenId tracking in consumeSseEvents
- _daemon-benchmark-helpers.ts: extract /usr/bin/time wrappers
(spawnDaemonWithTime, parseTimeOutput, measureProcessTreeRss,
measureCliStartupWithProfiler) from benchmark test
- _daemon-perf-report.ts: shared formatPercentiles, collectPlatformInfo,
writeSnapshotArtifacts, resolveOutputDir
- Slim baseline + benchmark tests to import from new modules
New features (PR2 scope):
- fixtures/mock-acp-child/agent.mjs: mock ACP agent using real
AgentSideConnection SDK, env-controlled modes (echo/reject/
crash-on-prompt/hang)
- mock-acp-typecheck.test.ts: compile-time Agent interface check
- qwen-daemon-loadtest.test.ts: 5 scenarios gated by
QWEN_LOADTEST_ENABLED=1 — rapid lifecycle, SSE slow-consumer
eviction, Last-Event-ID reconnect, ACP crash recovery, burst
concurrent sessions
- vitest.loadtest.config.ts: isolated config with root anchoring
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: redirect console.debug/dir to stderr in mock ACP agent
Copilot correctly noted that console.debug and console.dir also
write to stdout in Node, which would corrupt the NDJSON pipe.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix: address wenshao review — snapshot status, eviction assert, crash recovery
- All 5 scenarios now use try/catch/finally so snapshot.status
reflects actual test outcome
- SSE eviction scenario asserts evicted === true (near-deterministic
with maxQueued=16 + 80+ events)
- Crash recovery verifies end-to-end by creating a fresh session
post-crash, not just health check
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): stamp serverTimestamp at EventBus and fix streaming state finalization (#4855)
* fix(daemon): stamp serverTimestamp at EventBus and fix streaming state finalization
Two issues fixed:
1. Blocks missing serverTimestamp: previously serverTimestamp was only
stamped at the SSE write boundary (formatSseFrame), so events fetched
via load/replay had no timestamp. Move the stamp to EventBus.publish()
so all consumers share the same server clock. SSE layer retains a
fallback for synthetic frames that bypass EventBus. CompactionEngine
preserves envelope _meta through text chunk merging. Normalizer adds
a 4th probe location for ACP update._meta.timestamp.
2. Streaming display errors: when switching text block types (e.g.
thought → assistant), the old block's streaming flag was not set to
false. Extract unified clearActive{Assistant,Thought}{,ForParent}
helpers that finalize the old block before clearing the active pointer.
Also set streaming=true for thought blocks (previously only assistant),
and emit assistant.done during replay snapshot turn boundaries so
historical turns render as completed.
* fix(daemon): preserve tool replay metadata
* fix(web-shell): keep tool duration on client clock
---------
Co-authored-by: ytahdn <[email protected]>
* feat(web-shell): make bottom-left mode indicator mouse-selectable (#4874)
* feat(web-shell): make bottom-left mode indicator mouse-selectable
The approval-mode indicator in the status bar could only be switched
with shift+tab. Make the mode label a button that opens the existing
ApprovalModeMessage picker (which already supports per-row mouse
selection), so the mode can be chosen with the mouse too.
- StatusBar: render the mode label as a <button> when an onSelectMode
callback is provided; falls back to the original spans otherwise.
- App: wire onSelectMode to open the approval-mode picker inline.
- Update the hint text + add a click affordance (cursor, hover, title).
* fix(web-shell): close approval-mode picker on outside mouse press
The inline approval-mode picker has no modal backdrop, so a mouse press
outside it did not dismiss it. Listen for document mousedown and close
when the press lands outside the panel (Esc / row-select still work).
* refactor(web-shell): address review on mode-indicator click
- StatusBar: make onSelectMode required and always render the mode
indicator as a <button>, so the "click to switch" hint is never shown
on a non-interactive label (drops the dead backward-compat branch).
- MessageList: when an inline picker (tailContent) first appears, force
auto-follow and scroll it into view, so opening it while scrolled up
no longer looks like a no-op (covers mouse, Shift+Tab, slash command).
* feat(web-shell): wrap arrow-key navigation in approval-mode picker
ArrowUp/ArrowDown now wrap around (last→first, first→last) instead of
clamping at the ends, matching the existing ModelMessage picker.
* fix(web-shell): only dismiss approval picker on primary mouse button
The outside-press handler fired for any button, so right-click (context
menu) and middle-click (X11 paste) also closed the picker. Ignore
non-primary buttons (event.button !== 0).
* fix(web-shell): address maintainer review on mode-indicator UX
Three blocking items from @chiga0:
1. default mode is now mouse-operable — getModeIndicator returns an
indicator for `default` (using the existing mode.default string), so
the status-bar control is a clickable button in every known mode; the
"? for shortcuts" fallback only remains for the unknown/disconnected
state.
2. the status-bar trigger is now a real toggle (setApprovalModeInlineOpen
flips), and stopPropagation on its mousedown stops it from counting as
an outside press for the picker's dismiss handler — so it can never
close-then-reopen.
3. the scroll-into-view-on-open behavior is now opt-in via a new
MessageList `autoScrollTailIntoView` prop, passed only for the
approval-mode picker; model/agents/memory panels keep scroll position.
* polish(web-shell): address ytahdn review on mode picker
- ApprovalModeMessage: dismiss on touchstart too (tap-outside on touch
devices) and skip when the press was already defaultPrevented.
- MessageList: re-check shouldFollow inside the rAF so a scroll-up during
the frame gap doesn't get fought by the tail reveal.
- StatusBar: add aria-haspopup="listbox" so the trigger announces it opens
a picker.
* fix(web-shell): close touch close-then-reopen + honest listbox a11y
- StatusBar: stopPropagation on the trigger's touchstart too (not just
mousedown), so tapping it never counts as an outside press for the
picker's dismiss handler — mirrors the desktop fix for the touch path
added in 1ef1144.
- ApprovalModeMessage: mark the list as role="listbox" and rows as
role="option" + aria-selected, so the trigger's aria-haspopup="listbox"
matches real semantics.
* feat(web-shell): improve UX with double-ESC clear, thinking collapse, and layout fixes (#4867)
* feat(web-shell): improve UX with double-ESC clear, thinking collapse, and layout fixes
- Add double-ESC to clear editor input (500ms window, hint in StatusBar)
- Improve thinking block collapse with accurate line counting and debounced resize
- Add trailingInline prop to Markdown for inline collapse/expand buttons
- Fix layout padding: move padding from app container to MessageList
- Add file completion type with proper label styling
- Simplify bash output display by removing show-all toggle
- Remove SSE stream ended status dispatch and clear disconnect error
- Improve error logging with console.error for recap and prompt failures
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell): address review feedback
* fix(web-shell): restore compact thinking default
* fix(web-shell): address latest review feedback
---------
Co-authored-by: ytahdn <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* docs(config): clean permission policy schema copy (#4900)
* feat(web-shell): make bottom-right model indicator mouse-selectable (#4887)
The model label in the status bar could only be changed via the /model
slash command. Mirror the bottom-left mode indicator (#4874): make the
model label a button that opens the existing ModelMessage picker, so the
model can be chosen with the mouse.
- StatusBar: render the model label as a <button> (tooltip, hover
affordance — the name brightens + underlines, aria-haspopup="listbox").
stopPropagation on mousedown/touchstart so the opening press is not
treated as an outside press by the picker's own dismiss handler.
- App: wire onSelectModel to toggle the inline model picker, and let the
picker reveal itself (autoScrollTailIntoView) like the mode picker.
- ModelMessage: dismiss on outside press (mouse/touch); add listbox/option
roles + aria-selected; highlight rows on hover via CSS (.row:hover)
without moving the keyboard selection, so mouse and keyboard do not
fight on the scrollable list.
* feat(web-shell): render /settings as inline panel matching native CLI (#4944)
* feat(web-shell): render /settings as inline panel matching native CLI
Replace the full-screen settings dialog with an inline tail panel (same
pattern as the model/approval-mode pickers): history stays visible, the
panel sits above the composer, Esc or outside-click closes it.
- single fixed description line like the native truncate-end behavior;
overflowing text glides marquee-style instead of being cut off
- arrow keys wrap around at both ends, skipping category headers
- drop the web-only "Modified in <scope>" extra row (native parity)
* fix(web-shell): restore inline cross-scope hint and test nextSettingIdx
Address review feedback on #4944:
- render "(Modified in X)" / "(Also modified in X)" inline after the
setting label (same row, secondary color), matching the native CLI's
getScopeMessageForSetting() — the earlier removal dropped the info
entirely instead of just the extra row
- export nextSettingIdx and cover wrap-around, header skipping, empty
list, and normalization entry points with unit tests
* style: prettier formatting
* feat(daemon): add POST /workspace/reload-env for hot-reloading env vars and session auth (#4924)
* feat(daemon): add POST /workspace/reload-env for hot-reloading env vars and session auth
Add a new daemon endpoint that reloads environment variables from .env
files and settings.env without restarting the daemon, and refreshes
auth on all idle sessions so both new and existing sessions immediately
use updated credentials (e.g. API keys).
Core changes:
- settings.ts: reloadEnvironment() with file-snapshot-based deletion
tracking (lastReloadSnapshot seeded at boot), RELOAD_EXCLUDED_KEYS
safety list, and force-write semantics for explicit reload
- Session.ts: isIdle() method with cancel-race protection via
pendingPromptCompletion null-reset
- acpAgent.ts: workspaceReloadEnv extMethod handler with
Promise.allSettled session refresh, modelProviders reload, and
skipLoadEnvironment to preserve diff accuracy
- workspace-service: EnvReloadResult/Response types, facade with 30s
timeout and best-effort child forwarding
- server.ts: POST /workspace/reload-env route behind strict mutation gate
- capabilities.ts: conditional workspace_reload_env capability
- SDK: env_reloaded event type, DaemonClient.reloadEnv(), barrel exports
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): address PR review — 4 fixes for reload-env
1. SessionNotFoundError now reported as childError instead of silently
swallowed, so callers can distinguish "child not running" from
"child reloaded 0 sessions"
2. Remove duplicate EnvReloadResult — types.ts re-exports from settings.ts
3. Move pendingPrompt=null to finally block — prevents isIdle() from
returning false permanently if #executePrompt throws
4. Skip deletion pass when .env file read fails — transient I/O failure
should not wipe all tracked env vars
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): fix compile errors and drain regression from rebase
1. EnvReloadResult: export type re-export doesn't create local binding;
add import type before re-exporting
2. dotEnvReadFailed: variable declaration lost during rebase; restore
3. pendingPrompt: clear in try block before drain calls (drains check
pendingPrompt and early-return if set), keep in finally for error path
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): add LD_AUDIT to RELOAD_EXCLUDED_KEYS
LD_AUDIT provides the same code-execution primitive as LD_PRELOAD
via the dynamic linker's audit interface.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): skip notification-busy sessions and preserve tracking on read failure
1. isIdle() now checks notificationProcessing and notificationAbortController
to prevent refreshAuth during background notification model turns
2. When .env file read fails, preserve dotEnvSourcedKeys and lastReloadSnapshot
so the next successful reload can still detect key deletions
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): add BASH_ENV/ENV to exclusions and fix settings.env shadowing on read failure
1. Add BASH_ENV and ENV to RELOAD_EXCLUDED_KEYS — shell-interpreter
injection vectors analogous to LD_PRELOAD for Bash/POSIX sh
2. When .env file read fails, use lastReloadSnapshot as the shadow set
for settings.env to prevent keys normally shadowed by .env from
overwriting the still-live .env values in process.env
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* feat(daemon): session idle reaper for automatic cleanup (#4833)
* feat(daemon): add session idle reaper for automatic cleanup of disconnected sessions
Idle sessions accumulate when clients close browser tabs or crash without
calling DELETE /session. Without cleanup, sessions leak memory (EventBus
ring ~2-4 MB each) and eventually hit the maxSessions cap (default 20),
locking out new sessions entirely.
Add a configurable session reaper that periodically scans the in-memory
session registry and closes sessions that have no SSE subscribers, no
registered clients, no active prompt, and whose last heartbeat exceeds
a configurable idle TTL (default 30 minutes).
Key design decisions:
- Uses existing closeSession path (soft close, not hard kill)
- JSONL transcripts on disk are preserved — session/load or session/resume
can restore any reaped session
- Emits session_closed with reason 'idle_timeout' so clients can distinguish
from explicit closes
- Reaper timer is .unref()'d and stopped on shutdown/killAllSync
- Configurable via --session-reap-interval-ms and --session-idle-timeout-ms
CLI flags (0 = disabled)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): add telemetry reason tag, channel idle timer test, and server integration tests
- Add 'session.close.reason' attribute to telemetry event so operators
can distinguish reaper-initiated closes from client-initiated ones in
dashboards
- Add test verifying channel idle timer fires after reaper closes the
last session on a channel (design doc test #12)
- Add server.test.ts integration tests: health endpoint reflects
session count changes, DELETE /session passes no close opts
- Update fakeBridge.closeSession signature to accept the new CloseSessionOpts
third parameter
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): close session on last client detach + fix reaper idle predicate
Add close-on-last-detach to detachClient: when clientIds.size drops to 0
AND no SSE subscribers remain, call closeSessionImpl immediately. This
handles the normal tab-close path without waiting for the idle reaper.
Adjust the idle reaper to NOT check clientIds.size — it now serves as a
backstop for the crash path where detach was never sent (clientIds still
> 0 but no subscriber and no heartbeat).
Add SessionEntry.promptActive boolean flag to reliably detect active
prompts regardless of whether an originator clientId was provided,
fixing a gap where headless prompts (no clientId context) were invisible
to the reaper's activePromptOriginatorClientId check.
Update existing heartbeat detach test to use two clients (single-client
detach now triggers close-on-last-detach). Add 3 close-on-last-detach
tests.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4833 review — re-entrancy, comments, clamp, logs
- Move byId.delete before await notifyAgentSessionClose in
closeSessionImpl to match killSession ordering and prevent duplicate
close cascades from concurrent callers (reaper + detach-close race)
- Restore 4 load-bearing comments dropped during closeSession extraction:
HAZARD (channelInfoForEntry), tombstone (markSessionClosed), ordering
(publish before cancel), back-compat (closedBy field)
- Add Math.min(raw, 2_147_483_647) clamp to resolvePositiveFiniteMs to
prevent setInterval from treating >2^31-1 as 1ms (tight loop)
- Include close reason in stderr log for operator observability
- Use err.stack instead of String(err) in reaper/detach-close failure
logs to preserve call stacks for debugging
- Log reaper startup status (enabled with thresholds, or disabled)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4833 round-2 review — duplicates, guard, docs
- Remove duplicate `promptActive: false` in createSessionEntry (rebase
merge artifact)
- Remove duplicate `entry.promptActive = true/false` assignments in
sendPrompt (rebase merge artifact)
- Add `!entry.promptActive` guard to close-on-last-detach path so
sessions with an active prompt are not closed on detach (reaper
handles them after prompt completes)
- Update bridgeOptions.ts JSDoc to reflect that the reaper intentionally
does NOT check clientIds.size (crash-path backstop)
- Fix misleading "mirrors killSession" comment — the ordering
intentionally diverges (synchronous teardown before agent notification)
- Update design doc §4.8 to document `last_client_detached` reason value
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): address PR #4833 round-3 review findings
- Fix unused _s2 variable (TS6133 / lint failure)
- Fix sendPrompt not advancing session idle clock: set
sessionLastSeenAt = Date.now() on prompt start and completion
- Add deferred close-on-last-detach after prompt completion: when
prompt finishes and clientIds.size === 0 && subscriberCount === 0,
trigger closeSessionImpl (covers the race where client detaches
while prompt is still running)
- Update design doc §4.2: reflect actual reaper predicate (no
clientIds check, uses promptActive flag)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): log deferred close errors + sync design doc pseudocode
- Replace silent .catch(() => {}) in prompt-complete deferred close
with error logging (stack trace included)
- Update design doc §4.5 pseudocode to match implementation:
use entry.promptActive instead of activePromptOriginatorClientId,
remove clientIds.size check
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* docs: remove stale 'No registered clients' from reaper rationale table
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(web-shell): make context usage mouse-reachable and survive reloads (#4958)
* feat(web-shell): make context usage mouse-reachable
The status-bar percentage and the /context panel's detail hint could
only be exercised by typing slash commands. Mirror #4887:
- StatusBar: the "x.x% context used" label is now a button that runs
the same flow as typing /context (echo + usage panel). No
stopPropagation: it opens no picker, so a press should dismiss any
open picker like any other outside press.
- ContextUsageMessage: the "/context detail" literal inside the hint
line is now a button that runs /context detail. Located by literal
match in the translated hint so translations without it degrade to
plain text. Callback travels App -> MessageList -> MessageItem ->
SystemMessage with stable identity to keep memoization intact.
- App: extract showContextUsage() shared by the /context slash command
and both buttons, so click and typed behavior cannot drift.
* fix(webui): seed tokenCount from replay snapshot on session attach
tokenCount was only populated from streaming usage updates and reset
to 0 on attach, so the status-bar context indicator vanished on every
page reload until the next model response.
Scan the freshly loaded replay snapshot backwards for the latest
usage-bearing session_update and seed the connection with it (turn
compaction keeps each merged slot's last _meta, so usage survives).
Only populated when this attempt actually (re)loaded the session: a
reused session object carries the snapshot from its original load,
whose usage may be older than the in-memory count. Malformed replay
events are skipped per-event, mirroring the injection loop.
* test(webui): cover getReplayTokenCount edges and tokenCount fallbacks
Review follow-up on #4958: the seeding test only covered the
replay-hit branch.
- mappers.test.ts: empty array, usage-less replay, latest-wins,
inputTokens precedence + totalTokens fallback, non-positive and
non-numeric filtering, null payloads, and throwing payload getters.
- provider: SSE re-subscribe on the same session keeps the in-memory
count (the reused object's stale empty snapshot must not reset it);
attaching a different session without replay usage resets to 0.
* feat(web-shell): make /settings mouse-reachable via a status-bar gear icon (#4972)
Add a gear button at the far left of the status bar, before the
approval-mode indicator. Clicking it toggles the same inline /settings
panel as typing /settings; clicking again, pressing outside, or Escape
closes it.
- Same stopPropagation contract as the mode button: the settings panel
dismisses on outside mousedown/touchstart, so the opening press must
not reach the window or the gear could never toggle the panel closed.
- settingsInlineOpen joins autoScrollTailIntoView so the panel reveals
itself when opened from the status bar while scrolled up.
- The gear is absolutely positioned in the bar's 2ch left-padding
gutter (plus 6px of the footer margin): it takes no flex space, so
the mode label keeps its input-text alignment, with a visible gap on
both sides of the icon.
- Hidden while disconnected like the other status-bar controls (the
panel needs the daemon to load settings); tooltip/aria-label reuse
the existing settings.title i18n key.
* fix(web-shell): merge adjacent tool calls into one tool_group like native CLI (#4975)
* fix(web-shell): merge adjacent tool calls into one tool_group like native CLI
Native CLI batches every tool call of one scheduler turn into a single
bordered tool_group (mapToDisplay), but the web-shell adapter created a
separate single-tool group per daemon tool block, so parallel tool calls
rendered as N separate boxes.
Merge a tool block into the trailing tool_group when nothing visible
separates them. Sub-agent calls keep their own single-tool groups so
ParallelAgentsGroup still detects consecutive agent launches, and
synthetic raw-shell groups (bare block id, no tg- prefix) never absorb
real tool calls.
* fix(web-shell): route raw shell chunks to the running execute tool in merged groups
Shell transcript blocks carry no toolCallId; the handler previously
appended chunks to the last tool of the last group. With adjacent-merge
a group can now hold e.g. [Bash, Read], so prefer the most recent
in-progress execute tool, then the most recent execute tool, then the
last tool (old behavior) when picking the attachment target.
* feat(web-shell): collapse thinking output to a 5-line window (#4977)
* fix(build): complete the 0610 origin/main merge left half-applied
The 0610 merge (44b936b73) brought in main's test mock + import of
createSessionRootContext but kept the old refreshSessionContext
implementation and assertions, leaving a dead import that fails
tsc under noUnusedLocals. Align both impl and tests with main.
The same merge also missed the branch-only IDLE_HOOK_EVENTS table
when main added UserPromptExpansion / InstructionsLoaded to
HookEventName: add the two entries (matcher kinds per hookPlanner
semantics) and extend ServeHookMatcherKind plus the SDK mirror
types so the daemon<->SDK contract stays in sync.
Fixes 'npm run dev:daemon' startup (stale acp-bridge dist could
not be rebuilt because the workspace build was broken).
* feat(web-shell): collapse thinking output to a 5-line window
Long thinking output flooded the screen. The compactThinking
customization existed since #4867 but was never enabled for the
standalone shell, and sub-agent thought streams (the bulk of the
output under /review-style skills) had no collapse at all.
- Enable compactThinking for the standalone web shell (main.tsx);
the embedder API default stays opt-in.
- While thinking streams, the collapsed preview now follows the
tail (newest lines pinned into view) instead of freezing on the
first five lines; switches back to head-clamp + expand toggle
when the stream ends.
- Collapse running sub-agent streams in SubAgentPanel to the same
5-line tail window with an expand/collapse toggle; the full
400px scroll view remains one click away. Completed-agent
details keep the existing click-to-open behavior.
- Re-check overflow on content growth: the clamped box stops
resizing at 5 lines, so a ResizeObserver alone missed overflow
that arrives later (expand toggle could fail to appear).
* feat(serve): ACP/REST parity — 29 new _qwen/* methods + production hardening (#4827)
* feat(serve): ACP/REST parity — 29 new methods + production hardening
Rebased on daemon_mode_b_main (post #4563 merge). Adds all wave 1+2
methods in a single commit:
- Session (6): recap, btw, shell, detach, context_usage, tasks
- Memory (2): workspace/memory read + write (1MB limit, scope/mode validation)
- Files (7): read, read_bytes, stat, list, glob, write, edit (via WorkspaceFileSystem)
- Auth (4): status, device_flow start/get/cancel (projected, no verification leak)
- Workspace (5): tools, mcp/tools, mcp/servers add/remove, sessions/delete (100 cap, dedup)
- Agents (5): list, get, create, update, delete (SubagentManager)
Production hardening:
- toRpcError: FsError, MemoryError, AuthError, SubagentError → structured errorKind
- Error data propagation: catch blocks forward data to JSON-RPC error frames
- BTW_MAX_INPUT_LENGTH validation, shell audit logging
- sessions/delete: 100 cap + dedup + strict types + error preservation
- auth/status: verification material stripped (security)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* test(serve): fix 400→404 assertions + add 35 unit tests for wave 1+2 methods
Fix 2 test regressions:
- transport.test.ts:359 — unknown conn now returns 404 (was 400)
- transport.test.ts:1439 — deleted conn now returns 404 (was 400)
Add 35 new test cases covering all 29 _qwen/* methods:
- Protocol compliance (4): 415, 501, 406, missing header 400
- Session extensions (9): recap, btw (valid+invalid), shell (valid+invalid),
detach, context_usage, tasks, unowned rejection
- Workspace (7): tools, mcp/tools (valid+invalid), mcp/servers add/remove
(invalid), sessions/delete (non-array + >100 cap)
- Auth (2): status empty, device_flow/start without registry
- Memory (3): non-string content, invalid scope, invalid mode
- Files (5): read without fsFactory, read missing path, write missing
content, edit missing params, glob missing pattern
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): fix 12 test failures — param validation before fsFactory + session stream ordering
- Reorder file method handlers to validate required params before
checking fsFactory, so missing-param errors return INVALID_PARAMS
(-32602) instead of INTERNAL_ERROR (-32603)
- Fix session extension tests to open the SSE stream before
session/new, then drain the session/new frame before reading the
method-specific response
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell,webui): SSE reconnection stability, error routing, and toast API (#4952)
* fix(web-shell): update thinking overflow on stream
* fix(webui): keep daemon connection errors out of transcript
* fix(webui): persist daemon client identity
* fix(web-shell): improve transcript rendering stability
* fix(webui): route session errors through notices
* fix(web-shell): expose prompt cancellations in transcript
* fix(web-shell): avoid duplicate forward failure cancellation
* fix(web-shell,webui): SSE delta resume on reconnect and expose toast API
- Preserve session on retriable SSE errors so reconnection uses
Last-Event-ID for incremental append instead of full transcript
rebuild, reducing re-renders and eliminating virtualizer
removeChild errors.
- Defer store.reset() until right before store.dispatch() so they
share a single queueMicrotask notification — React never sees an
intermediate empty-blocks state.
- Add onToast prop to WebShellProps: when provided, all internal
toast notifications are forwarded to the callback and the built-in
ToastHost is hidden, allowing external toast systems to handle
display.
- Export ToastTone type from web-shell package.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* perf(web-shell): cache Markdown component maps to avoid per-render allocation
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell): prevent React 19 dev-mode OOM on large transcripts
Wrap performance.measure() to catch DataCloneError thrown by React's
logComponentRender when structured-cloning large transcript props.
Production builds are unaffected.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell,webui): deduplicate capabilities request, pass clientId, and align streaming token display
- Reuse workspace capabilities in DaemonSessionProvider to avoid
redundant /capabilities request on initial connect
- Expose clientId prop on WebShellWithProviders so externally created
sessions can reuse the same client identity via DaemonSessionProvider
- Filter sub-agent usage events (parentToolCallId) from tokenCount
updates so the status bar reflects main conversation context only
- Replace inputTokens-based token display in StreamingStatus with
estimated output tokens (streamed chars / 4), matching CLI behavior
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(web-shell,webui): fix stale token display, double toast, and add notice routing tests
- Reset charsRef when no streaming block found to prevent stale token count
- Guard releaseSession/deleteSession onError with isAlreadyDispatched to prevent double toast
- Remove unused _daemonNoticeId from markNoticeDispatched
- Add tests for retriable SSE error delta resume path
- Add tests for notice routing: session_died, stream_error, model_switch_failed, client_evicted, turn_error
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(webui): batch epoch reset replay updates
* fix(webui): share workspace capabilities request
---------
Co-authored-by: 钉萁 <[email protected]>
Co-authored-by: ytahdn <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): isolate per-session stats in daemon mode (#4954)
* fix(serve): isolate per-session stats in daemon mode
GET /session/:id/stats was returning process-wide cumulative metrics
instead of per-session data because uiTelemetryService is a singleton.
In daemon mode multiple sessions share the same process, causing stats
to bleed across sessions.
Add per-session metrics isolation via dual-write pattern:
- addEvent(event, sessionId?) routes events to both the global metrics
(backward compat for CLI) and a per-session Map bucket
- getMetricsForSession(sessionId) returns isolated session data
- removeSession(sessionId) cleans up on session close and prevents
late-arriving events from recreating the bucket via closedSessions Set
- resetSession(sessionId) supports session resume without wiping other
sessions (replaces global reset() in daemon context)
- Replay path (replayUiTelemetryFromConversation) passes sessionId so
resumed sessions correctly populate their per-session bucket
All telemetry dispatch points (loggers.ts, suggestionGenerator.ts)
now pass config.getSessionId() to addEvent for session attribution.
* fix: cap #closedSessions Set + add replay test (wenshao review)
- Bound #closedSessions to 1000 entries, evicting oldest on overflow
- Add test verifying resetSession does not clear global metrics
- Add test verifying #closedSessions cap allows evicted sessions to
accept new events
* fix: update test assertions for addEvent sessionId parameter
loggers.test.ts: 6 toHaveBeenCalledWith assertions now expect the
second sessionId argument ('test-session-id').
client.test.ts: add resetSession to mockUiTelemetryService so
replayUiTelemetryFromConversation doesn't throw on the mock.
* fix: reset lastPromptTokenCount on session resume (wenshao Critical)
resetSession(sessionId) didn't clear the global lastPromptTokenCount
and lastCachedContentTokenCount scalars, unlike reset(). A stale high
value from a previous session could cause premature auto-compaction
on a freshly resumed conversation.
* fix: remove global scalar resets from per-session branch + reset() clears session state
- sessionService.ts: remove setLastPromptTokenCount(0) and
setLastCachedContentTokenCount(0) from per-session branch — these
are global scalars that contaminate other sessions
- uiTelemetry.ts: reset() now clears sessionMetrics and closedSessions
* test: add setLastCachedContentTokenCount to client.test.ts mock
* feat(web-shell): add task auth and goal workflows (#4856)
* feat(web-shell): add /auth and /tasks interactive panels
- Add /auth command with interactive authentication panel for
daemon serve mode, supporting login/logout/refresh flows
- Add /tasks command with interactive background tasks panel
aligned with CLI's BackgroundTasksDialog (list/detail views,
keyboard navigation, cancel/stop with double-press confirm)
- Add daemon-side task cancel endpoint and SDK client method
- Fix background agent notification delivery in ACP Session
so completed agents trigger new model turns via SSE stream
- Add task status polling with 2s auto-refresh while panel open
- Support dynamic hints based on selected task state
- Classify background sub-agent tool calls to exclude from
floating agent panel
* feat(web-shell): enrich task detail, fix turn_error message, deduplicate prompt errors
- Add recentActivities, stats, prompt fields to agent task data chain
(acp-bridge types → CLI serialization → SDK types → web-shell UI)
- Fix broadcastTurnError extracting "[object Object]" from JSON-RPC
error objects by reading data.details for the actual error message
- Fix duplicate error display in web-shell by marking errors already
dispatched by sendPrompt and skipping them in reportError
- Remove "Prompt failed" prefix from prompt error messages
- Add StatusBar task pill, tasks command enhancements, i18n additions
* feat(web-shell): add goal command support
* fix(build): restore goal import and update sdk bundle budget
* fix(web-shell): harden task and goal interactions
* refactor(web-shell): reuse tasks status rendering
* fix(web-shell): restore transcript blocks hook
* fix(daemon): address auth provider review feedback
* fix(daemon): harden task auth goal review fixes
* fix(daemon): address remaining task auth goal review
* fix(daemon): address critical review findings
* fix(web-shell): address task and goal review issues
* fix(web-shell): address task cancellation review
* fix(daemon,web-shell): address critical and suggestion review findings
- Add POST /session/:id/goal/clear API so /goal clear during active
generation no longer destroys in-progress work (bypasses cancel+sendPrompt)
- Snapshot/restore chat history around notification prompts to prevent
polluting shared conversation context
- Null pendingPrompt in finally block to prevent stale controller on error
- Wrap notification .finally() body in try/catch to prevent unhandled rejection
- Add identity guard to dispatchGoalCleared to prevent race with new goal set
- Strip trailing dot from hostname in SSRF blocklist check
- Suppress per-iteration goal checking events from transcript
- Validate goal status kind against known union members
- Clean up goal hook on session close to prevent observer leak
- Show actionError in task detail view
- Cross-reference duplicated GOAL_CLEAR_KEYWORDS constant
* fix(test): remove duplicate mockBackgroundTaskRegistry from rebase merge
* fix(test): add missing hasUnfinalizedTasks mock to background task registry
* fix(daemon): bound notification drain inner loop with deadline check
Add deadline check inside inner notification drain loop to prevent
unbounded processing when new notifications arrive during drain.
* fix(web-shell): prioritize tasks panel escape handling
* fix(web-shell): clear goal without prompt dependency
* fix(web-shell): address task auth goal review
* fix(cli): clean up goal observer lifecycle
---------
Co-authored-by: ytahdn <[email protected]>
* fix(daemon): bind QWEN_CODE_SESSION_ID to the current session via AsyncLocalStorage (#4998)
* test(telemetry): add missing createSessionRootContext import in sdk.test.ts
tsc --build fails on daemon_mode_b_main because sdk.test.ts references
createSessionRootContext (mocked via vi.mock('./tracer.js')) without
importing the symbol. Test-only change; unblocks the package build.
* fix(daemon): bind QWEN_CODE_SESSION_ID to the current session via AsyncLocalStorage
In daemon mode one process hosts many sessions, but the shell context
env session ID was read from process.env — a single process-global slot
that only the FIRST Config ever claims (sessionEnvClaimed guard in
config.ts). Every later session (new or resumed) spawned shells that
reported the first session's ID, mismatching the actual session.
- add sessionIdContext (AsyncLocalStorage), mirroring promptIdContext
- getShellContextEnvVars(): prefer sessionIdContext over process.env;
fall back to process.env so single-session CLI behavior is unchanged
- ACP Session: wrap #executePrompt / #executeCronPrompt /
#executeBackgroundNotificationPrompt in sessionIdContext.run(...)
- tests: ALS precedence, env fallback, concurrent-session isolation
* fix(daemon): language switch writes to wrong output-language.md path (#4938)
* fix(daemon): language switch writes to wrong output-language.md path
## Problem
`POST /session/:id/language` (PR #4705) always writes `output-language.md`
to the global `~/.qwen/` path, but `Config.outputLanguageFilePath` may
point to a project-level `<cwd>/.qwen/output-language.md` (when it existed
at startup). Since `refreshHierarchicalMemory` reads from the Config-bound
path, the language switch silently fails when a project-level file exists.
Additionally, on a fresh environment where no `output-language.md` exists,
the first language switch creates the file but `Config.outputLanguageFilePath`
remains `undefined` (readonly), so `refreshHierarchicalMemory` never reads
the newly created file.
## Fix
1. **Config.outputLanguageFilePath**: remove `readonly`, add
`setOutputLanguageFilePath()` so the path can be registered after
first-time file creation.
2. **languageUtils.ts**: add optional `targetPath` parameter to
`writeOutputLanguageFile()` and `updateOutputLanguageFile()`. Export
`getOutputLanguageFilePath()` for callers that need the global default.
3. **acpAgent.ts**: write to the session Config's actual path. On first-time
creation (path was undefined), register the global path on Config. On
multi-session refresh, also update each session's own file if its path
differs from the one already written.
4. **languageCommand.ts** and **SettingsDialog.tsx**: same Config-bound
path fix for the CLI `/language` command and settings dialog.
5. **server.ts**: expose `supportedLanguages` array in `GET /capabilities`
so clients can discover valid language codes before calling the endpoint.
6. **SDK**: add `DaemonClient.setSessionLanguage()` method and
`SetSessionLanguageResult` type.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix: address review findings — type safety, dedup helper, error handling
- Add `supportedLanguages` to `CapabilitiesEnvelope` interface (TS2353)
- Extract `writeOutputLanguageAndRegisterPath()` helper in languageUtils
to eliminate the duplicated get-path/write/register sequence across
acpAgent, languageCommand, and SettingsDialog (fixes SettingsDialog
missing the registration step)
- Wrap file writes in the multi-session refresh loop with try/catch so
`refreshHierarchicalMemory` and `refreshSystemInstruction` always run
even when a project-level write fails
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix: let write errors propagate to allSettled, remove redundant write
- Remove inner try/catch in multi-session loop so file-write failures
are captured by Promise.allSettled and reflected in `refreshed`
- For sessions with no path: only register the global path (the file
was already written by the primary write), skip the redundant write
- Add test assertion that setOutputLanguageFilePath is called on
first-time creation
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix: restore try/catch + write for !sessionPath, fix test cast
- Restore try/catch around file writes in multi-session loop so refresh
always runs (write failures are logged, not propagated)
- Restore writeOutputLanguageAndRegisterPath for !sessionPath sessions
to handle the case where writtenPath is a project-level path and the
global file was never written
- Fix TS cast in test assertion (double-cast + bracket notation)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* test: add multi-session language propagation test
Verify the fan-out loop handles three session scenarios correctly:
- Session A (project path): writeOutputLanguageAndRegisterPath called
- Session B (different project path): updateOutputLanguageFile called
- Session C (no path): writeOutputLanguageAndRegisterPath + path
registration
- All sessions: refreshHierarchicalMemory + refreshSystemInstruction
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix: improve debug logs, SDK re-export, and add helper unit tests
- Include session ID and target path in multi-session write error logs
- Re-export SetSessionLanguageResult from top-level SDK barrel
- Add 4 unit tests for writeOutputLanguageAndRegisterPath covering
config-bound path, undefined fallback, null/undefined config
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix: hoist sessionPath declaration out of try block
sessionPath was declared with const inside try but referenced in catch,
causing a block-scope ReferenceError. Move to let before try.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* test: add catch-branch and targetPath coverage
- acpAgent: test that refreshHierarchicalMemory still runs when a
session's file write throws (catch branch coverage)
- languageUtils: test writeOutputLanguageFile with custom targetPath
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): Support image upload and echo in WebShell (#4922)
* feat(daemon): Support image upload and echo in WebShell
Add multimodal image upload and display support for daemon mode:
- Extend extractContentPart to handle flat and nested image formats
- Add user.image.delta event type for transcript rendering
- Implement optimistic local image rendering with base64 inference
- Update MessageItem equality check to prevent redundant re-renders
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(daemon): Address P0 CR findings — sanitize mimeType and unify image normalization
- Wrap event.mimeType in sanitizeTerminalText() to prevent ANSI injection (C1)
- Normalize images once and pass same array to both optimistic message and session.prompt() (C4)
Fixes: PR #4922 review comments from @ytahdn and @chiga0
* fix(daemon): Address wenshao's review comments
- Fix COW violation: use immutable array update instead of .push() to avoid mutating shared state snapshots (transcript.ts)
- Fix invalid HTML nesting: change <span> to <div> for .body container (UserMessage.tsx)
- Remove unnecessary 'as' casts: leverage TypeScript's discriminated union narrowing (MessageItem.tsx)
- Preserve legacy daemon prompt behavior: omit 'image/*' mimeType to avoid sending unknown types (promptContent.ts)
* fix(web-shell): restore next.role guard in areMessagesEqual to fix TS2339
TypeScript cannot correlate next through the early return check, so next
stays the full Message union. The switch on prev.role only narrows prev.
Adding next.role === 'user' && restores type safety without casts.
Fixes: wenshao's review comment on PR #4922
---------
Co-authored-by: Qwen-Coder <[email protected]>
* feat(daemon): add POST /workspace/reload for unified settings hot-reload (#4965)
* feat(daemon): add POST /workspace/reload for unified settings hot-reload
Add a single daemon endpoint that hot-reloads ALL settings (env vars,
model, approval mode, permissions, disabled tools, memory) to all
idle sessions. Replaces the narrower POST /workspace/reload-env.
Core changes:
- settings.ts: reloadEnvironment() with file-snapshot deletion tracking,
RELOAD_EXCLUDED_KEYS safety list, dotEnvReadFailed guard
- Session.ts: isIdle() with 6-field check including notification state
and pendingPromptCompletion null-reset
- acpAgent.ts: workspaceReload handler with settings diff detection
(diffSettingsKeys), conditional per-field refresh, correct ordering
(permissions before approval mode, switchModel skips redundant
refreshAuth), APPROVAL_MODES validation
- workspace-service: ReloadResponse type, reload() facade with daemon
env sync, 30s timeout, SessionNotFoundError reporting
- server.ts: POST /workspace/reload route behind strict mutation gate
- capabilities.ts: workspace_reload conditional capability
- SDK: settings_reloaded event type, DaemonClient.reload(), barrel exports
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): fix env-only reload and remove type-mismatched permission sync
1. Add envChanged flag so .env-only changes (no settings.json diff)
still trigger refreshAuth on idle sessions
2. Remove updatePersistentRules call — settings permissions.allow is
string[] but updatePersistentRules expects PermissionRule[]. Defer
permission rule sync to v2.
🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)
* fix(daemon): wrap setApprovalMode in try-catch and merge duplicate tools blocks
- Wrap setApprovalMode() in try-catch to prevent TrustGateError from
skipping subsequent refreshHierarchicalMemory/refreshSystemInstruction
- Merge two consecutive if(changed.has('tools')) blocks into one
* fix(daemon): wrap switchModel in try-catch for reload resilience
Consistent with setApprovalMode handling — prevents model switch
failure from skipping subsequent refreshHierarchicalMemory and
refreshSystemInstruction calls.
* fix(daemon): wrap refreshAuth in try-catch and log session reload failures
- refreshAuth can throw on network errors/invalid credentials; wrap in
try-catch like switchModel and setApprovalMode for consistency
- Log rejection reason when a session reload fails via Promise.allSettled
* fix(daemon): SSE event parity, error logging, and reloadDaemonEnv guard
- Include childError and sessionsSkipped in settings_reloaded SSE event
for parity with HTTP response
- Add debugLogger.warn in all catch blocks (switchModel, refreshAuth,
setApprovalMode) so failures are observable
- Wrap reloadDaemonEnv in try-catch to prevent .env permission errors
from aborting the entire reload
* fix(sdk): add sessionsSkipped and childError to DaemonSettingsReloadedData
Align SDK SSE event type with the updated workspace-service emit that
now includes these fields for parity with the HTTP response.
* fix(daemon): wrap refreshHierarchicalMemory and refreshSystemInstruction in try-catch
Consistent with all other operations in the reload handler — prevents
memory/instruction refresh failure from rejecting the entire session
via Promise.allSettled when earlier config changes already applied.
* fix(daemon): fix stale log message in reload error path
* fix(daemon): wrap reloadModelProvidersConfig in try-catch for consistency
* feat(serve): add cursor-based pagination for session list (#4902)
* feat(serve): add cursor-based pagination for session list
The ACP protocol defines cursor/nextCursor on ListSessionsRequest/
ListSessionsResponse, and the internal SessionService already supports
cursor-based pagination. Wire pagination through to both transport
layers:
- REST GET /workspace/:id/sessions now accepts ?cursor=<mtime>&size=<n>
query params and returns { sessions, nextCursor?, hasMore }
- ACP HTTP dispatch session/list now reads params.cursor and returns
nextCursor in the response, matching the ACP protocol spec
- Live (in-memory) sessions are merged only on the first page (no
cursor) since they are always the most recent
- Default page size: 20, max: 100
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): align session list pagination with ACP protocol standard
Remove the non-standard `hasMore` field from ListWorkspaceSessionsResult.
Per the ACP ListSessionsResponse spec, pagination state is conveyed
solely through `nextCursor`: present means more pages, absent means
done.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): guard cursor parsing against NaN and use null-safe nextCursor checks
- Add Number.isFinite guard on parsed cursor to prevent NaN from
silently returning empty results on malformed cursor strings
- Use != null instead of truthy check for nextCursor, consistent
with acpAgent.ts pattern and safe for edge-case cursor value 0
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): address review findings — cursor guard, page size cap, dedup
- Use numericCursor (not raw options.cursor) for live-merge gate so
invalid cursor strings like "abc" correctly fall back to first page
with live sessions included
- Track liveMergedIds to enable future cross-page dedup
- Trim merged results to pageSize so first page never exceeds the
requested size; recompute nextCursor from actual last item when
trimming occurs
- ACP dispatch reads _meta.size for page size, matching acpAgent.ts
pattern (ACP spec strips top-level size, so it lives in _meta)
- REST response excludes internal liveMergedIds field
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): address DragonnZhang review — dedup, invalid cursor 400, tests
1. Cross-page dedup: on subsequent pages (cursor set), exclude
persisted sessions whose IDs match currently live sessions, since
those were already merged on page 1.
2. Invalid cursor → 400: throw InvalidCursorError for non-numeric
cursor strings instead of silently falling back to page 1.
Handled as 400 invalid_cursor in REST and INVALID_PARAMS in ACP.
3. Tests: add invalid cursor 400 test and cross-page dedup test.
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): single bridge call, overlay live data on all pages
- Cache bridge.listWorkspaceSessions result (one call, not two)
- Overlay live data onto persisted entries on ALL pages, not just
page 1 — fixes live sessions with old persisted mtime disappearing
from paginated results
- Live-only sessions (no persisted counterpart) still only appear on
page 1 to prevent cross-page duplicates
- Remove liveSessionIds exclusion filter — no longer needed since
persisted entries are never skipped
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): prevent cross-page duplication via sessionExists, add size boundary tests
- On first page, only add live-only sessions that have NO persisted
file (via sessionExists check) — prevents live sessions with old
persisted mtime from appearing on both pages
- Overlay live data onto persisted entries on all pages (enrichment)
- nextCursor derived solely from persisted layer (no time-domain mix)
- Remove unused persistedIds, reuse SessionService instance
- Add size=0/200 boundary clamping tests
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(serve): ACP WebSocket transport (RFD Streamable HTTP phase 2) (#4773)
* feat(serve): add TransportStream + WsStream (WebSocket transport prep)
* feat(serve): complete ACP WebSocket transport implementation
Per ACP Streamable HTTP RFD: GET /acp with Upgrade: websocket → 101 →
full-duplex WebSocket. Coexists with SSE — clients choose transport.
Implementation:
- index.ts: WS upgrade handler with bearer auth (401/403 before upgrade),
initialize as first message, lazy session stream attachment, full
JSON-RPC dispatch through existing transport-agnostic AcpDispatcher
- connectionRegistry.ts: SseStream → TransportStream type widening
- server.ts: store acpHandle in app.locals, pass token
- runQwenServe.ts: call attachServer(httpServer) post-listen
dispatch.ts: zero changes (transport-agnostic by design)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* test(serve): add WsStream unit tests (17 cases)
Cover all WsStream behavior:
- send: JSON serialization, sequential write chain, post-close safety
- close: idempotency, onClose callback, non-OPEN guard
- events: ws close/error → stream close
- heartbeat: 15s ping, onHeartbeat callback, stops after close
- dead connection: no pong → close on next tick
- pong keeps alive: pong received → no close
- send failure: write error → auto-close
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): address R7 review findings on WebSocket transport
- URL parse: wrap in try/catch (malformed Host → destroy, no crash)
- Auth header: reject missing/malformed before indexOf (no undefined access)
- Origin check: remove dead `[::1]` literal (URL.hostname strips brackets)
- Content-Type: startsWith instead of includes (no substring false match)
- WsStream: wrap onHeartbeat in try/catch (prevent interval crash)
- WsStream: wrap ws.ping in try/catch (socket may be gone)
- Tests: fix unused _stream vars (TS6133 noUnusedLocals)
- Tests: fix heartbeat test (emit pong between ticks to match alive logic)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): WS security hardening + fix 12 test failures
Security:
- Set maxPayload: 10MB on WebSocketServer to match REST surface
- CSWSH: origin check now applies to loopback too (browser-initiated
requests to 127.0.0.1 carry the external origin)
- DNS-rebinding: add Host allowlist check mirroring REST hostAllowlist
- Bearer token: use crypto.timingSafeEqual for constant-time compare
Tests:
- Reorder file handlers: param validation before fsFactory guard
- Session extension tests: drain session/new frame before asserting
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): TS4111 bracket notation + WS origin IPv6 bracket strip + empty Host reject
- server.ts: app.locals.acpHandle → app.locals['acpHandle'] (TS4111)
- index.ts: strip brackets from URL.hostname for IPv6 origin check
(new URL('http://[::1]').hostname returns '[::1]' in Node.js)
- index.ts: remove host && guard to reject empty Host headers
(align with REST hostAllowlist which unconditionally rejects)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): address 5 WS security findings — serialization, rate limit, token hash, dispose
1. WS message serialization: chain async handlers via promise queue
to prevent concurrent message processing races
2. Rate limiter: add checkRate() to RateLimiterInstance, thread through
MountAcpHttpOptions, enforce per-tier limits on WS messages
3. Token pre-hash: use SHA-256 digest before timingSafeEqual to
eliminate token-length side-channel (matches REST bearerAuth)
4. acpHandle.dispose(): call during daemon shutdown before bridge
teardown to close WebSocketServer and send close frames
5. Test coverage: existing 73 tests pass; WS-specific integration
tests tracked as follow-up
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* test(serve): add 10 WS security integration tests + ws error handler
- Host allowlist: reject non-loopback Host, accept loopback
- CSWSH: reject cross-origin, accept loopback origin
- Bearer auth: reject missing/wrong token, accept correct token
- maxPayload: verify 1009 close on >10MB frame
- Initialize gate: reject pre-init messages
- Message serialization: verify concurrent messages processed in order
- Rate limiter: verify WS messages are rate-limited
- Add ws.on('error') handler to prevent uncaught exceptions
- Add logging to message queue catch for observability
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): guard attachSessionStream against shared WS connStream + fix cleanupSession race
- attachSessionStream: skip closing prevStream when it's the shared
connStream (WS mode reuses connStream for all sessions)
- cleanupSession: capture AbortController identity to avoid closing
a recreated session's binding after the old pump completes
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): remove upgrade listener on dispose + DRY rate limiter + type cleanup
- dispose() now removes the 'upgrade' listener from httpServer,
preventing TypeError crash on late-arriving WS upgrades
- Refactor middleware to delegate to tryConsume(), eliminating
duplicated token-bucket logic
- Use exported AcpHttpHandle type instead of inline type shapes
in runQwenServe.ts
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): WS prompt deadlock, rate-limit tier/key parity, connStream guard
- Prompt dispatch no longer blocks the message queue, preventing
deadlock when a permission vote is queued behind an in-flight prompt
- Rate-limit tiers use explicit read-method allowlist instead of
prefix match, so session/new|close|cancel are correctly 'mutation'
- wsKey uses proper Duplex cast + ::ffff: normalization for IP parity
- connStream non-null assertion replaced with isClosed guard
- tryConsume fires onError callback on bucket overflow
- Test name corrected (accepts → not rejects)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): exception-safe destroy() + ACP HTTP rate limiting
- connectionRegistry.ts: wrap each teardownBinding() call in
try/catch during destroy() so one failing callback cannot leak
the remaining sessions' resources (AbortControllers, streams,
pending requests)
- index.ts: add rate-limit enforcement for ACP HTTP POST path
(POST /acp was exempt from Express middleware but had no
alternative checkRate call, unlike the WS handler)
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
* fix(serve): type safety, token pre-hash, ws dependency, init timeout log
- upgradeListener: use correct function signature, remove `as any`
- connRef: type as `AcpConnection | undefined` instead of `any`
- SHA-256 token hash: pre-compute once at setupWebSocket instead of
per-upgrade, reuse `expectedTokenHash` for all comparisons
- Add `ws` + `@types/ws` to cli package.json dependencies (was only
hoisted from plugin-example)
- Log WS initialize timeout with source address for diagnostics
Generated with AI
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
* feat(web-shell): add expand toggle to shell tool output (#4984)
* feat(web-shell): add expand toggle to shell tool output
Long shell output was clamped to a fixed 5-line tail preview
('... first N lines hidden ...') with no way to see the rest,
unlike Read output which already had a show-all toggle. The
per-line 150-char truncation from #4952 had the same gap: a
long line was cut with no way to see its full content.
Add a toggle to ExpandedBashOutput: the collapsed default keeps
the CLI-style 5-line tail with per-line truncation; a 'Show all
(N lines)' button reveals the full untruncated output (scrolling
within the existing 400px max-height) and 'Show less' collapses
it back. The button appears when either dimension hid content
(line count or line length). Reuses the existing expandBtn style
and tool.showAll / tool.showLess i18n keys.
* fix(web-shell): address review feedback on shell output toggle
- Use a distinct 'Show full lines' label when only the per-line
150-char truncation hid content (all lines already visible), so
'Show all (N lines)' no longer overstates what expanding does.
- Add aria-expanded to the expand/collapse buttons (bash + read)
so assistive technology can announce the toggle state, matching
SubAgentPanel and AssistantMessage.
- Add render tests for the toggle: short output (no button), long
output expand/collapse round-trip, char-truncated-only expand,
and aria-expanded state.
* fix(ci): Raise daemon SDK browser bundle budget
Raise the browser bundle size gate to 114 KiB so the current daemon SDK bundle remains guarded without failing the CI build.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(ci): Build web shell during root build
Include the web shell workspace in the root build order so CI prepare generates its package artifact before artifact tests run.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(test): Update MCP client mocks for instructions
Add getInstructions to MCP SDK client mocks so tests match the connect path that stores server instructions.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(test): Align CLI test expectations with daemon changes
Update CLI mocks, locale coverage, and environment snapshot assertions to match the current daemon-mode behavior exercised by CI.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(test): Stabilize daemon serve tests in CI
Keep ACP permission streams open until the client response is observed, assert daemon log paths against the canonical workspace path, and avoid real FIFO files in the workspace init unit test.
Co-authored-by: Qwen-Coder <[email protected]>
* fix(cli): Sanitize daemon shell command logs
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: ChiGao <[email protected]>
Co-authored-by: 秦奇 <[email protected]>
Co-authored-by: Claude Opus 4.7 <[email protected]>
Co-authored-by: Qwen-Coder <[email protected]>
Co-authored-by: ytahdn <[email protected]>
Co-authored-by: ytahdn <[email protected]>
Co-authored-by: 顾盼 <[email protected]>
Co-authored-by: Alexxigang <[email protected]>
Co-authored-by: tanzhenxin <[email protected]>
Co-authored-by: Shaojin Wen <[email protected]>
Co-authored-by: Edenman <[email protected]>
Co-authored-by: kkhomej33-netizen <[email protected]>
Co-authored-by: Shang Yuanchun <[email protected]>
Co-authored-by: 易良 <[email protected]>
Co-authored-by: DennisYu07 <[email protected]>
Co-authored-by: pomelo <[email protected]>
Co-authored-by: zhangxy-zju <[email protected]>
Co-authored-by: qqqys <[email protected]>
Co-authored-by: dreamWB <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: yiliang114 <[email protected]>
Co-authored-by: Dragon <[email protected]>
Co-authored-by: 胡玮文 <[email protected]>
Co-authored-by: qwen-code-ci-bot <[email protected]>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: dykebo <[email protected]>
Co-authored-by: 方磊 <[email protected].1.11>
Co-authored-by: MikeWang0316tw <[email protected]>
Co-authored-by: jifeng <[email protected]>
Co-authored-by: Qwen Code <[email protected]>
Co-authored-by: 衍星 <[email protected]>
Co-authored-by: 钉萁 <[email protected]>
Co-authored-by: yuanyuanAli <[email protected]>
* feat(channels): add Feishu (Lark) channel adapter
* fix(channels/feishu): fix webhook stop button, memory leak, spin-wait timeout, and reaction cleanup
* fix(channels/feishu): fix security, stability and build issues from PR review
* fix(channels/feishu): fix card lifecycle, streaming limits, and download safety from CR round 2
* fix(channels/feishu): harden webhook, card lifecycle, and disconnect cleanup from CR round 3
* fix(feishu): clarify stoppedMessages JSDoc to match actual cleanup behavior
* fix(channels/feishu): handle post messages without language key wrapper in quote context
* fix(channels/feishu): fix webhook signature bypass, stop-button double-send, and blockStreaming duplicates from CR round 4
* fix(channels/feishu): harden card lifecycle, markdown splitting, and defensive guards from CR round 5
* fix(channels/feishu): harden card lifecycle, markdown splitting, and defensive guards from CR round 5
- Set cardCreationFailed on onPromptStart failure to prevent retry spiral
- Skip throttle updates when card creation permanently failed
- Handle code fences in hard-split and table-stripping fallbacks
- Use parity-based fence detection in splitByTables (align with splitChunks)
- Add cs.stopped and else branch in onPromptEnd to prevent timer race and state leak
- Mark cardState.stopped after busy-wait timeout to abandon orphaned in-flight creation
- Apply MAX_CARD_CHARS truncation with fence parity in onResponseComplete
- Sanitize senderId before <at> tag interpolation
- Use replaceAll + callback form for mention replacement
- Floor token expiry to prevent thundering herd on expire:0
- Add log for stop-button auth rejection
- Fix stoppedMessages JSDoc to match actual cleanup lifecycle
- Fix test fixture to match "still creating" scenario
- Fix typecheck errors in test file (TS2571, TS4111)
- Add stop-button auth negative path tests (operator mismatch, missing operator, missing sender)
- Replace spanning regex in table-stripping with line-by-line stripTables() to resolve CodeQL ReDoS warning
* fix(channels/feishu): fix HMAC bypass, prompt injection, SSRF, and card lifecycle from CR round 5-6
Security:
- Fix webhook HMAC bypass: use defineProperty(non-enumerable) for headers instead of prototype shadowing
- Fix cross-user prompt injection: mark quoted content as untrusted with explicit marker
- Fix SSRF: validate all Feishu IDs with FEISHU_ID_RE before URL interpolation in 6 endpoints
- Fix safeSenderId regex: add hyphen to character class so ou_abc-def-123 is not rejected
Card lifecycle:
- Set cardCreationFailed on onPromptStart failure to prevent retry spiral
- Skip throttle updates when card creation permanently failed
- Fallback to plain message delivery when cardCreationFailed with accumulated text
- Track creationTimer in CardSessionState so cleanupCard/disconnect can cancel orphaned card creation
- Add cs.stopped and else branch in onPromptEnd to prevent timer race and state leak
- Mark cardState.stopped after busy-wait timeout to abandon orphaned in-flight creation
- Apply MAX_CARD_CHARS truncation with fence parity in onResponseComplete
- Preserve atPrefix in streaming truncation to prevent @mention visual snap
- Account for suffix and fence reserve in truncation maxBody calculation
- Clean up auxiliary maps after handleInbound when gate rejects the message
- Clean up blockStreaming mode Map entries in onPromptEnd
- Skip bare @mention without question text
Markdown:
- Handle code fences in hard-split and table-stripping fallbacks
- Use parity-based fence detection in splitByTables (align with splitChunks)
- Replace spanning regex in table-stripping with line-by-line stripTables() to resolve CodeQL ReDoS warning
Defensive guards:
- Sanitize senderId before <at> tag interpolation
- Use replaceAll + callback form for mention replacement
- Floor token expiry to prevent thundering herd on expire:0
- Add log for stop-button auth rejection
Tests:
- Fix stoppedMessages JSDoc to match actual cleanup lifecycle
- Fix test fixture to match "still creating" scenario
- Fix typecheck errors in test file (TS2571, TS4111)
- Add stop-button auth negative path tests (operator mismatch, missing operator, missing sender)
- Assert cancelSession called in stop-button happy-path test
* fix(channels/feishu): add request timeouts, token dedup, and harden file/quote sanitization
* fix(channels/feishu): harden card lifecycle, webhook auth, and resource cleanup from CR round 7
* fix(channels/feishu): harden card lifecycle, mention handling, and error recovery
The nightly/preview release workflow has been failing for 3 days with
`TS5055: Cannot write file ... because it would overwrite input file`
in packages/core during the version bump step.
Root cause: `npm install --package-lock-only` in version.js triggers
the root `prepare` lifecycle, which re-runs `tsc --build` while
packages/core/dist/ already exists from the initial `npm ci`. The
unbuilt acp-bridge reference (added in #4295 but missing from
build.js) corrupts TypeScript's incremental project graph resolution.
Fixes:
1. Add --ignore-scripts to the lock-file-only install in version.js
2. Add packages/acp-bridge to the build order in build.js
Closes#4368, closes#4339, closes#4307
Primary change: prevent the model from burning tokens in an infinite retry
loop when a tool call repeatedly fails schema validation with the same
error (observed with ask_user_question and a malformed `questions`
parameter retrying 10+ times with the same validation error).
- Track consecutive validation failures per (tool name, error message)
pair in CoreToolScheduler via a `validationRetryCounts` Map.
- After 3 consecutive failures for the same (tool, error) pair, append a
RETRY LOOP DETECTED directive to the error response instructing the
model to stop, re-examine the schema, try a fundamentally different
approach, or surface the issue to the user.
- Reset per-tool counters when the tool invocation succeeds; reset
globally when an incoming batch shares no tool name with any
previously failing tool; reset the per-tool counter when the tool
returns a different validation error so unrelated mistakes do not
accumulate toward the threshold.
- Distinct from LoopDetectionService, which tracks model-behavior loops
(repeated thoughts, stagnant actions); this change catches tool-API
misuse loops at the scheduler layer.
Piggyback fixes bundled in the same PR:
- packages/cli/index.ts, packages/core/src/services/shellExecutionService.ts:
treat PTY `EAGAIN` on the read path as an expected read error alongside
`EIO`, avoiding noisy surface-level failures from transient
non-blocking reads.
- scripts/build.js: switch the settings-schema generation step from
`npx tsx` to `node --import tsx/esm` for Bun compatibility.
Tests:
- Unit tests in coreToolScheduler.test.ts cover: directive injection on
the 3rd consecutive failure, counter reset when a different tool is
called, and counter reset after a successful invocation of the same
tool (fail → fail → succeed → fail → fail must not trip the directive).
* refactor: merge test-utils package into core
Consolidate the standalone @qwen-code/qwen-code-test-utils package
into packages/core/src/test-utils/, eliminating the need for a
separate package that only provided createTmpDir, cleanupTmpDir,
and FileSystemStructure type.
Changes:
- Move file-system-test-helpers.ts into core/src/test-utils/
- Re-export from core's test-utils index
- Update 3 core test files to use relative imports
- Update cli useAtCompletion test to import from @qwen-code/qwen-code-core
- Remove test-utils devDependency from core and cli package.json
- Delete packages/test-utils/ directory
All affected tests pass (fileSearch, crawler, ignore, useAtCompletion).
Co-authored-by: Qwen-Coder <[email protected]>
* fix: remove deleted test-utils from build order
The test-utils package was merged into core but the build script still
tried to build it separately, causing CI failures.
Co-authored-by: Qwen-Coder <[email protected]>
---------
Co-authored-by: Qwen-Coder <[email protected]>
- Add plugin-example to build order in scripts/build.js
- Add prepublishOnly script to auto-build before npm publish
This ensures the plugin-example package is built during the main build process and automatically compiled before publishing to npm.
Co-authored-by: Qwen-Coder <[email protected]>
- Update package.json exports to point to dist directory
- Add TypeScript build scripts to each channel adapter
- Include channel adapters in build order
This enables proper TypeScript compilation and distribution of channel
adapter packages.
Co-authored-by: Qwen-Coder <[email protected]>
This adds the new channel-base package to the build order, positioned
before cli since cli depends on it.
Co-authored-by: Qwen-Coder <[email protected]>
Moves export-html and insight templates from cli/assets to a new
dedicated web-templates package. Updates Dockerfile and build scripts
to use consolidated bundle/prepare:package/pack workflow.
Co-authored-by: Qwen-Coder <[email protected]>
Add JSON Schema generation for settings.json files to provide IntelliSense
and validation support in VS Code. The schema is automatically generated
from the internal SETTINGS_SCHEMA definition during the build process.
- Add generate-settings-schema.ts script to convert TypeScript schema to JSON Schema
- Add jsonValidation contribution to vscode-ide-companion package.json
- Include schemas directory in .vscodeignore for packaging
- Integrate schema generation into build process
Co-authored-by: Qwen-Coder <[email protected]>
VSCode IDE Companion depends on @qwen-code/webui, but npm workspaces
build packages in alphabetical order, causing webui to be built after
its dependent.
Fixed by explicitly defining the build order:
1. test-utils
2. core
3. cli
4. webui
5. sdk
6. vscode-ide-companion
Co-authored-by: Qwen-Coder <[email protected]>