mirror of
https://github.com/QwenLM/qwen-code.git
synced 2026-11-07 06:19:43 -10:00
main
107
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
f3af3dd857 |
refactor(managed-agent): Split server into Maven modules (#15871)
* refactor(managed-agent): split server into Maven modules Separate contracts, orchestration, persistence, adapters, assembly, and verification while retaining the existing service delivery model. Move tests and build consumers together and document local evidence and pending CI acceptance. Co-authored-by: Qwen-Coder <[email protected]> * refactor(managed-agent): reduce configuration and SDK boilerplate Co-authored-by: Qwen-Coder <[email protected]> * refactor(managed-agent): narrow contracts and simplify test scaffolding Co-authored-by: Qwen-Coder <[email protected]> * fix(managed-agent): repair verification after module migration Resolve shared fixtures and worker paths from the Maven module root, update CI packaging assertions, and align existing test fixtures with the extracted contracts. Restore restricted Workspace constructors and remove redundant test visibility changes without altering inherited MySQL coverage. Co-authored-by: Qwen-Coder <[email protected]> * test(managed-agent): align remaining Harness and OSS fixtures Preserve SDK refusal messages and register the managed OSS adapter at fixture injection points. Keep the existing retry and client shutdown assertions intact. Co-authored-by: Qwen-Coder <[email protected]> * style(managed-agent): order Hosted cleanup Harness imports Co-authored-by: Qwen-Coder <[email protected]> * test(managed-agent): fix recovery smoke fixture and import order Supply the required transcript coverage in the recovery browser fixture and wait for history before testing a complete handoff. Preserve its existing safety and submission assertions. Order the cleanup coordinator test imports for Checkstyle. Co-authored-by: Qwen-Coder <[email protected]> --------- Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
28415ddff3 |
refactor(managed-agent): Consolidate server and broker sources (#14277)
* refactor(managed-agent): Consolidate server and broker sources Move the combined Java application beside sdk-java and remove the standalone Runtime Broker artifact. Update build, development, packaging and CI references while preserving Java package identities, runtime protocols and schema resources. Co-authored-by: Qwen-Coder <[email protected]> * docs(managed-agent): Preserve historical evidence and verification guidance Restore commit-pinned H3 probe inputs and align the Java verification environment contract with the consolidated server layout. Co-authored-by: Qwen-Coder <[email protected]> * fix(ci): Run hosted Broker tests under Bash Keep Maven property arguments intact on Windows and stop before Broker tests when the SDK install fails. Exercise both successful and failed SDK installation in the workflow regression tests. Co-authored-by: Qwen-Coder <[email protected]> * fix(ci): Quote the hosted Broker shell value Follow the repository yamllint single-quote rule without changing the parsed workflow configuration. Co-authored-by: Qwen-Coder <[email protected]> --------- Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
01d97f571a |
fix(core): retain CSI preparation resources through the HTTP store (#14180)
* test(managed-agent): expect the canonical V2 baseline * fix(core): retain CSI preparation resources through the HTTP store * fix(ci): lint Java acceptance scripts with Node globals Co-authored-by: Qwen-Coder <[email protected]> * fix(ci): narrow Node globals to managed-agent fixtures Co-authored-by: Qwen-Coder <[email protected]> * test: witness the file-history refusal path and label acceptance cleanup Address review round 1 findings R1-3, R1-4, R1-10 and R1-12. The managed-file_history branch of collectNestedResourceRefs refuses a malformed record instead of collapsing its closure to an empty set, but nothing pinned that: wrapping the branch in a catch that returns [] survived the whole suite. Two assertions at the collector seam now kill that mutant, verified by applying it and confirming the new test reds. The prepared-record case modelled previousRecordRef and intentRef as two distinct resources, a shape production never emits: SQL admission requires both to equal the predecessor's file-history ref and reads that ref from this transaction. Share one ref so the fixture models a real record, and retitle the test and the collector comment to what the walk actually does. In the acceptance gate, release the adapter, executor and HTTP client unconditionally and assert the three waits afterwards, so a slow child can no longer leak them for the rest of the surefire fork, and name each wait in its assertion message. Pass the case label to post() in the worker refusal loop, matching its SQL-readback twin, so a stopped refusal names which of the five cases changed instead of naming the route twice. * test(managed-agent): translate proc-fd addresses on every platform The acceptance harness short-circuited its /proc/self/fd translation when the host really was Linux, so the file backend's native proc-fd arm ran there for the first time while the macOS arm stayed on the translated path. That short-circuit is the only platform-varying input in the bind path, and bind is where the harness dies. The 409 it dies with does not locate the fault. The worker answers every throw from the history handler with managed_csi_history_unavailable and discards the error object, and the broker recognises only managed_context_unavailable and managed_context_conflict, so anything else becomes a 409 managed_runtime_identity_conflict - a code that names a comparison the request never reaches. The identity, context and installedContext fields are pure functions of one SQL-stored handle and never carry mount, pod or proc-fd state. Translate unconditionally instead, matching managed-csi-mount.test.ts, which forces platform linux through a Proxy and translates every owned descriptor with no host-platform short-circuit. The fixture fakes the mount, so the descriptors that matter are the ones it tracks whether or not the host exposes /proc/self/fd. Update both design docs, which claimed Linux uses actual proc-fd addressing. Not verified on Linux from this checkout. The decisive check is one run of WorkspaceCsiSqlWorkerMySqlIT on ubuntu-latest; if it still 409s, proc-fd addressing is exonerated and the remaining candidates are the openDirectory device/inode comparison and the readdir emptiness gate in the bind branch. --------- Co-authored-by: Qwen-Coder <[email protected]> Co-authored-by: Shaojin Wen <[email protected]> |
||
|
|
73aa65a4b4 |
chore(desktop): rename packages/desktop-shell to packages/desktop (#12653)
* chore(desktop): rename packages/desktop-shell to packages/desktop The Electron-era packages/desktop was removed in #9085 and the OpenWork downstream has forked, so the short name is free and the shell suffix is the only thing left of the transition. Rename the package directory and every load-bearing reference: workspace negations (npm + pnpm), the ci.yml crate filter, desktop-release.yml, the isolation guard, lint/ignore configs, scripts tests, CLI workspace-fixture tests, and living docs. User-facing identity is untouched: the crate stays qwen-code-desktop, productName stays "Qwen Code Desktop", the bundle identifier, updater feed, release tag scheme, and the legacy electron-bridge asset names are all unchanged. check-desktop-isolation now guards both path names so the old one cannot re-enter a workspace set. Dated design docs under docs/design/ keep their historical paths deliberately. Refs #8596 * docs(design): follow the rename in the undated notification design notes The web-shell-browser-notification-details pair is a living doc without a date prefix, so it falls under the PR's update rule rather than the historical-record exception. * docs(desktop): stop citing paths the rename invalidated Three prose sites and one CI comment still described the pre-rename world, or contradicted themselves once `packages/desktop` named both the removed Electron app and the living Tauri shell. - ci.yml `desktop_shell`: the comment this branch added credited the Cargo.toml guard with keeping "branches from either side of the rename" green. It does not. A pre-rename head's files sit under `packages/desktop-shell`, which the changed-files filter no longer matches, so the job skips before the guard ever runs. Say that, and say what the guard does cover (a head the filter matched because ci.yml itself changed, with no crate at the new path). - docs/design/web-shell-user-message-links.md: "desktop-shell routing" / "desktop-shell clicks" -> "desktop-host", the wording this branch already chose in LinkifiedText.tsx for the same rule. - docs/design/telemetry-runtime-client-attribution-design.md: repoint the `runtime.rs` citation. It backs the live `QWEN_CODE_DESKTOP=1` claim, and the other document of record for that invariant -- the comment in acp-channel-fallback.ts -- was already repointed by this branch, so the two disagreed. Only the path token changes; the doc's dated findings are untouched. - brand-create.mjs / SKILL.md / src-tauri/src/main.rs: name the historical referent as historical (the Electron `packages/desktop` removed in PR 9085) instead of letting it read as a self-reference. In main.rs the citation `packages/desktop/packages/shared/src/config/storage.ts` now looked like a subpath of the file's own package. Rewritten, not deleted: the `QWEN_DEFAULT_WORKSPACE_DIR` clause next to it is the only in-code documentation of that override and still resolves. Deliberately not swept: `scripts/check-desktop-isolation.js`'s `packages/desktop-shell` tripwire, ci.yml's #8132 history comment, `docs/design/9152-architecture-invariant-classification.md` (names both spellings and is accurate), and the date-prefixed `docs/design/2026-07-31-desktop-web-shell-release.md`. Co-authored-by: Qwen-Coder <[email protected]> Patrol-Run: qwen-pr-closeout/jmug1iw422v * test(scripts): pin the desktop crate path and the isolation guard's coverage Both invariants fail green today, and this rename is the second time the crate directory has moved. `scripts/check-desktop-isolation.js` gained `'packages/desktop'` in `nativePrefixes` -- the only production-logic line in this branch -- and nothing read it. Deleting that line leaves the guard's output and exit code byte-identical, because `isNativeLocation('packages/desktop')` then matches no remaining prefix; a later PR that drops `!packages/desktop` from the root workspace list would re-admit the package with CI green. The `desktop_shell` job names the crate directory in five places (the changed-files filter, the Cargo.toml guard and its `::notice::` text, the rust-cache `workspaces:`, and two `working-directory:` values). Nothing asserted they agree with each other or with a directory that exists, so the next drift reports a skipped job as a passed one. The new suite parses both instead of re-running them, and is superset-shaped on purpose: `nativePrefixes` carries a fourth entry (the `packages/desktop-shell` tripwire) that nothing negates, and an exact-match assertion would invite deleting it. The npm/pnpm mirror of the negation list is already pinned by package-scripts.test.js, so this reads package.json only. Verified by mutation, each applied alone and then restored: reverting the filter alternative or either `working-directory` to `packages/desktop-shell`, dropping `'packages/desktop'` from `nativePrefixes`, and dropping `!packages/desktop` from package.json all turn this suite red. Today no other test does. Co-authored-by: Qwen-Coder <[email protected]> Patrol-Run: qwen-pr-closeout/jmug1iw422v * test(scripts): pin what the desktop-isolation tests actually claim Four review findings on scripts/tests/desktop-isolation.test.js, each verified by mutating the thing it claims to pin, before and after. - The comment above the local `isNativeLocation` copy claimed a change to the script's rule "has to be made here too". Nothing reads the rule back from the producer -- `nativePrefixesFromSource` parses the array literal only -- and narrowing the script's rule to prefix equality leaves the suite green. Describe the copy instead of claiming coupling that does not exist. - `still carries the Cargo.toml existence guard` matched only the guard's condition text. Flip the body's `changed=false` to `changed=true`, or move it after `fi`, and the suite stayed green at 5/5 while the job runs every gated step against a crate that is not there. Assert the assignment sits inside the guard's own `if ... fi` body. - Both on-disk checks keyed on the bare directory, so git-ignored residue under `packages/desktop-shell` (`node_modules`, which survives a branch switch with an empty `git status`) reddened two tests on a tree with no defect and blamed the root workspace set. Key on `package.json`, which is what `packages/*` requires to make a directory a workspace member; a real re-entry still reddens both. - The `startsWith(filterAlternative)` assertion compared a path built from `crateDir` -- `filterAlternative` with one trailing slash stripped -- back against `filterAlternative`, so it could not fail for any input. Dropping the trailing slash from the changed-files filter in ci.yml left it green. Replace it with the property that makes the alternative a path prefix rather than a bare string prefix. Co-authored-by: Qwen-Coder <[email protected]> Patrol-Run: qwen-pr-closeout/jmugedurp3j --------- Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
b7543aeb1b |
feat(browser-use): add Chrome Native Messaging relay (#11242)
* 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.
|
||
|
|
6c962b3719 |
feat(web-shell): manage git remotes from the workspace branch picker (#11163)
* feat(web-shell): manage git remotes from the workspace branch picker
The workspace git popover could pull, commit, push and switch branches,
but the remotes themselves were read-only context: a user who clones from
a zip (no origin), works triangular (fork + upstream), or wants to drop a
stale remote had to leave the Web Shell for a terminal.
Adds a Manage Remotes panel inside the popover — list, add, remove —
backed by new workspace-scoped daemon routes and the SDK methods for
them. The listing reads git through its structured accessors rather than
the rendered "remote -v" output, which git annotates for partial-clone
remotes and which a line parser silently misreads. Mutations answer with
the fresh list so the panel re-renders in one round trip, and a remove
also refreshes the branch listing and the tracking state of the chip,
because git deletes the remote-tracking refs and upstream config together
with the remote.
Names and URLs are validated before git is spawned (flag injection,
refname rules for add; removal stays as lenient as git itself so a
hand-edited config can always be cleaned up), and rendered through a
display sanitizer that strips the invisible-character set — a git config
the user did not author can carry bidi marks that spoof the displayed
URL.
Design doc: docs/design/git-manage-remotes.md
* fix(web-shell): harden git remotes management after review audits
The config-scope read, removal verification and client refusal handling
carried gaps the reverse audits surfaced: include.path/worktree scopes were
under-listed yet un-removable (destructive dead ends), GIT_ALLOW_PROTOCOL
was deleted outright (a fail-open swap against config-file policy), the
classifier let echoed names/URLs steal config-write failures, and several
guards shipped without witnesses. Fixes:
- list the repository-owned scope via `config --list --show-scope -z`
(local+worktree), completing worktree-scope removals git cannot edit
- normalize an inherited GIT_ALLOW_PROTOCOL (strip ext/fd) instead of
deleting it; keep deny-by-default force
- order sendGitError's anchored config-write shapes first; add
remote_config_unparsable for unparsable configured refspecs
- follow git's boolean/integer grammar exactly (valueless/empty/hex/kmg)
- keep the URL visible under row shrink; restore focus after in-flight
mutations; disarm confirms on refusal; silent re-reads stay silent
- witness every guard above in unit/e2e suites; sync the design doc
* fix(web-shell): close remotes edge cases from the second review round
Seven Critical threads from the review bot's second batch, all fixed with
witnesses and a ten-round reverse audit on top:
- add pre-flights all config scopes and refuses a same-name inherited
section (remote_shadows_inherited), after probing repository-ness;
removal verifies resolution across every scope so an inherited survivor
can never be reported as removed (fail-closed on killed reads)
- sendGitError shapes match git's message start only (line 1, or git's
two-line lock chain): config-chosen names/URLs can carry any keyword,
and config values can carry real newlines, so deeper line-initial text
is attacker-controllable; classification reads the full redacted detail
while the client message stays bounded
- killed config reads rethrow with the all-scope stdout dump stripped
(stderr diagnostics preserved) on every read path
- focus restores: add submit button, remove-row button when focused,
back-button fallback; restores are gated on lent focus, cleared on view
exit and workspace switch; refused removal awaits the silent re-read so
the restore lands on the converged list
- no_such_remote remove refusals also refresh branches and status
* fix(core): harden git remote removal verification and upstream cleanup
- iterConfigRecords: shared NUL-framed --show-scope record walk for all
four config-read consumers
- promisor bool grammar: match git's strtoimax exactly (C-isspace
leading class, attached sign, hex/octal/decimal, case-insensitive
k/m/g, [INT_MIN, INT_MAX] bound)
- removal: pre-removal pointingBranches snapshot (worktree-over-local,
last value) so mixed-scope upstream keys stay attributable
- removal: sweep worktree-scope branch.<b>.remote/merge/pushRemote and
remote.pushDefault that git's rm cannot write (--fixed-value
--unset-all for value-matched keys), re-verify and refuse
remote_still_configured
- removal: refuse when an upstream key still resolves to the removed
remote from a file this module will not edit (include.path'd file or
inherited global/system scope, incl. rm-unmasking), resolved with
git's effective last-value-wins semantics
- removal: converge a retry after a failed cleanup on the
no-such-remote path instead of dead-ending
* fix(web-shell,cli): close remotes edge cases from the fourth review round
- core: never fire the worktree completion when git died BEFORE
mutating — the refusal phrase matches at a line start only, and an
error:/fatal: invalid refspec at any line start vetoes it outright
(a config-chosen refspec value can carry the phrase on a deeper
line); the refusal keeps its remote_config_unparsable answer and the
row stays
- cli: redact gitdir paths git echoes outside the workspace tree — a
linked worktree's shared main .git dir, a submodule's gitdir, a
relocated admin dir (via the commondir file), the symlink-canonical
spelling of each (git realpaths at setup), and over-long targets
(head-bounded reads, truncated lines redacted as prefix tokens)
- web-shell: IME-owned Enter guard on the add form (isComposing /
keyCode 229, both inputs)
- web-shell: whitespace-lookalike marking — names/URLs differing only
by whitespace (CSS-collapsed) now flag, with escapes in the tooltip
and aria-labels; the search filter collapses both sides to match the
inked text
- web-shell: sticky stash warning survives the remotes round trip —
snapshot on entry, restore on back/Escape/dismiss, busy-gated so a
settling mutation's footer wins, a newer standing warning always
outranks a held snapshot, and re-entry never nulls a held one
- web-shell: focus capture/restore resolves from the popover content's
own root (shadow-portal embedding), and the settle restore bails
when the content is unmounted mid-mutation (no cross-instance focus
theft)
* fix(core,web-shell): close remotes edge cases from the R4 review batch
- core: sweep orphaned refs/remotes/<name>/* after a certified removal
(git's rm deletes them only through a parseable fetch refspec), with
--no-deref so a planted symref can never delete its target, plus the
no-such-remote converge arm so a retry after a failed sweep does not
dead-end; re-verified, refusing remote_still_configured on a survivor
- core: extraPushUrls falls back to the url list when no pushurl exists
(git pushes to every url then) so the badge no longer under-reports
git's push fan-out
- cli: route suite gains strict-mutation-gating (per-call + count),
mid-flight generation close → 503, runtime-env threading, both lock
chains, the ancestor-walk ceiling, and the host system/global config
precondition guards
- web-shell: armed remove confirm disarms on filter-out / Escape /
add-submit; the popover mock now unmounts on close and dismisses on
an un-prevented Escape (Radix DismissableLayer parity); Escape events
in the witnesses are cancelable
- web-shell: a successful removal no longer awaits the branch refresh
(busy/focus released immediately); a successful add clears the
remotes filter so the new row is visible; the removing row shows a
spinner; the armed confirm's aria-label names the consequence badge
- web-shell: search matches the extras badge text and sanitizes the
needle; the push/fetch tooltip labels are localized (en + zh-CN);
the e2e primary journey carries @smoke
- sdk: workspaceGitRemoteAdd/Remove accept an optional per-call
timeoutMs; the panel passes 600s (the mutation chains git spawns
that each carry their own 30s budget)
- docs + PR body updated to the shipped implementation (config-scope
reads, WRITES-vs-RESOLVES scope split, six classifier branches)
* fix(core,cli,web-shell): close remotes edge cases from the R5/R6 review batch
- core: refuse include-held/split remote sections BEFORE spawning
`git remote remove` (git rm deletes the tracking refs and upstream
keys before failing on a section it cannot write — every retry
destroyed again); record origins are resolved against the worktree
toplevel (git chdirs) with both literal and realpath spellings, and a
killed probe refuses instead of answering blind
- core: the upstream-key sweep now covers local scope too and matches
multi-valued keys by exact value (`--fixed-value`), since git's rm
skips multi-valued keys with a warning; the re-verification pins only
value-matched keys (an include-held inert merge key must not refuse a
completed removal)
- core: the survivor gate gains the unmask case — a pointed branch or
`remote.pushDefault` whose shadowing record the removal unset must
not fall back to an inherited record naming a remote with no section
(the pre-removal snapshot proves causation), while git's sectionless
forms (`.`, URLs, scp-like, local paths) and pre-existing dangling
values never refuse
- core: promisor values are resolved by the host git itself
(`--type=bool --get-all`, additive like git's registration) instead
of an in-module bool grammar whose integer bound tracks a moving git
target; a promisor record at any scope marks the badge, and a killed
badge read rethrows stripped instead of answering false
- core: Apple Git's runtime-prefix defaults file reports scope
`unknown`; the record walk recognizes it so the verification folds
stay sound (the listing and sweep still filter to repository scopes)
- cli: redaction covers the inherited config files git echoes by
absolute path ($HOME/.gitconfig, the XDG config — including empty-XDG,
no-HOME and trailing-slash verbatim-concatenation spellings — and the
build-time system gitconfig), NUL-truncated gitdir AND commondir
pointer targets, head-truncated targets keyed on the NUL-normalized
form, and the bad-config-line / unable-to-access payload shapes at
arbitrary include.path locations (transport URLs are not config
targets and stay verbatim)
- web-shell: the popover installs the house preserveImeEscape mask
while open, so a composition-cancelling Escape no longer tears down
the remotes view nor swallows the native IME cancel (the popover mock
now delivers Escape from document-capture like Radix's
DismissableLayer)
- e2e: remotes spec selects on data-testid instead of hashed
CSS-Modules class substrings
- kill suite: the mock chains pin exact call counts (a retargeted kill
read can no longer pass silently)
* fix(core,web-shell): close the slash-namespace and render-identity gaps
- core: isRemovableRemoteName now refuses names containing `/` — a
slashed remote's tracking namespace is a subdirectory of the prefix
remote's (refs/remotes/origin/staging/* lives inside
refs/remotes/origin/*), so no post-removal sweep can tell the remote's
own refs from the prefix remote's branch refs, and a never-configured
slashed name would 404 only after the converge-arm sweep destroyed
them; the panel answers 400 before anything runs and the terminal
remains the tool for the shape
- web-shell: the remotes row identity check gains the two structural
arms the strip list cannot enumerate — a name that is not NFC (a
canonical twin inks identically) and a Latin name mixing in another
script's letters (the Cyrillic-о homoglyph shape) — both marking the
unusual row with its distinguishing characters escaped in the tooltip
and aria-label, while a legitimate non-ASCII name stays unmarked
- docs: the design record's absolute render-identity claim and the
remove-route leniency claim are narrowed to the shipped mechanisms
* test(core): pin worktree-over-local upstream attribution on removal
* fix(cli,web-shell): bound the loose classifier keywords and keep git's sentence boundary
- cli: the legacy loose keyword branches (dirty / already exists / no
upstream / …) match the CAPPED 512-char slice again — an unbounded
scan reclassified long push/pull output whenever a path or URL past
the cap carried a keyword (a `dirty-cache.git` push rejection
answered 409 dirty_working_tree); the anchored remote branches keep
the full detail for the two-line lock chain
- web-shell: git error text in the single-line footer now collapses
whitespace before stripping the invisible class — a stripped newline
fused git's two-line lock chain into one unreadable sentence
* test(cli): allow the redaction's process-scoped HOME/XDG_CONFIG_HOME reads
* fix(core,cli,web-shell): close the R9-batch removal integrity gaps
- core: the upstream-key sweep now reaches a multi-valued key's
NON-effective entry naming the removed remote (residue whose later
surfacing would dangle), and the merge key is swept only when the
same scope's remote key holds no surviving entry — a branch that
keeps its upstream keeps its merge
- core: the tracking-refs sweep resolves ownership by longest-prefix
against the configured remote set (a configured slashed sibling's
namespace is no longer taken down with the prefix remote) and covers
the exact bare ref refs/remotes/<name>
- core: removal certification asks git's own resolver
(`ls-remote --get-url`, documented not to contact the remote), so a
legacy $GIT_DIR/remotes/<name> file or an insteadOf alias can no
longer keep a "removed" name fetchable
- core: the sweep now walks every linked worktree's config.worktree
(the invoking worktree's reads never see siblings' files), lazily,
fail-closed per worktree
- core: the pre-removal snapshot carries per-branch local value lists,
and a local [branch] section git rm destroyed while its shadowed copy
named a SURVIVING remote is restored — a worktree-shadowed fallback
upstream is no longer collateral damage
- cli: the unable-to-access redaction arm accepts drive-letter absolute
paths (the Windows lane runs the redaction suite)
- web-shell: a remote URL carrying non-ASCII bytes fails closed — URLs
are an ASCII-only surface, so the row marks and the tooltip spells
the homoglyph out
* fix(core,cli,web-shell): close the R10-batch removal and confusables gaps
- converge arm: ask git's own transport for the bare-word path leg
(bundles resolve; --resolve-git-dir called them too large), skip the
sweep for empty pushInsteadOf aliases, re-verify the ref sweep, and
carve win32 backslash spellings as sectionless values
- unmask gate: push-side arms count pushurl records and pushInsteadOf
aliases; the path leg answers through git's transport
- pre-flight: inherited refusal only when a repository half exists to
destroy; union gate and worktree completion keep their race backstops
(kill-suite witnesses)
- redaction: linear /etc/gitconfig token arm, open-family in-file arm,
fail-closed absolute-path sweep with the apostrophe-tail fragment drop
- confusables: table-first fold with NFC closure at generation time,
symmetric all-ASCII collision marking, skeleton as a search target,
U+2028/2029 escaped emission, self-map and empty-alias guards
- design docs: bilingual zh-CN twin plus the round's gloss corrections
* ci: run the platform lanes for the git remotes path handling
The win32 path-spelling carve and the local path-transport probes behave
differently per host and no POSIX-only lane can tell whether they work on
Windows; classify the two git-remotes files platform-sensitive (exact
paths, not a keyword) so both lanes see future changes to them.
* test(core): write the slashed sibling section instead of remote-adding it
git newer than 2.50 refuses `git remote add a/b` over an existing `a`
("remote name 'a/b' is a subset of existing remote 'a'"), which killed
the macOS and Windows lanes in fixture setup. A config-written section
is git-version independent and models the hand-edited config the lax
removal predicate exists for.
* Revert "ci: run the platform lanes for the git remotes path handling"
main retired the platform-lane pull_request trigger and froze
classify-platform-sensitivity.mjs untouched so the future restoration
revert stays clean (ci.yml comment). The GIT_PATH_HANDLING entries
extended a script no CI path invokes — the lanes actually ran through
workflow_dispatch event gating — and broke that freeze.
* fix(core,cli,web-shell,docs): close the R11 confusables split and deferred batch
- web-shell: the generator closed prototypes under NFC + table only,
but the runtime fold also NFKC-folds table-absent halves, so 29
emitted values split one ink-identical class across two skeletons
(R11-2). Close every value under the exact consumer fold map-wide,
delete self-maps inside the convergence loop so the fixed point is
computed against the final map, post-verify the invariant, and
regenerate (29 values, witness: U+1D52 vs U+00BA).
- core: escape the NUL separator in pushKey (a raw NUL byte made grep
and ripgrep treat the module as binary); rename the misnomer
repository-scope describe.
- cli: readHead opens workspace-controlled paths synchronously on the
shared error path; a FIFO commondir wedged the daemon event loop.
Guard on isFile (FIFO witness, POSIX-gated).
- web-shell test: replace the vacuous cross-workspace focus assertion
with an equality on the pre-settle active element.
- docs (en + zh-CN): consumer-fold closure clause, ls-remote probe
spelling, orphaned bullet fragment repaired, §6 witness rows.
* test(core): retry the tmp-dir teardown on Windows EBUSY
The windows lane lost an otherwise-passing not-a-repo test to a
transient EBUSY on the afterEach rmdir (a handle held by the indexer
or an exiting git child). Retry the teardown a few times instead of
failing a test whose assertions already passed; non-EBUSY errors and
exhausted retries still throw.
* docs(web-shell): state the consumer-fold example's mechanism exactly
The `º/₀` halves NFKC to `o/0`; the capital O comes from the per-half
table chance (0030 -> 004F), not from NFKC. The result string was
right, the stated mechanism was not — anyone re-predicting a fold
whose NFKC half is itself a table key would mis-derive it. Also name
the tooltip-escape consumer at the delete arm and print the code
point (not the raw char) in the fixed-point diagnostic.
* fix(core,web-shell,docs): close the R13 Criticals and their audit fallout
- R4-3: widen EXECUTING_HELPER_URL to admit git's empty-name helper
form (`::payload` execs a PATH-resolved `git-remote-`); rationale
corrected — the empty name is not on git's deny-by-default list, and
a protocol.allow policy that would cover it is overridable from
config files. Witness rows `::sh -c id`/`::0`/`::`; mutation of the
pattern turns them red while the IPv6 literals stay accepted.
- R12-1: restore the local upstream backups at the TOP of the
removal-failure path (above the !completed throw and the converge
classification), so a refusal following an already-destructive rm
cannot skip the rollback; a killed restore read rethrows instead of
letting git's original answer surface un-rolled-back (kill witness
pins the restore read's argv, separating it from the converge gate's
scope read).
- R13-2: the converge arm excludes the removed name's own
namespace-less top-level bare ref from sweep AND re-verify while
keeping the longest-prefix ownership resolution whole — a bare ref
exactly owned by a configured slashed sibling keeps that owner
(first attempt at this fix regressed exactly that; witnesses:
remote-HEAD symref, flat layout, slashed sibling bare ref).
Accepted residuals disclosed: a formerly-configured name's bare-ref
residue is orphaned, and a flat layout's slashed branch refs stay
sweepable.
- R13-3: mark BOTH rows when a collision group's skeleton is non-ASCII
and the variance is a table fold rather than canonical equivalence
(skeletonAscii/allCanonical on the group); witness öö × ةة; the
all-ASCII and pure-canonical polarities keep their pinned behavior.
- Audit fallout: the TR39 fold moves to
client/utils/remote-name-skeleton.ts beside its table integrity gate
(no self-maps, no value containing a table key, key folds to value,
value is a fold fixed point, NFC); the non-discriminating
lowercase-spoof completion test is removed (the exact-prefix test
carries the veto witness); design docs synced EN+ZH for the third
marking polarity, the error-path restore and its fail-closed
masking, the converge residuals, and the new test rows.
* fix(core,cli,web-shell,docs): close the R14 Criticals and their audit fallout
- R14-2: the TR39 fold iterates to a fixed point (capped) instead of
running one pass — the closing NFC can compose a table key and a
decomposed spelling only meets the table after composition; new
remote-name-skeleton.ts carries the fold beside its integrity gate
and fixed-point corner tests.
- R14-3: redaction gains a quoted-path arm (git's die(_('%s' …))
family owns a quoted space-bearing payload whole) plus a slash-
carrying fragment arm for apostrophe-bearing paths.
- R14-4: tracking-ref ownership skips refs inside a SURVIVING remote's
fetch-dest namespace (NUL-framed get-regexp read), on sweep and
re-verify alike; closes the flat-dest slashed-branch residual.
- R14-5: the restore's presence read is NUL-framed, so an empty value
reads as present instead of absent (no more doubled pushDefault).
- R14-6: isSectionlessUpstream narrows to `.`/colon-bearing values;
dangling slashed/backslash upstreams now refuse like their bare-word
twin; win32 UNC keeps a carve (network transport, offline-share
timeout); existing paths still certify through the path probe.
- R14-7: the post-refusal branch/status refresh runs in the same
synchronous block as the staleness guard, ahead of the awaited
re-read, so a mid-await workspace switch cannot seed the new
workspace's panel with the old closure's data.
- Audit fallout: stale comments corrected (sectionless shapes, flat
dests, probe classes), win32 UNC carve, NUL-framed dest read without
the speculative JSON.parse arm, prettier-clean test files, and EN/ZH
design-doc sync for all six changes plus matrix/Files-affected
attribution of the new skeleton module and its tests.
* fix(core,web-shell,docs): close the R15 Criticals and their audit fallout
- R15-1: foreign-namespace roots derived per wildcard position; mid-
wildcard dests (refs/remotes/*/main, or*/main) fail closed. The
reverse audit caught an unsatisfiable star-position conjunction that
disabled the orphan sweep in any repo with another default-refspec
remote; fixed and pinned by an origin + refspec-less orphan witness.
- R15-2: the sibling-worktree sweep verifies the sibling shares this
repository's common dir before any read or write, so a planted
.git/worktrees gitdir can no longer receive its unset writes;
planted-gitdir witness, real-sibling tests unchanged.
- R15-3: the remotes search folds the needle in three case forms (the
TR39 table is case-sensitive); Istanbul/lstanbul witness.
- R15-4: the fold is invariant under canonical equivalence — two-level
decomposition fallback at runtime, generator closure over NFD(key),
table regenerated (6564 entries, U+021A dropped, 27 values re-classed,
lunate sigma preserved); full invariance sweep pinned.
- Deferred-triage fixes: hermeticity precondition regex, win32 UNC
short-circuit witness, worktree-completion kill witness, dash-URL
client-guard witness, NFKC-fallback pin, timeout-ceiling and
mixed-scripts comment accuracy, zh predicate-bullet and UNC doc
parity, pushl marker-comment accuracy.
* refactor(core,web-shell,docs): land the R15 reverse-audit follow-ups
- The sibling sweep skips the invoking worktree BEFORE the ownership
probes, so a repo whose only worktree record is its own pays no
probe spawn (just the one lazy toplevel read, reused per sibling).
- The killed-sibling witness is re-aimed at the new spawn order and
pins the kill to the sibling's config.worktree read; under the old
queue the kill landed on an ownership probe while the test passed.
- The remotes search dedupes its case-folded needles and folds each
row's ink once instead of once per needle variant.
- EN design doc: two stranded fragments repaired; ZH counterpart gets
the missing subject in the marker sentence (parity).
* test(web-shell): route the remotes e2e through the post-#11700 picker entry
Main's context-overview rework removed the sidebar git pill and the
welcome-view branch chip this spec opened the picker through; the
merge-head smoke run failed waiting for a pill that no longer renders.
The spec now enters the scenario session and opens the picker from the
environment panel's branch row — the same route the branch-picker
visual spec uses — keeping every assertion unchanged.
* build: raise the tsc build heap ceiling to 4096 MiB
A fresh `tsc --build` of packages/cli on the merged tree peaks just
above the 3072 MiB ceiling: two consecutive CI Lint runs and a local
clean-tsbuildinfo build all OOM at ~3.0/3.1 GiB, while each parent tree
alone stays under the ceiling and incremental builds never showed it.
Workspace build children inherit NODE_OPTIONS from the root build
script, so raising it there is what fits the union program; the test
ceilings are untouched.
* test(web-shell): pin the remotes e2e to the scenario branch and armed state
- openBranchPicker derived its click target from a hardcoded branch
name while accepting scenario overrides; it now reads the scenario
branch, pinned by the search test whose fixture switches to feat/x
(RED without the derivation).
- The smoke test asserts the armed Confirm label between the two
remove clicks, so a single-click regression fails at the witness
instead of as a second-click timeout; pinned by a temporary
single-click mutation that turns the assertion RED.
* fix(cli): move the git routes off the core barrel per the #11798 rule
Main's new lint rule bans new cli value-imports from the core package
root; the remotes and branches serve routes imported their symbols from
the barrel. Point them at the defining core modules (utils/git-remotes,
utils/git-branches, utils/gitDirect, utils/gitUtils) and drop the
allowlist entry the branches route no longer needs, per the list's
shrink-only contract.
* fix(core,cli,web-shell,docs): address R16 review and convergence-audit findings
- Refuse removal up front when a repository-scope section's name stays
push-resolvable through a url.*.pushInsteadOf prefix: a
post-destruction refusal wedges the upstream keys the certify sweep
can no longer reach (the retry's 404 converge arm skips over the same
alias. Six shape witnesses: local-section, strict-prefix,
inherited-only 404 doctrine, worktree scope, and the included- and
inherited-refusal ordering ahead of the alias refusal.
- Convert the truncated-gitdir redaction from an unbounded \S* regex to
a linear per-token replace with identical semantics.
- Picker collision groups key on the casefolded skeleton; a per-pair
case-twin arm marks case-only pairs at any script (a non-ASCII third
member no longer disarms an ASCII pair); U+FFFC/U+FFFD placeholder
names mark with the (lookalike name) copy; every arm and polarity
carries a mutation-verified witness.
- Drop the core barrel re-export of utils/git-remotes.js: its only
consumer deep-imports the module per the #11798 rule.
- Sync EN+ZH design docs to the four structural arms, arms 1-4 witness
attribution, the six pre-flight witnesses, and the documented
fetch-side wedge as a known house limitation.
HEREDOC
)
* fix(cli,core,docs): address R17 verification findings and convergence-audit findings
- M6/M8 (four-time survivors): the bounded-slice test now pins the
not-a-repo keyword family past the 512 cap (deep-cap probes for
`not a git repository` and `invalid reference`), the `invalid
reference` alternation half gains its positive table row, and a new
table test pins the line-1 anchor of the remote-already-exists arm
(a line-2 occurrence falls to the loose keyword arm). Each pin is
mutation-verified: its mutant reddens exactly that test while every
sibling stays green.
- The inherited-scope-alias wedge (a global/system/unknown
pushInsteadOf alias prefix-matching a listed repository-scope
section) gains its repo-suite witness, and the pre-flight comment
plus both design docs name it, including that the 409 names no alias
at any scope so the UI never shows the cause (fail-closed, terminal
is the only escape).
- Verification-bot dispositions: the wire-visible distinct error code
for the pre-flight refusal is deferred as a follow-up; the leaked
HEREDOC commit-message trailer is declined (fixing it would require
rewriting published history).
* fix(remotes): close R18 review findings and local audit findings across rollback, converge and fold
R18-1: the ambient named-section guard matched across lines
(`[^.]+` spans newlines), so a host `remote.pushDefault` read as a
named section and skipped the whole route suite; exclude the newline,
stop the scan at the `=`, and pin the line boundary both ways
(two-component pushDefault plain / followed by a dotted key / carrying
a dot in its value must not match; dotted section names must).
R18-2: the no-such-remote converge arm ran the certify path's
destructive sweep without any unmask gate, so a removal could destroy
the local shadow of a dangling inherited upstream and still answer
404; run the snapshot-scoped half (sweptUpstreamResolving re-verify
plus unmaskedPointedUpstream) after the sweeps, keeping git's 404 for
inherited survivors the snapshot never pointed at.
R18-3: an include-held value equal to the removed name blocked the
collateral-damage restore; the new discountGate discounts it from the
presence reads when the section is gone from every scope AND the name
no longer resolves at all — resolver probe (legacy $GIT_DIR/remotes
file, insteadOf alias) plus local-path probe (same-named directory
repo or bundle file; a sectionless name short-circuits before the path
probe, which would otherwise put a scp-like spelling on the network),
and a probe that cannot answer yields no-discount inside the gate
rather than aborting the rollback ahead of the merge arm. The discount
spans the remote, pushRemote and pushDefault presence reads; the
merge pairing reads the undiscounted presence; the exit-0
split-section path restores a second time after its worktree-half
completion so the gate never sees a half the completion removes.
R18-4: isSectionlessUpstream treated any colon as a network transport,
failing the unmask gate open over colon-after-slash local paths;
apply git's colon-before-first-slash rule, keeping the dot and win32
UNC carves.
R18-5: an invisible character split the skeleton collision group
(group key folded the raw name while the search folded the sanitized
one); key the group, member flags and render lookup on the sanitized
fold, keeping the polarity arm on the raw name.
R18-6: the settle effect restored mutation-start focus without
reading settle-time focus, yanking focus out of a control the user
moved to mid-flight; record the start element and skip the restore
when in-content focus moved elsewhere.
R18-7: the skeleton fold was not invariant under canonical
equivalence (positional table walk before the closing NFC);
canonicalize at the entrance (NFC is a canonical function) and cover
fused code points with a longest-decomposed-prefix table lookup,
mirrored in the generator so the table stays closed.
Round-7 audit additions on top of the R18 fixes: the discount gate's
local-path leg and its probe-failure carve-out (a live directory-repo
or bundle upstream must not read as dangling residue; a wedged
resolver must not abort the rollback), the sectionless-name
short-circuit, the split-section second restore, the pushDefault
arm's dead conjunct, and witnesses for each: directory-repo and
bundle no-re-point pairs, probe-failure merge restore, pushRemote
write-back, split-section completion write-back, and the kill-suite
pin that a scp-like removed name never reaches the path probe.
Rounds 8-9 closed the remaining witness gaps: the pushurl-only
section scope-leg witness (the fetch-side resolver and the path probe
are both blind to a pushurl-only section), the kill-suite pin that a
killed gate probe yields no-discount while a later gate surfaces the
kill, the split-section witness now asserting certification, the
sanitized render-lookup witness (the skeleton-escape tail spells the
fold-covered code point), the pushDefault write-back comment
re-attributed to the unmask arm that actually refuses its fixture, and
the generator's vestigial NFD argument removed (old and new generator
produce byte-identical tables). Accepted residuals recorded in code
comments and both design docs: merge-key re-sweep on late refusals,
the sibling-worktree blind spot of the gate's section leg, the
swallowed discount when a surviving `[branch <b>]` section takes an
in-section insert ahead of a later `[include]` directive, the ambient
guard's `=`-in-name miss, and the six formerly-unified ink classes of
the regenerated table.
Mutation-verified: each mutant reddens only its target witness.
Rounds 10-11 closed the last witness gaps and comment drift: the
win32 drive-letter fail-open in isSectionlessUpstream (a drive-letter
prefix is a LOCAL path on win32 — the carve is win32-gated — while
every other platform reads it scp-like ssh, so the colon rule answers
it sectionless and keeps every probe off the wire; witnessed per
platform, with zero ssh spawns on POSIX), the converge-arm comment's
false claim that a legacy file never reaches the arm (git's rm exits 0
over it, so the resolver leg is what skips the sweep on a retry), the
per-arm sanitized member-flag witnesses (all-ASCII-only and
case-twin-only), the inventory rows' three omitted witnesses, the
comment counts ("Three refusal sources", "One gate decision per
pass"), the win32 drive-letter carve's missing no-separator spelling
(has_dos_drive_prefix needs only letter plus colon, so `C:x` probes
locally on win32 too), the merge-churn residual's code-comment record
at the post-certification cleanup, and the generator paragraph the
entrance-NFC rewrite orphaned (the ink-equal-value phenomenon is
systematic — 1010 of 6564 values — and its example is now a real
composition exclusion, U+FB30).
Rounds 13-14 rebuilt isSectionlessUpstream as a faithful mirror of
git's url_is_local_not_ssh: has_dos_drive_prefix (any non-NUL ASCII
character, or one whole non-ASCII code point, plus a colon), the
is_valid_win32_path conjunct (NTFS-forbidden characters, reserved
device-name segments, segments ending in space or period, and the
whole-path trailing-dot magic), and forward-slash UNC — a drive-letter
url whose tail NTFS rejects is routed by git to ssh, so probing it
would spawn ssh from a config string; the predicate is exported and
unit-tested under a stubbed platform (original descriptor restored),
because the win32 legs are not executable off-win32. Both design docs
enumerate the win32 classification correctly, and the accepted
residuals are numbered one to four.
Round 15 closed the last predicate divergences against git's
url_is_local_not_ssh / is_valid_win32_path: reserved device names match
as git's PREFIX rule (terminated by end, `.`, `:`, or a separator,
after optional spaces; LPT accepts any digit, COM 1-9), the
per-segment trailing-period rule exempts all-period segments of
length <= 2 (`C:/..` and `C:/.` are valid local paths, not ssh), and
the colon/slash legs are evaluated before the drive-prefix leg exactly
as git's expression orders them; the unit table covers the divergent
shapes and three mutants (old reserved regex, reordered legs, old
period rule) each redden only their unit tests.
Recorded deferrals from rounds 15-17: the per-pass gate memo is a
latency-only guard with no behavioral witness (spawn count, never
outcome); core.protectNTFS=false on win32 makes git read reserved-name
drive tails as local while the predicate calls them sectionless
(fail-safe direction, explicit opt-out only, same family as the UNC
over-approximation); and 1024 of the 6564 emitted confusables keys are
not NFC fixed points and therefore unreachable under the entrance NFC
(dead weight, behavior-preserving to drop). Round 17 also added the
kill-suite witness for the discount gate's scope leg sitting outside
its try (a killed scope read aborts before any destructive cleanup,
while a killed probe leg answers no-discount inside the gate).
Deferred follow-ups (recorded, not dropped): the merge key a refusal
landing after unsetUpstreamKeys can re-sweep when the local remote
key does not stand (include-held residue on a pointed branch); the
sibling-worktree blind spot of the discount gate's section leg; the
swallowed discount when git's rm leaves the local `[branch <b>]`
section standing and an `[include]` directive sits after it; the
ambient guard's `[remote "a=b"]` miss; the race-only pre-existing
TOCTOU window between the union gate and the tail surviving-keys
gate; the six formerly-unified ink
classes of the regenerated confusables table; the remoteInkKey helper
unification; the equal-combining-class skeleton limitation; the
converge-arm duplicate dump spawn; a wire-visible error code for the
pre-flight refusals.
* fix(remotes): certify removals push-side as well as fetch-side
The removal certification's resolver leg answered fetch-side only:
`ls-remote --get-url` applies insteadOf and never sees
url.<base>.pushInsteadOf, the rewrite git uses when pushing — a name
kept resolving push-side by an alias racing in after the pre-flight
read was certified as no longer resolving. The union gate and the
discount gate now read the push-side alias prefixes from the same
all-scope dump their section legs already take, at zero extra spawns
(the kill suite's spawn accounting is unchanged): a name kept
push-live refuses 409 remote_still_configured, and a residue equal to
a push-live name is not discounted into a silent re-point. The
pre-flight owns the steady-state shape (a section plus its alias
refuses before destruction; the converge arm skips the same alias on
retries); these legs are the backstops for the race window.
Witnesses: the union-gate push-alias refusal and the discount-gate
push-alias no-discount kill-suite cases (each mutant reddens only its
witness); the docs state the push-side leg in both languages.
---------
Co-authored-by: qwen-code-dev-bot <[email protected]>
|
||
|
|
351b5fc51a |
ci(lint): stop new cli imports from the core package root (#11798)
Importing a value from the @qwen-code/qwen-code-core root evaluates all of core in every test whose import graph reaches the importing file, which is where most cli test time goes (#10908). The existing rule stops at packages/core/src, so cli kept adding root imports: 446 production files at #10957's merge, 465 eight days later. Enable @typescript-eslint/no-restricted-imports for cli production files with type-only imports allowed, reusing the barrel specifier set from no-core-root-barrel-import. The 372 files that value-import the root today are listed in eslint.legacy-core-barrel-imports.mjs; the list only shrinks. The new file is registered wherever eslint.legacy-filenames.mjs is: the lint-gate freshness list, the autofix sensitive-file classifier, and the hygiene fix agent's deny list. ESLint and Prettier (--experimental-cli) were run on the changed files, and the new block was exercised through ESLint's API against the real eslint.config.js. The scripts/tests vitest suites were not run locally. Refs #10908 |
||
|
|
f71a4e797e |
chore(pnpm): scope build approvals, pin the ACP zod peer, add a freshness lane (#11797)
Follow-ups left open when #11625 merged: its three unresolved review threads, the deferred finding in #11681, and #10524. - allowBuilds decisions now honour the whole key the way pnpm does: a bare name covers every version, an exact `name@version` (or a `||` union) covers only those, and a range or source-like key decides nothing. Reducing a key to its name let an approval scoped to one version cover the next (R1-10). - Pin `@agentclientprotocol/sdk>zod` to 3.25.76 so a pnpm worktree runs the zod the npm tree installs. Under zod 4 the SDK's own `instanceof z.ZodError` test stops matching and a malformed request answers -32602 instead of -32603; both versions are npm-locked, so the agreement gate cannot see the split (R1-1). - Cover web-shell's shipped client sources with the undeclared-import rule; it is the one published package whose sources are not under src/. Measured cost today: zero violations (R2-6). - Add a path-filtered workflow that regenerates pnpm-lock.yaml with `corepack pnpm import` and fails when the committed file differs, which is the freshness half set membership cannot cover (#11681). - setup-worktree: accept only an executable file on PATH, so a corepack left without its exec bit reports the actionable error instead of EACCES (#10524). - Name the esbuild divergence an accepted parity gap, and record what `fsevents: false` costs a macOS worktree. |
||
|
|
1e768979c5 |
chore(pnpm): gate pnpm-lock on package-lock and declare hoisted imports (#11625)
* chore(pnpm): gate pnpm-lock on package-lock and declare hoisted imports - Lockfile check: every pnpm-lock version must be locked in package-lock (one documented npm-lock gap, failing if it goes stale), and every dependency npm runs an install script for needs an explicit allowBuilds decision (fsevents: false records current behaviour). - Regenerate pnpm-lock with `pnpm import`, which is deterministic and drops 18 versions npm never locked; document it as the regeneration step. - Enforce import/no-extraneous-dependencies on shipped sources and declare the 15 imports that only resolved through hoisting, at already-locked versions. - Run the pnpm smoke workflow when package-lock.json changes. - Add the Stage 2 verification brief. Refs #10444 * chore(pnpm): regenerate vscode NOTICES and pin the new smoke path - NOTICES.txt: core's new OpenTelemetry declarations make the generator visit six Apache-2.0 entries in a different order. Same 655 entries, same text; only their order changes (6 header lines). - package-scripts test: expect package-lock.json in the pnpm smoke paths. * fix(pnpm): close lockfile-gate gaps found in review - fail closed when pnpm-lock.yaml has no packages section instead of printing the strongest success line over an unread graph - match git/file: dependency keys against npm's resolved field, whose pnpm key is the source rather than a version - count an allowBuilds entry only when its value is boolean, so pnpm's own 'set this to true or false' placeholder no longer passes the gate - drop the inert package-lock.json trigger from the pnpm smoke workflow; no step in that job reads it, and npm/pnpm agreement is already gated by ci.yml's Check lockfile step on the full profile - stage-2 evidence recipe: cover nested workspace roots in the reflink arm, sample peak worktree count at most 5 minutes apart, run the parity matrix in a throwaway workflow, and give the npm baseline the same skip guards the pnpm arm has - drive every gate branch with fixture-based negative tests * docs(verification): correct pnpm stage-2 measurement recipe Quiesce the df window, name the worktree sampler's working directory and forbid host cron, and register the throwaway workflow's size baseline so the parity run's test:ci does not fail under both installers. Co-authored-by: Qwen-Coder <[email protected]> Patrol-Run: qwen-pr-closeout/jmty6iqs0zv * docs(verification): fix stage-2 recipe's dispatch and macOS fs probe Step 2 now pushes the scratch branch before gh workflow run --ref (the ref is resolved server-side), notes the workflow token scope, and gives the merge-to- default / pull_request fallback when a branch-only dispatch is refused. Step 1 probes the checkout's own volume with diskutil info "$(pwd)" instead of the sealed read-only / system volume. Pushing, dispatching, and posting the results comment are marked operator actions. Co-authored-by: Qwen-Coder <[email protected]> Patrol-Run: qwen-pr-closeout/jmty8nwk9zy * test(lockfile): cover stale-gap and alias arms of check-lockfile Add two failure-branch cases: a knownNpmLockGaps entry that leaves the pnpm graph (the !pnpmVersions.includes arm), and an aliased install script reported under its real package name (the npmPackageName details.name arm). Both were untested and stayed green if the arm was deleted. Co-authored-by: Qwen-Coder <[email protected]> Patrol-Run: qwen-pr-closeout/jmty8nwk9zy * fix(lockfile): close the empty-env seam and name the overrides remedy - `CHECK_LOCKFILE_ROOT` was read with `??`, so an exported-but-empty variable made `root` the empty string and every path in this gate cwd-relative: it would then report on whatever lockfiles sit in that directory as if they were the repository's, and pass quietly when the cwd happens to be the repo root. Truthiness keeps the fixture seam and closes the empty case. - The version-agreement failure named exactly one remedy, `corepack pnpm import`, while pnpm-workspace.yaml carries eight `overrides` (three of them pin typescript) that no npm-side regeneration can reproduce. The message now names that layer, so a still-red gate points at what actually decides the value. Verified: `node scripts/check-lockfile.js` exits 0 on the committed tree, prettier and eslint are clean on the file, and both suites that execute the gate pass. Co-authored-by: Qwen-Coder <[email protected]> --------- Co-authored-by: qwen-code-ci-bot <[email protected]> Co-authored-by: Qwen-Coder <[email protected]> Co-authored-by: qwen-code-dev-bot <[email protected]> |
||
|
|
db8897d567 |
fix(export): shrink the exported transcript renderer to what a read-only transcript needs (#11038)
* fix(export): stop inlining the interactive Web Shell runtime in exported HTML /export html builds document-main.tsx with esbuild bundle:true and inlines the result into every exported file. The entry imported WebShellTranscript from the @qwen-code/web-shell package root, whose facade also reaches App, the daemon providers, the editor/terminal chrome and the full injected component stylesheet, so each export carried 19,523,259 runtime bytes (62x the legacy renderer) even for an empty session (#11031). Add a transcript-only subpath entry (@qwen-code/web-shell/transcript, mirroring the existing ./daemon-react-sdk subpath and the SDK's ./daemon/transcript pattern) that exports only the read-only transcript renderer, and point document-main.tsx at it. The entry is built in its own rollup run so it carries only the stylesheet reachable from transcript rendering instead of the whole component sheet. Exports stay fully self-contained: CSP, nonce handling and offline rendering are unchanged. Also add a hard size budget on the inlined document runtime in the template build, mirroring the MAX_*_BROWSER_BUNDLE_BYTES assertions in packages/sdk-typescript/scripts/build.js. The limit sits below the regression value so a repeat fails the build instead of landing silently. Measured on the generated document template (empty session): - before: 19,525,807 bytes raw / 4,775,943 gzip (runtime 19,523,259) - after: 17,966,485 bytes raw / 4,512,650 gzip (runtime 17,963,937) Co-authored-by: Qwen-Coder <[email protected]> Patrol-Run: qwen-issue-patrol/jmtn7fhrmj3 * fix(export): drop dead Shiki and CodeMirror from the export runtime The transcript-only entry stopped the interactive shell from reaching the inlined document runtime, but two large graphs still did, and the size budget could not see either of them. - Shiki (~9.7 MB of pre-minify inputs, the single largest) is unreachable in an export: `CodeBlock` returns before touching the highlighter when `renderMode === 'document'` and always renders a plain `<pre>`. It is a static import of `codeHighlighter.ts`, so esbuild cannot drop it. The document build now resolves `shiki` / `@shikijs/*` to a stub. Its Oniguruma WASM engine could not have started under the export CSP (`script-src 'nonce-…'`, no `'wasm-unsafe-eval'`) in any case. - CodeMirror (~1 MB) still reached the transcript entry: `UserMessage` imported three composer-tag string getters from `hooks/useComposerCore.ts`, which pulls the whole editor at top level. The getters move to `utils/composerTag.ts` (editor-free, and already imported by `UserMessage`); `useComposerCore` re-exports them for existing callers. Replace the byte-cap-only ratchet with a structural one: the document build now emits a metafile and fails when a forbidden module graph appears in the inputs (Shiki, the web-shell package root, CodeMirror), naming the reason. The byte cap stays as a coarse backstop and still needs re-measuring. Also fix a latent collision introduced by building the transcript entry in its own rollup run: both entries injected their stylesheet under the same `data-qwen-web-shell="component"` key, so a host importing both would keep whichever loaded first and silently lose the other's rules. Injection is now keyed per entry, and shadow-root style adoption concatenates every match. Refs #11031 * docs(verification): add the export-html runtime size verification plan The change to the inlined `/export html` runtime rests on measurements that cannot be taken on the machine that wrote it. Rather than leave that as a caveat in the PR description, commit the plan to the branch so any build-capable machine gets it by cloning: exact commands, the reference numbers to compare against and whose machine they came from, the premise the Shiki removal rests on plus a way to falsify it independently, the two budget constants that are knowingly stale, and what to report back. Follows the docs/verification/abort-controller-refactor layout; results belong next to it as results.md. Refs #11031 * test(web-shell): scope the transcript entry guard to its JS graph The not.toContain('vaul') guard ran against the whole bundle, but injectCssModules prepends the Tailwind-generated stylesheet as a single-line __qwenWebShellCss constant, and Tailwind v4 compiles classes from every scanned source file regardless of the entry's module graph — so drawer.tsx's data-[vaul-drawer-direction=…] variant selectors land in the transcript entry's CSS even though no transcript JS imports vaul (verified: 64 'vaul' occurrences in the injected CSS line, 0 in the JS remainder, no from"vaul" import specifier). Strip the injected CSS line before the graph guards. If the injection shape ever changes, the replace() is a no-op and the checks fail loudly rather than passing falsely. * fix(export): drop the dead echarts runtime from the export bundle CI measured the merged branch at 8,456,076 runtime bytes, and named the inputs: `echarts 3841596` and `zrender 624992` are still the largest single block in it. They arrive the same way mermaid does. `@datafe-open/markdown-chart-echarts` ends `createEChartsRenderer` with const loadECharts = options.loadECharts ?? (async () => await import('echarts')); and this repository never takes that default: `MarkdownChartRenderer` always passes a `loadECharts`, because `adaptLegacyRuntimeLoader` returns a function that throws 'Chart runtime is unavailable.' when no `loadEcharts` prop was supplied, and no call site in `packages/web-shell/client/` supplies one. So the fallback is dead in this codebase — but a bundler cannot prove that, and the export build is esbuild `format: 'iife'` with a single outfile, which cannot code-split, so the dynamic import is flattened straight into the renderer. Resolves `echarts` to a stub on exactly the reasoning the Shiki stub already uses in this file — unreachable in document mode — and adds echarts/zrender to FORBIDDEN_DOCUMENT_INPUTS so it cannot come back unnoticed. Chart blocks in an exported transcript already could not render; they threw 'Chart runtime is unavailable.' before this change and do the same after. Whether exports *should* render charts and diagrams is #11091, and this does not prejudge it: giving the renderer a real runtime stays a deliberate act. Also lowers the runtime budget from 19,000,000 to 8,700,000 using the CI measurement above. It is still loose, because the echarts stub in this same commit lowers the real number again — tighten it from the next green run rather than from a guess. The structural guard is the load-bearing check. * fix(web-shell): make the transcript entry's "no daemon providers" claim true Review found the entry docblock over-claiming. `WebShellTranscript.tsx` value-imported `transcriptBlocksToLocalizedMessages` from `hooks/useMessages`, and that module value-imports `useConnection` / `useTranscriptBlocks` / `useWorkspace` from the `daemon-react-sdk` barrel — so `dist/transcript.js` still carried the provider guards, including `useDaemonActions must be used within DaemonSessionProvider`. Gives that helper the same leaf-module treatment as the composer tags: the pure projection (and the `Translator` type it needs) moves to `adapters/localizedMessages.ts`, which imports nothing from the daemon SDK barrel, and `useMessages.ts` re-exports both so existing callers and its own test are unaffected. `build-artifact.test.ts` now asserts `dist/transcript.js` contains neither `DaemonSessionProvider` nor `DaemonWorkspaceProvider`, so the docblock's claim is pinned rather than asserted in prose. Also fixes the read-only recipe in `packages/web-shell/README.md`, which still taught the root import this PR makes wrong — a host following it would ship the interactive shell, which the reviewer measured as landing a document at ~8.8 MB, past the new cap. Same for the example in the read-only transcript design doc. Tightens the runtime budget to 7,400,000 / 7,300,000 warning, from the reviewer's local measurement of 7,275,173 bytes with the echarts stub in place (CI's 8,456,076 predates it). * fix(web-shell): drop the now-unused adapter import from useMessages The projection that used transcriptBlocksToDaemonMessages moved to adapters/localizedMessages.ts in |
||
|
|
077c57d200 |
refactor!: retire @qwen-code/webui (#9812)
* 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 ( |
||
|
|
7f7bce3174 |
feat: chat transcript mr2a html export (#10076)
* 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]> |
||
|
|
cd1ac72874 |
feat(opentui): bundle assets, CI matrix and parity tooling (Batch 7) (#10770)
* feat(opentui): add the build, CI and parity tooling for the renderer migration Batch 7 of the ink→OpenTUI migration (#8662): everything the renderer needs to be built, verified and shipped — ink stays the default. Bundled builds silently lose code-block syntax highlighting because @opentui/core resolves its tree-sitter assets package-relatively, which misses inside the esbuild bundle. Relocate the runtime assets (parser worker, grammar wasms/scm, web-tree-sitter, native render library) next to the bundle, and gate OTUI_ASSET_ROOT on the tree being complete for the running platform — @opentui/core throws on any missing key, so an incomplete relocation must fall back instead of half-configuring. Standalone archives gain a Bun runtime (the renderer needs bun:ffi) and per-target @opentui platform packages via the existing release packaging, with --runtime=node restoring classic packaging. The renderer matrix drives interactive E2E under node+ink and bun+opentui, but Batch 6's renderer gate silently falls back to ink on an unsupported runtime, so a green opentui leg could be a false green. QWEN_TUI_RENDERER_STRICT turns that fallback into a loud startup failure for the matrix legs only; user-facing default behavior is unchanged. Parity tooling: a tui-parity workflow with component snapshots and a no-flicker gate (zero full-screen clears, balanced DEC 2026) that runs offline without model credentials, an ink→opentui codemod with a self-test, the PTY/tmux comparison harnesses, and the cli scripts/ tree is now covered by the package typecheck. * fix(ci): build all packages in the tui-parity jobs With prepare skipped, npm ci leaves the CLI's workspace dependencies unbuilt, and a workspace-scoped build of the CLI alone resolves their types from a dist that does not exist yet. The parity jobs must run the repository-root build like the other E2E legs. * fix(build): enforce renderer strict mode and drop musl from standalone packages Address yiliang114's review on the Batch 7 build/CI work: - propagate QWEN_TUI_RENDERER_STRICT into RendererSelection so the dispatcher also fails loudly when the OpenTUI entry returns false or throws, closing the false-green path in the E2E renderer matrix - stage the OpenTUI platform packages only for the bun runtime and drop the -musl variants: the bundled Bun binaries are glibc-linked and cannot start on musl hosts, so the musl render packages claimed support the archives cannot deliver - wipe dist/opentui-assets before re-copying so a stale tree from an earlier bundle cannot satisfy the key-existence runtime gate - route the script-PTY capture branch through spawnScriptPty so the argv form follows the platform, and give it the destroy() that finish() expects from the node-pty-like interface - harden pty-e2e.sh (set -euo pipefail, mktemp+trap, full TCL escaping of the prompt) and tmux-compare.sh (missing-binary check, mktemp+trap) - pin the CI Bun setups to 1.3.14 = DEFAULT_BUN_VERSION so an upstream Bun release cannot flip the gating legs on its own * fix(build): keep classic Node packaging as the standalone default The temporary OpenTUI preview flavor (--runtime=bun) stays available but no longer replaces the default release archives, keeping Batch 7 additive for existing standalone users. * fix(scripts): compare prettier-normalized output in the codemod self-test Address F1 and F3 from the deep verification report: - The self-test compared the codemod's raw output against the prettier-formatted fixtures/after.tsx, so 2 of 17 tests failed as committed. Normalize both sides through the repo prettier config before comparing (tests 1 and 6); the harness awaits because prettier 3's format() is async-only. - Refresh the tui-parity.yml baseline entry from 2190 to the measured 2508 bytes so the ratchet tracks real growth. * fix(build): gate standalone opentui assets by runtime flavor Node archives carry no opentui-assets tree at all: the renderer needs bun:ffi, and cross-built archives would only hold another platform's native library that the all-or-nothing asset gate could never activate. Bun archives now prune every @opentui/core-* directory that does not belong to the build target, dropping the build host's library from the archive. The npm-package allowlist comment is corrected to match the observed fallback behavior. * test(cli): cover the OpenTUI strict-mode dispatch and e2e renderer matrix main() now has coverage for the four dispatch outcomes: strict mode throws both when the OpenTUI entry declines to start and when it boots with an error, and non-strict mode falls through to startInteractiveUI. resolveE2eCliCommand gains coverage for the opentui leg — bun on PATH resolves to bun, and a missing bun fails with the actionable error. |
||
|
|
fe34a5cf22 |
refactor(vscode-ide-companion): complete the WebShell UI cutover (#9811)
* 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 (
|
||
|
|
a511ce4a12 |
feat(desktop-shell): restore the brand builder skill for the Tauri shell (#10164)
* feat(desktop-shell): restore the brand builder skill for the Tauri shell The Electron-era desktop-brand-builder skill was removed with packages/desktop in #9085, leaving the Tauri shell without a white-label customization path. Restore it against the new branding hooks: tauri.conf.json, the icon set, and the bootstrap UI. The bundled script is dependency-free Node, regenerates icons via tauri icon, and empties updater endpoints so branded builds never touch the official feed. * fix(desktop-shell): give brand builder scripts node globals for eslint The desktop-brand-builder skill script runs under node but lives outside every existing node-scripts glob in eslint.config.js, so lint:ci failed with 7 no-undef errors on process/console/URL in brand-create.mjs. Add the skill scripts path to that existing block. Co-authored-by: Qwen-Coder <qwen-coder @alibabacloud.com> * fix(desktop-shell): complete updater identity patching and fix npx spawn on Windows - When branded build has no custom updater endpoints, also clear the official pubkey and set bundle.createUpdaterArtifacts to false so the Tauri bundler does not produce signed updater artifacts that no feed will serve. - Add shell: true to the npx spawnSync call so it works on Windows where npx is npx.cmd. Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): address review findings for brand builder skill - Add brand-builds/ to .gitignore (R1-19) - Validate logo is a file, not a directory (R1-8) - Document target-specific bundle path in SKILL.md (R1-17) Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): harden brand-create against injection and shell safety - Use function replacers in replaceAll to prevent $& pattern interpretation when appName contains dollar signs (R1-3) - Quote logo path in shell spawn to handle paths with spaces (R1-4) - Add image extension validation for logo files (suggestion R1-6) - Document silent config mutations in SKILL.md (suggestion R1-5) Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): document cross-compile workflow and guard against re-run - SKILL.md: document that build:runtime must be re-run with QWEN_DESKTOP_TARGET set before each cross-compile target, otherwise the packaged artifact contains a wrong-arch Node binary. - brand-create.mjs: detect already-branded shell-root (productName no longer 'Qwen Code Desktop') and fail early with a clear message, preventing silent stale results from non-idempotent re-runs. - SKILL.md: add explicit 'never re-run in the same clone' warning to Failure Handling section. Addresses review findings R1-16 (cross-compile docs) and idempotency guard from qwen-code-ci-bot. Co-authored-by: Qwen Code <[email protected]> * fix(desktop-shell): harden brand-create against updater crash, icon misreport, and JS injection - Keep updater pubkey as empty string instead of deleting it (the tauri-plugin-updater schema requires `pubkey: String` with no default; removing it causes deserialization failure at startup). - Report accurate icon replacement status when `tauri icon` fails on non-PNG logos (previously claimed icon.png was replaced even when it was not). - Escape single quotes in appName before injecting into bootstrap.js single-quoted string literals (an appName like "Bob's App" caused SyntaxError). - Add root `npm install` step to SKILL.md workflow (build:runtime shells out to repo root which needs cross-env and other root devDependencies). Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): eliminate shell injection in brand icon generation (R1-4) Replace shell:true npx spawn with direct Node invocation of the Tauri CLI entry point. The logo path is now passed as a plain argv element, preventing command substitution via crafted filenames ($(cmd), `cmd`). Falls back to shell-less npx when @tauri-apps/cli is not resolvable from the shell root. Adds a test verifying generateIcons contains no shell:true usage. Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): require updaterPubkey when custom updater feed is configured (R1-1) When a brand supplies updaterEndpoints, the matching signing pubkey must also be provided. Without this check, custom feeds were paired with the official pubkey, breaking update verification permanently. loadConfig now fails fast when updaterEndpoints is non-empty but updaterPubkey is missing. patchTauriConfig sets the pubkey from the brand config when endpoints are present. SKILL.md documents updaterPubkey and TAURI_SIGNING_PRIVATE_KEY usage. Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): reject appName matching pristine default to close re-run guard bypass (R3-4) When appName equals 'Qwen Code Desktop' (either explicitly or derived from brandId like 'qwen-code-desktop'), the detectAlreadyBranded guard never fires on the first run, allowing a second run to double-patch bootstrap strings. loadConfig now rejects this appName at validation time, before any files are mutated. Covers both explicit override and derived paths. Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): silence empty-block lint in brand-create-safety test Add /* best-effort cleanup */ comments inside two catch blocks used for teardown so ESLint no-empty rule is satisfied. Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): escape backslashes and newlines in appName for bootstrap.js injection brand-create.mjs only escaped single quotes before splicing appName into the single-quoted string literals of bootstrap/bootstrap.js. A free-form appName ending in a backslash (or containing a newline) produced syntactically invalid generated bootstrap.js while the script still exited 0 reporting bootstrapPatched. Derive the injected content via JSON.stringify so backslashes, newlines, and control characters are all escaped, then re-quote it for the single-quoted context. Add a safety test covering hostile appName values. Co-authored-by: Qwen-Coder <[email protected]> * fix(desktop-shell): HTML-escape appName in bootstrap/index.html, fail closed on missing updater section (R5-1, R5-8) R5-1: appName was spliced raw into bootstrap/index.html (<title>, alt attribute, <h1>, <h2>), so free-form brand names with <, > or " produced broken markup (and a </title> breakout). The index.html path now uses an HTML-escaped form while bootstrap.js keeps its JS-literal escaping. R5-8: when the target shell-root's tauri.conf.json has no plugins.updater section, the brand's validated updaterEndpoints/updaterPubkey were silently discarded while brand-create exited 0 reporting them as applied. Fail closed before any file is written, leaving the config unmutated. Tests: hostile-appName index.html fixture assertions (escaped output, no raw breakout) and a no-plugins.updater shell-root case (non-zero exit, stderr names the missing section, config byte-identical). Both new assertions go red when the corresponding fix is removed. Suite 8/8 green; prettier + eslint clean on both changed files. Co-authored-by: Qwen-Coder <qwen-coder @alibabacloud.com> * fix(desktop-shell): fail on non-array updaterEndpoints in brand.json A scalar updaterEndpoints (e.g. a string typo of the JSON-array shape documented in SKILL.md) was silently coerced to [] before the updater-safety guards ran, so brand-create exited 0 while shipping the brand with in-app updates permanently disabled. Reject any non-array value with an explicit error naming the expected shape; omitted or [] still disables updates as documented. Co-authored-by: Qwen-Coder <[email protected]> --------- Co-authored-by: Qwen-Coder <qwen-coder @alibabacloud.com> Co-authored-by: Qwen-Coder <[email protected]> Co-authored-by: Qwen Code <[email protected]> Co-authored-by: root <[email protected]> |
||
|
|
6652fdc9f6 |
refactor(core): centralize worktree config derivation (#9915)
* refactor(core): centralize worktree config derivation * refactor(core): centralize agent config derivation (#9918) * refactor(core): centralize agent config derivation * refactor(core): centralize scoped config profiles (#9920) * fix(core): keep approval-mode transitions working on derived teammate and dispatch configs Give every per-agent config child-local approval state, not just the ones spawned with an explicit mode: tools bind to the config and teammate mode switches (Shift+Tab) plus 'Proceed always' confirmations call setApprovalMode on it, which the derived-Config guard rejects without an approval profile. Snapshot the base mode when none is requested so no AUTO strip is acquired and cleanup stays a no-op. Layer an approval profile over the workflow-orchestrator's derived dispatch contexts (worktree isolation / workingDir) as agent.ts does, with cleanup in the outer finally. * fix(core): anchor plans-directory assertions at the plans-owning base Config Derived agent profiles rebind targetDir to their own workspace, but the plan file stays in the owning base's configured plans directory. The containment assertions in savePlan/loadPlan compared against the derived workspace and threw FatalConfigError for teammates whose cwd differs from the parent project root, which savePlanBestEffort swallowed into a debug warning — silently dropping the plan. Resolve the anchor to the Config that owns the plans-directory state instead. * test(core): cover deriveAgentConfig workspace rebinds Mirror the deriveWorktreeConfig pairing test: assert the public getter overrides (getCwd/getProjectRoot/getWorkingDir/getTargetDir, plan-file path) and the paired private targetDir/cwd field writes plus own workspaceContext/fileDiscoveryService, so a refactor that drops any rebind fails loudly instead of leaking parent-tree reads into spawned agents. * test(scripts): add flat-config integration test for no-config-object-create Mirror no-core-root-barrel-config.test.js: load the real eslint.config.js via new ESLint({overrideConfigFile}) and lintText virtual packages/core/src/** paths, so a future edit to the flat-config wiring (plugin key, rule name, ignores) that silently stops the gate applying to packages/core/src/** turns this test red instead of degrading the invariant with no signal. --------- Co-authored-by: Shaojin Wen <[email protected]> |
||
|
|
50c553550e |
fix(live): restore Live Host after desktop removal (#9994)
* fix(live): restore the standalone Live Host Co-authored-by: Qwen-Coder <[email protected]> * fix(release): restore Live Host release feeds Co-authored-by: Qwen-Coder <[email protected]> * chore(skills): remove the unsupported desktop pet skill * fix(ci): stabilize Live Host validation Co-authored-by: Qwen-Coder <[email protected]> * test(cli): complete session swap telemetry fixture Co-authored-by: Qwen-Coder <[email protected]> --------- Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
ce72ddbe6c |
feat(desktop): remove packages/desktop after OpenWork fork; keep the Tauri upgrade bridge (#9085)
OpenWork (modelstudioai/openwork) has forked the Electron desktop code and is self-contained now, so retire the Electron package and its release/sync machinery from this repo: - Delete packages/desktop (Electron app, live-host app, bun workspace). - Retire scripts/desktop-openwork-sync.ts and the desktop-openwork-sync root script; the OpenWork sync is no longer needed. - Retire .github/workflows/live-host.yml, live-host-release.yml and sync-live-host-to-oss.yml; live-host releases now live in OpenWork. The CLI-side packages/cli/src/serve/live code stays for now (separate cleanup). - Retire scripts/check-voice-guard-sync.js (cli<->desktop parity only) and its CI step. - Clean up remaining references: root package.json workspaces negation and package-lock.json, eslint/prettier/yamllint ignores, architecture docs, web-shell skill descriptions, and review-lib workspace fixtures/comments (renamed to point at packages/desktop-shell, the remaining negation). Deliberately kept: the Electron->Tauri upgrade bridge — desktop-release.yml (incl. the electron_bridge input), create-electron-bridge-manifest.mjs, sync-desktop-to-oss.yml (mirrors Tauri desktop-shell artifacts only) and everything under packages/desktop-shell. |
||
|
|
a60cbbc54a |
refactor(core): make utils/ a leaf layer (#9778)
* refactor(core): make utils/ a leaf layer Eliminate every runtime (value) upward import from packages/core/src/utils production modules so utils/ can become a leaf layer with no runtime dependency on the rest of core. Two mechanisms, no behavior change: - Relocate domain-coupled modules out of utils/ into their owning module (agents, config, core, memory, services, tools), and move generic constants/types that live elsewhere into utils/. All `git mv` moves keep history; every import that pointed at a moved file is rewritten. - Extract the remaining value imports as small leaf modules inside utils/ (AuthType, isTool, ToolErrorType, DEFAULT_QWEN_MODEL) and re-export them from their original owners so cross-package consumers are unaffected. doesToolInvocationMatch moves into shell-utils, its only production consumer. Only type-only imports now cross the utils/ boundary. The two deferred inversions in debugLogger (Storage, getTraceContext) are stateful and left for a follow-up. * chore(core): enforce utils/ leaf layer with lint rule Add architecture/no-core-utils-upward-import, which flags runtime (value) imports that leave packages/core/src/utils. Type-only imports, sibling utils imports, and external package specifiers stay allowed; the two deferred debugLogger inversions (config/storage, telemetry/trace-context) are carried on an explicit allowlist. Enable the rule as an error on core sources and cover it with Linter-based tests. * fix(core): restore iconv-lite tree-shaking for sync-file-encoding The utils leaf-layer refactor moved sync-file-encoding from utils/ to services/, but the esbuild tree-shake plugin still matched the old ./utils/ specifier, so its sideEffects:false marker no longer applied and the ACP startup closure regained a static iconv-lite import. Point the onResolve filter at the new ./services/ path. * fix(ci): catch stale integration imports earlier * fix(core): close utils boundary review gaps * fix(core): close self-reference boundary gaps * ci: re-trigger after self-hosted runner checkout EACCES |
||
|
|
56db17bd4c |
refactor(cli): enforce utils leaf-layer dependency direction (#9146) (#9737)
* refactor(cli): enforce utils leaf-layer dependency direction (#9146) Move domain-coupled modules out of packages/cli/src/utils into the directories that own them: config/ (dialogScopeUtils, settingsUtils), i18n/ (languageUtils), ui/ (handleAutoUpdate, standalone-update, systemInfo, systemInfoFields, update-relaunch, commands, doctorChecks), nonInteractive/ (nonInteractiveHelpers, chat-recording-failure, tool-result-boundary-diagnostics, permission-suggestions), serve/ (sandbox), services/housekeeping/ (scheduler, non-interactive-scheduler), and commands/review/ (findings). Extract the generic normalizePartList helper into utils/normalize-part-list.ts so utils consumers keep importing downward, and move the MergeStrategy enum into utils/deepMerge.ts (its owner). Add an eslint architecture rule (no-utils-upward-import) that forbids value imports from utils/ back up into a domain directory. Type-only imports stay exempt: they are erased at compile time and cannot create a runtime cycle (Settings in modelConfigUtils, CommandContext in sessionPaths). No behavior change: typecheck, build, and the affected unit tests pass. * fix: use Qwen Team 2026 license header on new files (#9146) * chore: refresh stale utils/ path references after leaf-layer move (#9146) * docs: reconcile no-utils-upward-import header with the allowed type-only set (#9146) * fix(cli): allowlist sandbox process.env accesses after leaf-layer move (#9146) * chore(ci): re-record qwen-autofix.yml size baseline after #9677 (#9146) #9677 recorded qwen-autofix.yml at 392111 bytes while the file it committed was already 397656, so every PR that merged main after it tripped the growth ratchet. Re-record the actual size; the file itself is unchanged by this PR. * fix(review): drop the stale utils/findings.ts digest root after the leaf-layer move (#9146) The #9146 move returned findings.ts to commands/review/, but the digest root lists merged from main still pinned it under utils/, where the file no longer exists — the absent root darkened every review's staleness check and failed review-source-digest.test.ts. Drop the stale file-shaped root from both digest copies and their pins; the commands/review/ directory root covers the validator at its new home, and the two utils helpers keep their file-shaped roots. * fix(review): colocate seatbelt profiles with the sandbox module (#9146) * fix(review): exempt inline type-only specifiers from the utils upward-import rule (#9146) * fix(review): report upward inline type-specifier imports under verbatimModuleSyntax (#9146) Co-authored-by: Qwen-Coder <[email protected]> * test(review): pin mixed-specifier and zero-specifier upward imports in the utils rule (#9146) Co-authored-by: Qwen-Coder <[email protected]> * test(review): anchor the nested-checkout utils rule fixture on the last marker (#9146) Co-authored-by: Qwen-Coder <[email protected]> * test(review): pin that the utils/findings.ts digest root stays removed (#9146) Co-authored-by: Qwen-Coder <[email protected]> * fix(review): reword stale-bundle SCOPE header to the post-move helper shape (#9146) * test(review): drop the pre-move utils/findings.ts from the skill-parity fixture (#9146) * test(serve): derive the seatbelt colocation tripwire from BUILTIN_SEATBELT_PROFILES (#9146) * fix(architecture): fail closed on computed dynamic imports in the utils leaf rule (#9146) * fix(cli): point settings.test.ts at the post-move settingsUtils path (#9146) main updated settings.test.ts after this branch moved settingsUtils.ts from utils/ into config/, and the merge kept main's old import specifier, which vite fails to resolve. Repoint it at ./settingsUtils.js; every other consumer already uses the new path. * fix(cli): close utils boundary review gaps * test(cli): cover utils boundary allow paths --------- Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
be891657f7 |
refactor(node-repl)!: deliver the persistent Node REPL as a standalone MCP server (#9499)
* 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]> |
||
|
|
10c647f320 |
refactor(core): remove root barrel self-imports and enforce the boundary (#9635)
* refactor(core): remove root barrel self-imports * fix(core): activate root barrel boundary rule * test(core): cover root barrel export visitors * fix(core): remove unused boundary constant * fix(core): correct misplaced imports flagged by root barrel rule coreToolScheduler: ToolExecutionStatus is exported from core/turn.ts, not tools/tools.ts; was also duplicated in the tools import block. nonInteractiveToolExecutor: RuntimeContentGeneratorView is exported from agents/runtime/agent-context.ts, not core/contentGenerator.ts. Both were surfaced by the new no-core-root-barrel-import rule in #9152. * fix(core): complete telemetry mock and harden barrel rule edge cases extensionManager.test: the ../telemetry/loggers.js mock was missing logExtensionInstallEvent, logExtensionUninstall, and logExtensionDisable, which the source now imports from that path after the barrel cleanup. This caused 53 test failures. no-core-root-barrel-import.js: added package-specifier detection (@qwen-code/qwen-code-core), template-literal dynamic import support, depth-0 ./index.js handling, and __tests__ exemption parity with the test-file check. Added trailing newline. Tests: added coverage for all new edge cases in both rule test files. Refs #9152 * fix(core): close package-level barrel gap and coverage holes The barrel rule blocked only specifiers resolving to the src-level index.{js,ts}; the package-level barrel (packages/core/index.ts, which re-exports the src barrel) remained reachable via one extra ../ hop. Match ../index.{js,ts} so core production files cannot re-import the root barrel through that path. Also: hoist the duplicated src-root marker to a single constant, reword the rule message so it no longer hardcodes ../index.js, pin the .ts spelling branch, fix the vacuous fixtures-exemption case, and add a cross-directory flat-config fixture so a narrowed files glob fails the integration test. Refs #9152 * fix(core): flag barrel subpaths and inline type imports in the root barrel rule * fix(core): harden no-core-root-barrel-import rule Anchor the source-root marker on its last occurrence so nested checkouts resolve correctly, reject relative imports of the compiled dist barrel, and treat .spec files as tests. Adds regression coverage for each. |
||
|
|
b455bad5e5 |
refactor(cli): keep acp-integration off serve internals (#8084) (#9144)
* refactor(cli): keep acp-integration off serve internals (#8084) The dependency direction set in #8084 regressed: native Live Voice ( |
||
|
|
a29c8b11db |
refactor(cli): stop utils/ importing serve/ and the UI layer (#9146) (#9147)
packages/cli/src/utils is the directory every other directory imports (83 from ui, 30 from the package root, 23 from config), so it only works as a leaf. It currently imports back into six siblings, which is what makes the package's directory graph cyclic. Three moves, each decided by who actually consumes the module: - serve/fast-path-argv.ts moves down into utils/. It is 25 lines with no imports, doing pure argv string manipulation, consumed from three layers. A utility filed under the daemon; relocate the target rather than rework the caller. Renamed serve-fast-path-argv.ts since fast-path-argv is ambiguous among general helpers. - utils/windowTitle.ts moves up into ui/utils/. Its only consumers are AppContainer and startInteractiveUI, and it imports StreamingState, ICON and the OSC-8 helper. - utils/systemInfo.ts imports formatMemoryUsage from core directly instead of through ui/utils/formatters.ts, a one-line re-export of the same symbol. It cannot move into ui/ because the daemon status provider consumes it, so the import is inverted instead. Adds a no-restricted-imports rule for utils/** rejecting serve/. Scoped to serve/ only: that direction is now completely clean, so the rule states something true. The remaining ui/, config/, i18n/ and nonInteractive/ edges are tracked in #9146. Runtime upward imports out of cli/src/utils: 25 -> 20; utils -> serve 1 -> 0, eliminating that cycle; utils -> ui 7 -> 3. |
||
|
|
cb2555c7c5 |
feat(desktop): package Web Shell as a release-ready desktop app (#8132)
* feat(desktop): add Web Shell Tauri proof of concept * feat(desktop): prepare Web Shell shell for release * fix(desktop): make release dry runs portable * fix(desktop): harden cross-platform release smoke * fix(desktop): stabilize Windows and Linux CI * fix(desktop): scope bootstrap env to daemon * fix(desktop): stabilize packaged app smoke * fix(desktop): diagnose Linux packaged startup * fix(desktop): address release readiness review * fix(desktop): address follow-up review findings * fix(desktop): address runtime review blockers * fix(desktop): gate cookie auth acceptance behind desktop bootstrap flag - Cookie→Bearer translation middleware now only active when desktopShellBootstrap is enabled - Use timing-safe comparison for bootstrap token validation * fix(desktop): replace cookie handshake with URL fragment auth - Navigate the desktop WebView to /#token=<token>; the fragment never reaches the server, so drop the desktop cookie bootstrap middleware, its cookie->bearer translation, and the related serve tests - Skip the deferred-runtime auth gate for pre-auth Web Shell routes (GET|HEAD / and /assets/*): a document navigation cannot carry an Authorization header, so the fast-path window used to answer the first desktop navigation with 401 Unauthorized until a manual reload - Poll /health?deep=true before navigating: deep health stays 503 (reason: bootstrap) until the runtime app that mounts the Web Shell is ready, so readiness can no longer race the deferred window - Run the folder picker off the main thread and only store the runtime after the WebView navigation succeeds - Enable withGlobalTauri plus a bootstrap capability so the bootstrap page can subscribe to desktop lifecycle events - Update smoke-packaged to assert the fragment contract (unauthenticated root navigation 200, no cookies minted, API routes still 401) and sync the release design doc * fix(desktop): fix Linux smoke log path, add runtime .gitkeep, correct README (#8132) * fix(desktop): close release readiness gaps * fix(cli): keep deferred serve auth gate closed when web shell unmounted (#8132) * fix(desktop): address review feedback on auth gates and runtime bundle (#8132) - Cover the method guard in isPreAuthWebShellRequest: assert unauthenticated POST to / and /assets/* is still 401 during the deferred runtime window. - Add unit tests for is_allowed_navigation covering the unset origin, set origin, and bootstrap-after-origin cases. - Drop DEV:'true' from the release bundle step so the esbuild metafile is no longer shipped as dead weight in the desktop runtime. * fix(desktop): address review feedback on runtime extraction and release workflow (#8132) - Extract .zip Node archives with unzip so Linux cross-builds for win32-x64 no longer crash on GNU tar. - Build the Windows signing config with ConvertTo-Json instead of backslash escapes, which PowerShell treats as a parse error. - Fetch the runtime Web Shell without a bearer token so the smoke test exercises the pre-auth navigation path the shell relies on. - Make GitHub release creation idempotent so a re-run after a partial publish uploads assets instead of failing on the existing tag. * fix(desktop): normalize artifact filenames to prevent updater 404s (#8132) GitHub rewrites spaces to dots when release assets are uploaded, but the updater manifest encoded spaces as %20 via encodeURIComponent. This caused every platform's auto-update URL to 404 on published releases. Replace spaces with hyphens in the Collect artifacts step for all platforms so the local filename, the manifest URL, and the published asset name agree by construction. Update test-release.js fixtures to match and assert no artifact name contains a space. * fix(desktop): address review feedback on security, lint, and code quality (#8132) * fix(desktop): address review feedback on smoke test, error UX, and window state (#8132) * fix(desktop): address review feedback on crate build, recovery UX, auth gate, and CI (#8132) * fix(desktop): address review feedback on settings race, version script, and log growth (#8132) * fix(desktop): address review feedback on retry, auth gate, and release clobber (#8132) * fix(desktop): gate commands to bootstrap origin and show native update dialog (#8132) * fix(desktop): use matches! instead of PartialEq on JoinError result (#8132) * fix(desktop): wait for deferred runtime in smoke tests and sync release flags on clobber (#8132) --------- Co-authored-by: Qwen Code Bot <[email protected]> Co-authored-by: qwen-code-dev-bot <[email protected]> Co-authored-by: qwen-code-ci-bot <[email protected]> Co-authored-by: Qwen Code Autofix <[email protected]> |
||
|
|
8f667f5bdc |
feat(integrations): add retrieval-only external context search (#7586)
* feat(integrations): add direct external context provider Co-authored-by: Qwen-Coder <[email protected]> * fix(integrations): harden external context failure handling Preserve provider timeout classification, reject ambiguous Mem0 statuses, release rejected response bodies, and clarify credential and workspace deployment boundaries. Co-authored-by: Qwen-Coder <[email protected]> * refactor(integrations): narrow external context to retrieval Limit Phase 1 to one provider-bound search tool, remove hooks and writes, and document the direct profile's actual permission and isolation boundaries. Co-authored-by: Qwen-Coder <[email protected]> * fix(integrations): harden external context deployment Pin the managed MCP source through an administrator-owned command-line configuration, document the Direct Profile trust boundary, and remove unused logging/runtime abstractions. Co-authored-by: Qwen-Coder <[email protected]> * fix(integrations): preserve external context results Co-authored-by: Qwen-Coder <[email protected]> * fix(integrations): honor provider proxy settings Install an environment-aware dispatcher before the external context MCP server starts so enterprise egress proxy and NO_PROXY settings apply to provider requests. Document the managed launcher environment and cover startup wiring. Co-authored-by: Qwen-Coder <[email protected]> * fix(integrations): diagnose invalid proxy settings Classify proxy dispatcher construction failures as sanitized configuration errors so managed deployments can identify an invalid proxy environment without exposing proxy credentials. Co-authored-by: Qwen-Coder <[email protected]> --------- Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
5c82857fea |
Add harness infrastructure for web-shell package (#6517)
* test(web-shell): add browser and lint harness * test(web-shell): harden browser smoke harness * fix(web-shell): guard mock daemon model state * test(web-shell): remove unused scenario harness * fix(web-shell): remove stale lint disables * test(web-shell): make matchMedia stub writable * fix(web-shell): exclude tests from package typecheck * test(web-shell): tighten mock daemon route contract * Update packages/web-shell/client/e2e/utils/mockDaemon.ts Co-authored-by: qwen-code-ci-bot <[email protected]> * test(web-shell): clear stale SSE connections * ci(web-shell): gate smoke on full CI profile --------- Co-authored-by: ermin.zem <[email protected]> Co-authored-by: qwen-code-ci-bot <[email protected]> Co-authored-by: Shaojin Wen <[email protected]> Co-authored-by: 易良 <[email protected]> |
||
|
|
23c6c7032a |
feat(mobile-mcp): vendor mobile-mcp with opt-in 0-1000 relative coordinates (#6235)
* Squashed 'packages/mobile-mcp/' content from commit c5d7d27fd git-subtree-dir: packages/mobile-mcp git-subtree-split: c5d7d27fd61e4762e15ae4b1c68b6c011be88bb7 * feat(mobile-mcp): vendor mobile-mcp with opt-in 0-1000 relative coordinates Fork mobile-next/mobile-mcp (v0.0.61) into packages/mobile-mcp/ via git subtree, renamed to @qwen-code/mobile-mcp with the following additions: Relative coordinate shim (src/coord-norm.ts): - MOBILE_MCP_COORDINATE_SPACE=1 enables 0-1000 normalized coordinates - MOBILE_MCP_COORDINATE_SCALE configurable (default 1000, 999 for mobile_use) - Input denormalization for click/double_tap/long_press/swipe - Output normalization for list_elements and get_screen_size - Tool description rewriting when enabled - Default off = zero behavior change Android enhancements: - mobile_install_app: -r/-g/-d/-t install flags (Android only) - mobile_ui_dump: full UIAutomator XML hierarchy dump - mobile_adb_pull / mobile_adb_push: file transfer via ADB Infrastructure: - cd-mobile-mcp.yml: npm publish workflow (tag mobile-mcp-v*) - scripts/sync-from-upstream.sh: git subtree pull for upstream sync - .vendored-from / .vendored-patches.md: vendoring metadata - Upstream telemetry disabled by default - eslint.config.js: exclude packages/mobile-mcp from root lint * chore(mobile-mcp): update package-lock.json for workspace dependencies * fix(mobile-mcp): quote all YAML strings to pass yamllint * fix(mobile-mcp): fix cd workflow yaml to pass both yamllint and actionlint * fix(mobile-mcp): address review findings on our additions - ensureScreenSize: log warning instead of silent failure (#4) - invalidateScreenSize on orientation change (#5) - adb_push: path.posix.resolve to prevent /sdcard/ traversal (#6) - adb_pull: readOnlyHint → destructiveHint (writes local file) (#9) - adb_push: remove validateOutputPath on read-source local_path (#11) - normalizeElementResult: log error instead of bare catch (#16) - rewriteDescription: remove dead duplicate regex (#17) - cd workflow: add test step between build and publish (#19) * fix(mobile-mcp): update server.json identity and fix package.json main entrypoint --------- Co-authored-by: Shaojin Wen <[email protected]> |
||
|
|
32d2f4674d |
ci: add fork PR safety precheck (#5926)
* ci: add fork PR safety precheck * fix(ci): lint PR safety precheck script |
||
|
|
5581424b6b |
feat(browser-ext): revive Chrome extension via daemon-direct architecture (#5777)
* 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]> |
||
|
|
adc2bce414 |
feat(cua-driver): vendor qwen-cua-driver with opt-in 0–1000 relative coordinates (#5896)
* feat(cua-driver): vendor trycua/cua driver with 1000-normalized coordinate support
Vendor libs/cua-driver from trycua/cua into packages/cua-driver as the
basis for qwen-code's computer-use backend, adding an opt-in relative
(1000x1000 normalized) coordinate mode for Qwen-VL clients.
- coord_norm.rs: 0-1000 <-> pixel conversion, per-(pid,window_id) size
cache, tools/list description rewrite (TDD, 27 tests)
- ToolRegistry: normalized field + invoke input/output hooks
- protocol.rs: system-instruction coordinate wording switched by mode
- serve.rs: daemon list path description rewrite (input_schema aware)
- main.rs: CUA_DRIVER_RS_COORDINATE_SPACE env seed
Default coordinate_space=pixels => zero behavior change for existing
pixel clients. Set CUA_DRIVER_RS_COORDINATE_SPACE=normalized_1000 to
enable. Excludes rust/target build output.
* feat(cua-driver): make normalized coordinate scale configurable
Add CUA_DRIVER_RS_COORDINATE_SCALE (default 1000) so the normalization
full-scale can absorb the Qwen 999-vs-1000 cookbook ambiguity without a
recompile. norm_to_px/px_to_norm now take an explicit scale; denormalize_args
reads the process-wide COORDINATE_SCALE seeded once at startup from env.
* ci(cua-driver): add cross-platform release workflow for vendored driver
Standalone GitHub Action that builds, signs, and releases the vendored
cua-driver under packages/cua-driver. Adapted from upstream trycua/cua
cd-rust-cua-driver.yml:
- macOS: universal binary (lipo arm64+x86_64), codesigned + notarized into
CuaDriver.app using qwen-code's existing secrets (MAC_CSC_LINK cert +
App Store Connect API key notarization); Developer ID identity is
auto-discovered from the imported cert.
- Linux: x86_64 + arm64, built in debian:11 for a glibc 2.31 floor.
- Windows: x86_64 + arm64, unsigned (no EV cert, matches upstream).
- Release: softprops/action-gh-release on cua-driver-rs-v* tags or manual
dispatch, prerelease.
Triggered by tag push (cua-driver-rs-v*) or workflow_dispatch.
* chore(cua-driver): rebrand vendored driver as qwen-cua-driver
Rename the vendored trycua/cua driver so the fork installs and runs
independently of any upstream trycua install:
- binary cua-driver -> qwen-cua-driver
- bundle CuaDriver.app -> QwenCuaDriver.app
- bundle id com.trycua.driver -> com.qwencode.cua-driver
Updates the cargo/uia manifests, Info.plist, bundle/proxy launch paths,
permission/health-report wording, the install/build scripts, and the
cross-platform release workflow.
* feat(cua-driver): finish relative-coordinate mode — toggle, scale, zoom/move_cursor
- CUA_DRIVER_RS_COORDINATE_SPACE is now a 1/0 toggle (via is_env_truthy);
default off keeps pixel mode byte-identical to upstream.
- Thread CUA_DRIVER_RS_COORDINATE_SCALE through every coordinate surface
(was hardcoded 1000): input denormalization already used it; now the
rewritten screenshot dims, the tool/param descriptions, and the agent
instructions track the configured scale too.
- Normalize zoom (window basis) and move_cursor (screen basis) inputs and
rewrite their descriptions, alongside click/double_click/right_click/drag.
- Fix zoom on downscaled (Retina) windows: apply the get_window_state resize
ratio so the crop lands on the region the agent saw. Normalized mode only;
pixel-mode zoom unchanged.
All coordinate behavior stays gated on the normalized flag, so the default
(pixels) path is unchanged from upstream.
* chore(cua-driver): add upstream-sync script (git subtree unusable here)
`git subtree split --prefix=libs/cua-driver` hangs on a commit deep in
trycua/cua's history, so the subtree add/pull workflow isn't usable for
the vendored driver (and a pull would re-split + re-hang every time).
Add scripts/sync-from-upstream.sh instead: it git-diffs two upstream refs
(never walks the full history, so it dodges the hang), reprefixes the
libs/cua-driver delta to packages/cua-driver, and `git apply --reject`s it
on top of our local changes — conflicts land as *.rej for manual fixup.
Record the vendored version in .vendored-from and document the migration +
sync method in the design doc.
* chore(cua-driver): exclude vendored driver from qwen-code ESLint
The vendored packages/cua-driver tree carries upstream JS (e.g. the
test-harness Electron app) that doesn't follow qwen-code's lint rules and
fails CI. It is not a workspace package (no package.json) and is not
qwen-code TypeScript, so add it to eslint.config.js global ignores —
alongside packages/desktop/** — the standard treatment for vendored code.
* fix(cua-driver): let start_session revive an idle-reaped session
Ports the fix from upstream trycua/cua#2035 into the vendored driver.
When a session is reaped for idleness, a subsequent start_session with the
same id failed instead of resuming it. Revive the ended session in place so
the agent can continue rather than getting a hard error.
* fix(cua-driver): retry daemon socket writes on EAGAIN
Ports the fix from upstream trycua/cua#2036 into the vendored driver.
A non-blocking daemon socket can return EAGAIN/EWOULDBLOCK mid-write when the
peer's receive buffer is momentarily full. The driver treated that as fatal
and dropped the connection. Add a bounded retry/poll loop (mirror of the
read-side socket_io helper) so transient back-pressure no longer kills the
session; only a real timeout or hard error fails the write.
* fix(cua-driver/linux): stop reporting bare "Clicked" for X11 synthetic clicks
Ports the fix from upstream trycua/cua#2025 into the vendored driver.
On X11, clicks are delivered via XSendEvent synthetic events, which many
toolkits (GTK/SDL/Allegro) ignore because send_event is set. The driver still
reported a flat success ("Clicked"), masking that nothing happened. Report
the synthetic-delivery caveat honestly so the agent can fall back instead of
assuming the click landed.
(platform-linux crate is not built on macOS; verified by clean upstream apply
and covered by upstream + release-workflow Linux CI.)
* fix(cua-driver/windows): list empty-/null-title top-level windows
Ports the fix from upstream trycua/cua#2021 into the vendored driver.
list_windows filtered out any top-level window whose title was empty or null,
so legitimate targets (splash screens, some Electron/game windows, tool
windows) were invisible to the agent and unclickable. Include empty-title
windows, using class name / process as a fallback label.
(platform-windows crate is not built on macOS; verified by clean upstream
apply and covered by upstream + release-workflow Windows CI.)
* chore(cua-driver): track cherry-picked upstream PRs; fix vendored-from
The vendored copy is actually at cua-driver-rs-v0.6.7 (workspace version and
all 0.6.7->0.6.8 delta files confirm it), but .vendored-from had drifted to
0.6.8 during an earlier sync-script trial whose code delta was not kept. Left
as-is it would make a future sync diff 0.6.8->newer and silently skip the real
0.6.7->0.6.8 fixes. Correct it back to 0.6.7.
Also record the four not-yet-merged upstream PRs we carry as cherry-picks
(trycua/cua#2021/#2025/#2035/#2036) in .vendored-patches.md, and have
sync-from-upstream.sh point at it so the next sync reconciles them.
* ci(cua-driver): satisfy repo yamllint on the release workflow
The vendored-driver release workflow tripped 114 quoted-strings violations
under the repo's .yamllint (quote-type: single, required). Single-quote all
string scalars to match every other workflow in .github/workflows.
While reformatting, the release-notes body also got its paragraph blank lines
collapsed and still referenced the old CUA_DRIVER_RS_COORDINATE_SPACE=
normalized_1000 value — restore the blank lines and update it to the current
0/1 toggle (default 0 = off; optional CUA_DRIVER_RS_COORDINATE_SCALE=1000).
* chore(cua-driver): sync vendored driver to cua-driver-rs-v0.6.8
First real run of scripts/sync-from-upstream.sh: it 3-way-applied the upstream
0.6.7->0.6.8 delta onto our local fork. 10/12 files applied cleanly; the 2
rejects (install.ps1, _install-rust.sh) were already-applied baked-version
bumps (0.6.6->0.6.7, our copies were already at 0.6.7), i.e. no real conflict.
0.6.8 brings: Wayland input path (platform-linux), linux health_report +
overlay tweaks, a platform-macos build.rs step, and dependency bumps. Version
moved to 0.6.8 across the workspace.
Verified our work survived the sync untouched: the relative-coordinate shim
(coord_norm/protocol) and all four cherry-picked PRs (socket_io/session +
linux/windows) are intact — in particular the 0.6.8 edit to platform-linux
tools/impl_.rs landed alongside our #2025 change with no collision. macOS
cargo check + 132 core tests green. (platform-linux/windows + the binary
integration test build only on their own runners; upstream CI covers those.)
* ci(cua-driver): add a dry_run gate to the release workflow
Mirror the desktop-release / release dry-run pattern: a workflow_dispatch
dry_run boolean input (default true). The cross-platform build + package jobs
always run and upload their artifacts; the GitHub Release job now publishes
only on a tag push or an explicit dry_run=false dispatch.
Lets us rehearse the whole build/package pipeline (dry_run=true, notarize=false)
and inspect the produced artifacts without cutting a release. A branch push
(no tag, not a dispatch) likewise builds without releasing.
|
||
|
|
3d6b6f7475 |
feat(lint): enforce kebab-case filenames with ESLint (#4797)
Co-authored-by: 俊良 <[email protected]> |
||
|
|
18cc73ce05 |
feat(web-shell): add extension management (#5398)
Co-authored-by: ytahdn <[email protected]> |
||
|
|
62e45c567f | feat(desktop): Add desktop app package with Qwen ACP SDK integration (#3778) | ||
|
|
174e8de179 |
fix(core): stop AbortSignal listener leak in long sessions (MaxListenersExceededWarning) (#4366)
* fix(core): consolidate AbortController handling to stop listener leaks in long sessions
Users hit `MaxListenersExceededWarning: 1509 abort listeners added to
[AbortSignal]` in long interactive sessions. The agent runtime nests
parent→child controllers (masterAbortController → per-message round →
per-API-call round → tool execution) and each layer registered its own
`addEventListener('abort', ...)` on the parent without `{once:true}` or
reverse cleanup, so listeners accumulated on long-lived parents across
hundreds of model turns.
Add `utils/abortController.ts` with three helpers:
- `createAbortController(maxListeners = 50)` — factory that pre-caps the
signal so the warning never fires on per-request signals.
- `createChildAbortController(parent)` — WeakRef-based parent→child
propagation with `{once:true}` on the parent listener AND a reverse-cleanup
listener on the child that detaches the parent listener when the child
aborts. This is the key mechanism — short-lived children stop accumulating
dead listeners on long-lived parents.
- `combineAbortSignals(signals, {timeoutMs})` — N-way combiner that replaces
the existing one-input `combinedAbortSignal.ts` (kept as a `@deprecated`
shim so `httpHookRunner.ts` doesn't churn).
Migrate every production `new AbortController()` in `packages/core/src` (24
sites) to the helper. Wrap `_runReasoningLoopInner` per-iteration body and
`AgentHeadless.execute` in `try/finally` so the round controller is aborted
(triggering reverse cleanup) even when the model stream or tool execution
throws. Add `{once:true}` to the manual abort listeners in `hookRunner`,
`functionHookRunner`, and `message-bus` that were missing it. Remove the
`raiseAbortListenerCap` band-aid from `openaiContentGenerator/pipeline.ts` —
no longer needed now that the per-round signal carries `maxListeners=50`.
Add `cli/utils/warningHandler.ts` as a belt-and-suspenders: hides
`MaxListenersExceededWarning.*AbortSignal` from end users in production
(any shape Node ≥20 emits), keeps it visible under `DEBUG`/`QWEN_DEBUG`/
`NODE_ENV=development`. Uses `process.on('warning', ...)` without
`removeAllListeners` so third-party warning subscribers stay intact.
Direct reproducer in `docs/verification/abort-controller-refactor/` proves
the old pattern accumulates 2000 listeners over 2000 rounds while the new
pattern stays at 0.
* fix(core): address PR #4366 review feedback
Four issues from the Copilot review:
1. combineAbortSignals — add a per-iteration `aborted` check inside the
for-loop so we short-circuit if an input signal flips aborted between
the initial scan and listener registration. In single-threaded JS this
can't actually interleave, but the defensive check makes correctness
obvious and protects against signals whose `aborted` getter has side
effects. New test exercises the path via a Proxy that flips after the
initial scan.
2. warningHandler docstring — was stale: said "AbortSignal / EventTarget"
while the regex was tightened to AbortSignal-only in the previous review.
3. README.md — replace personal absolute path with `$WT` placeholder so
the verification recipe is shareable.
4. README.md — replace the markdown table with per-scenario headed
sections. Prettier had interpreted an inline `ps -ef | grep sleep`
pipe character as a column separator, breaking the table rendering on
GitHub. Per-section format is also easier to scan and edit.
* test(core): fix abortController race-defense test to actually hit the loop check
The previous version set the Proxy's `aborted` to true before calling
combineAbortSignals, so the initial `find` scan caught it and we took the
fast path — not the per-iteration check the test was meant to validate.
Switch to an access counter so `aborted` is false on the first read (during
`find`) and true on subsequent reads (inside the loop). This forces the
loop to enter, then catches the flip via the defensive per-iteration check
before any listener is attached to the next input.
Verified the test fails if the per-iteration check is removed.
* fix(lint): include docs/**/*.mjs in the script ESLint block so the AbortController repro passes lint
CI Lint flagged 11 no-undef errors in
docs/verification/abort-controller-refactor/listener-accumulation-repro.mjs
(AbortController, console, process) because the project's flat config
only declared Node globals for ./scripts/**/*.mjs.
The reviewer's suggestion (`/* eslint-env node */`) doesn't work under
ESLint 9 flat config — env directives are deprecated there. The proper
fix is to extend the existing script-globals block to also cover the
verification repro script under docs/.
* fix(core,cli): address PR #4366 critical review findings
Two real bugs the reviewer caught and I confirmed locally:
1. warningHandler.ts didn't actually suppress anything. Adding a
`process.on('warning')` listener does NOT prevent Node's default
onWarning printer from writing to stderr — the default is just an
ordinary listener registered in `lib/internal/process/warning.js`.
My previous code therefore:
- failed to suppress targeted AbortSignal warnings (they still hit
stderr via the default printer)
- produced a SECOND copy of every non-suppressed warning (default
printer + my handler's own stderr.write)
The unit tests missed it because they synthesised a fake warning and
called `process.listeners('warning')` directly rather than going
through `process.emitWarning`.
Fix: snapshot the existing `'warning'` listeners (which include the
default printer and any third-party telemetry hooks) BEFORE replacing
them. Install ours as the sole listener. For non-suppressed warnings
fan out to the captured set so the default printer + telemetry still
fire; for suppressed warnings stop here. Tests now use
`process.emit('warning', ...)` to drive the real listener chain, plus
a spawned-child integration test that asserts the real stderr from
`process.emitWarning` is empty for AbortSignal warnings and still
contains DeprecationWarning text.
2. abortController.createChildAbortController kept a WeakRef to the
child controller. A natural usage pattern — pass `child.signal` into
an async API and drop the controller object — could let the
controller be GC'd while the signal is still in use, after which
`parent.abort()` would no longer propagate. Reproduced with
`node --expose-gc`.
Fix: hold the child strongly via the parent's listener closure. The
reverse-cleanup listener still removes the closure when child aborts
(closure releases child → GC-eligible), and the parent's `{once:true}`
listener self-removes when parent fires (same effect). Net listener
accounting on long-lived parents is unchanged; the only difference is
the controller now stays alive long enough for propagation to reach
downstream consumers that hold only the signal. Tests updated: drop
the old `--expose-gc`-dependent assertion that abandoned children
GC immediately (that was a property of the OLD contract); add a
signal-only-retention test that verifies propagation under the new
contract without needing GC at all.
Verified: 32 helper/warning tests pass (incl. spawned-child stderr
integration); 363 affected caller tests pass; typecheck + prettier +
eslint clean for the touched files.
* fix(core,cli): address PR #4366 review — fix combineAbortSignals orphan listeners + runtime DEBUG toggle
Two real bugs the reviewer caught:
1. combineAbortSignals registered its cleanup listener on
controller.signal AFTER the for-loop. Node does NOT fire 'abort'
listeners added to an already-aborted signal, so when the
per-iteration defensive check aborted the controller mid-loop, the
cleanup never ran — orphaning every input-signal listener registered
before the break, and leaving the (also-registered-after-the-break)
setTimeout uncleared.
Fix: skip timeout scheduling when controller.signal.aborted is
already true post-loop, and when it's true call cleanup()
synchronously instead of registering a doomed listener. Existing
test for the mid-iteration path now also asserts that the
pre-break input signal (a) has zero abort listeners — that's the
assertion that catches the orphan bug. New test for the
already-aborted-input + timeoutMs combination confirms the timer
isn't scheduled (would otherwise overwrite the abort reason).
2. warningHandler captured isDebugMode() in a closure at init time, so
toggling DEBUG / QWEN_DEBUG at runtime (e.g. via a /debug slash
command) didn't update suppression behavior. Moved the check inside
the handler — warnings are rare so the per-emit env-lookup cost is
negligible. New test asserts a mid-stream DEBUG=1 flip starts
forwarding suppressed warnings to the prior-listener chain.
* test(core): strengthen the timeout-guard test in combineAbortSignals to actually exercise the new !aborted check
Reviewer correctly pointed out that the previous version of this test
took the pre-loop fast path (since `a.abort('pre')` ran before
`combineAbortSignals`), so it never reached the in-loop guard at
abortController.ts:138.
Switched to the Proxy `aborted`-getter pattern from the sibling
mid-iteration test (so the loop genuinely re-checks `aborted` and
short-circuits inside the for-loop), and added a `setTimeout` spy that
asserts the timer was never scheduled — this is the only observable
difference from "scheduled then immediately cleared by synchronous
cleanup()", which is what the timer-advance assertion alone couldn't
distinguish.
Verified by mutation testing: removing the guard makes the new test
fail; restoring it makes it pass. Refs PR #4366.
* test(core): cover timeout-triggered cleanup of input-signal listeners in combineAbortSignals
Reviewer noted the timeout path only had an empty-input test, leaving
the leak-sensitive case uncovered: when timeoutMs fires with a
long-lived source signal in the input list, do the input-side
listeners get released? They do (the timeout callback aborts the
combined controller, which fires the auto-cleanup listener registered
on its signal, which calls the per-input removeEventListener), but
that path wasn't tested.
Adds a test that snapshots the source listener count before, asserts
it increased by 1 after combineAbortSignals returns, advances fake
timers past timeoutMs, and asserts the count returns to baseline.
Refs PR #4366.
* fix(test): use pathToFileURL for the warning-handler e2e import on Windows
CI failure on windows-latest:
AssertionError: expected '\r\nnode:internal/modules/run_main:12…'
to match /DeprecationWarning.*Plain deprecation/
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme in:
file, data, and node are supported by the default ESM loader. On
Windows, absolute paths must be valid file:// URLs. Received protocol 'd:'
The e2e test wrote a child script with an `import "<helperPath>"` where
helperPath was a raw Windows absolute path (`D:\a\qwen-code\...`). Node's
ESM loader parses that as a URL on Windows and rejects the `D:` "scheme".
Converted the helper path to a `file://` URL via `pathToFileURL`. macOS
test still passes; the Windows-specific schemes-must-be-URL behavior is
now honored. Refs PR #4366.
* fix(core,cli): address PR #4366 review batch — onAbort leak, migrate missed sites, tighten tests
Adopted 6 of the 7 review threads (skipping the debug-logging suggestion).
1. processFunctionCalls onAbort leak (CRITICAL): the new
`finally { roundAbortController.abort(); }` in _runReasoningLoopInner
would fire the `onAbort` handler in `processFunctionCalls` if
scheduler.schedule or batchDone threw (the explicit
removeEventListener at the old happy-path exit would be skipped),
emitting spurious "Tool call cancelled by user abort." TOOL_RESULT
events for every un-emitted callId — corrupting the transcript and
misleading the model on the next round. Fixed by wrapping schedule
+ batchDone in their own try/finally so removeEventListener always
runs before the outer finally's abort.
2. Migrate 3 new-from-main `new AbortController()` sites that this
PR's audit missed (they came in via the merge from main):
- goals/goalHook.ts (2 sites: judgeController, fallback signal) —
consistency
- hooks/promptHookRunner.ts (1 site: internalAbortController) —
real leak (manual addEventListener without {once:true} or
cleanup, exactly the pattern this PR exists to fix). Switched to
createChildAbortController + finally `internalAbortController.abort()`
for reverse cleanup on the success path.
3. Repro script (`listener-accumulation-repro.mjs`): inlined helper
diverged from production — used WeakRef on child, while production
was changed to strong-ref earlier in this PR. Updated the inlined
copy to match production exactly, with a comment noting the
intentional WeakRef-on-parent-only pattern.
4. warningHandler.ts: documented the snapshot-and-replace trade-offs
in the JSDoc (late-added listeners bypass our filter; late
`removeListener` calls have no effect on our fan-out). Tried the
re-snapshot-per-warning approach the reviewer suggested but it
doesn't work — `removeAllListeners('warning')` permanently removes
the snapshot from Node's tracking, so a `process.listeners('warning')`
filter at fan-out time always returns empty for prior listeners.
The current design is the right trade-off; documentation is the
correct fix.
5. abortController.test.ts: added three coverage gaps the reviewer
identified —
- createChildAbortController forwards custom maxListeners
- manual cleanup() before scheduled timeout fires cancels it
- timeoutMs <= 0 is treated as "no timeout"
6. Migrated `httpHookRunner.ts:202` (the lone caller of the deprecated
`createCombinedAbortSignal`) to `combineAbortSignals` directly,
then deleted `combinedAbortSignal.ts` + its test. All semantics
covered by `combineAbortSignals` tests in abortController.test.ts.
Refreshed `migration-completeness.txt` (now empty — clean grep).
Tests: 194 pass across abortController/warningHandler/agent-runtime/
followup/hooks/goal/promptHook suites. Typecheck + prettier clean.
* docs(verification): commit the headless-scenario scripts referenced by the PR body
The PR body's "End-to-end scenarios I drove locally" section points at
docs/verification/abort-controller-refactor/scripts/02-lite.sh and 06-headless-sigint.sh.
These are the actual reproducible commands behind the EXIT codes /
warning counts reported there — checking them in so anyone can replay
without copy-pasting from the PR description.
Refs PR #4366.
* docs(verification): sync automated-results with current state
Two doc fixes the reviewer flagged:
- migration-completeness.txt was a 0-byte file with a confusing
cross-reference. Populated with the actual grep command + its
"(no output)" result so the empty-output state is explicit.
- automated-results.md still referenced combinedAbortSignal.test.ts (8
tests, @deprecated shim) — both files were deleted in
|
||
|
|
870bdf2a9d |
feat(cli,sdk): qwen serve daemon (Stage 1) (#3889)
* feat(cli): scaffold `qwen serve` HTTP daemon (Stage 1, #3803) Adds a `serve` subcommand that boots an Express 5 listener with bearer auth, host allowlist, and CORS modeled on `vscode-ide-companion/src/ ide-server.ts`. Ships only `/health` and `/capabilities` to begin with; session/prompt/event routes will land in follow-up PRs once the per- session ACP child-process bridge in `httpAcpBridge.ts` is wired. Defaults to 127.0.0.1 with auth disabled so local development needs no configuration. Binding beyond loopback (e.g. `--hostname 0.0.0.0`) refuses to start without a token (`--token` or `QWEN_SERVER_TOKEN`). Capabilities envelope versioned at v=1 with a `features` array — clients should gate UI off `features`, never off `mode`, so subsequent PRs can add capability tags without breaking older clients. Per design issue's Stage 1 scope (~700-1000 LOC). Adds ~430 LOC of implementation + tests in this scaffold; the remaining budget belongs to the route wiring + bridge implementation in follow-ups. * feat(cli): wire HttpAcpBridge + POST /session for `qwen serve` (#3803) Stage 1 follow-up to the scaffold. Implements the bridge between the HTTP daemon and the existing ACP child agent, plus the first session endpoint. `HttpAcpBridge.spawnOrAttach`: - Spawns `node $cliEntry --acp` per workspace via an injectable `ChannelFactory` (default uses `process.argv[1]`; tests use an in-memory `TransformStream` pair so they don't fork real processes). - Drives the ACP `initialize` + `newSession` handshake via the SDK's `ClientSideConnection`, with a 10s timeout that kills the channel. - Under `sessionScope: 'single'` (default), reuses the live session when the same canonical workspace cwd is requested again — backs the `attached: true` flag. - The `Client` impl on the bridge side proxies file reads/writes to local fs (daemon and agent share the host) and buffers `sessionUpdate` notifications for the SSE wiring in the next PR. `requestPermission` returns `cancelled` until the `/permission/:requestId` route lands. `POST /session`: - 400 on missing or relative `cwd`. - 200 with `{sessionId, workspaceCwd, attached}` on success. - 500 on bridge failure (the failing channel is killed, not leaked). `runQwenServe` constructs the bridge and ties `bridge.shutdown()` into the listener-close path so SIGINT/SIGTERM drain children before the socket closes. Tests (14 new, 0 regressions in the 4967-test baseline): - 9 bridge cases over an in-memory channel — fresh spawn, single-scope reuse, cross-workspace isolation, thread-scope independence, path canonicalization, relative-path rejection, init failure cleanup, init timeout, multi-channel shutdown. - 4 route cases for /session (missing/relative/200/500). - 1 lifecycle case asserting `runQwenServe.close()` calls `bridge.shutdown()` before closing the listener. Verified end-to-end: `qwen serve` boots, `POST /session` spawns a real `qwen --acp` child and returns the SDK-assigned `sessionId`, repeat calls under the same cwd return `attached: true`, `SIGTERM` reaps the child along with the listener. * feat(cli): wire POST /session/:id/prompt + /cancel for `qwen serve` (#3803) Stage 1 follow-up after the bridge scaffold. Adds the two routes a client needs to actually run a turn against the daemon. Bridge: - `sendPrompt(sessionId, req)` looks up the session, FIFO-queues the call against the per-session prompt queue, and forwards through the SDK `ClientSideConnection.prompt`. Concurrent calls observe ACP's "one active prompt per session" invariant — second waits for first. - A failed prompt does NOT poison the queue; the tail catches and keeps draining so the next caller still runs (the original caller still sees its own rejection). - `cancelSession(sessionId, req?)` bypasses the queue and forwards the ACP notification immediately. ACP semantics: the agent winds down the *currently active* prompt; queued work is unaffected. - Both methods throw `SessionNotFoundError` (a typed Error subclass) when the id is unknown so route handlers can map cleanly to 404 without brittle message matching. - Both methods overwrite the `sessionId` field in the request body with the routing id — a stale or spoofed body would otherwise be dispatched to the wrong agent process. Routes: - `POST /session/:id/prompt` → 200 with PromptResponse, 400 on missing/non-array prompt, 404 on unknown session, 500 on agent error. - `POST /session/:id/cancel` → 204 always (cancel is a notification), 404 on unknown session. Tests (14 new — 7 bridge + 7 route, 0 regressions in the 4981 baseline): - sendPrompt: success forwards & returns response · routing-id overrides body sessionId · concurrent prompts FIFO-serialize (verified via per-prompt start/end ordering with a release latch) · failed prompt doesn't block subsequent prompts · 404 for unknown id. - cancelSession: forwards with routing id · 404 for unknown id. - Routes: 200/400/404/500 paths for prompt; 204 with body or empty + 404 for cancel. Verified end-to-end against a real `qwen --acp` child: - POST /session/:id/prompt with `[{type:'text',text:'hi'}]` → 200 `{"stopReason":"end_turn"}` in ~3.4s. - POST /session/:id/cancel → 204. - POST /session/does-not-exist/prompt → 404 with the unknown id surfaced in the body. * feat(cli): wire SSE streaming for `qwen serve` events (#3803) Stage 1 follow-up that turns prompt into a real streaming experience. Replaces the in-memory `notifications: SessionNotification[]` buffer on each session with a per-session EventBus and exposes it through `GET /session/:id/events` as an `text/event-stream` SSE feed. EventBus (`packages/cli/src/serve/eventBus.ts`): - Monotonic per-session ids (`v: 1` schema). Each `publish` chains an id, returning the materialized BridgeEvent. - Bounded ring (default 1000) backs `Last-Event-ID` reconnect — a consumer that drops can resume from `lastEventId` and replay any still-buffered events before live events flow. - Per-subscriber bounded queue (default 256). When a slow consumer overruns its queue, the bus appends a synthetic `client_evicted` terminal frame and closes that subscription so it can't hold the daemon hostage. Other subscribers are unaffected. - `subscribe()` returns an AsyncIterable — registration is synchronous so events `publish`ed immediately after the subscribe land in the queue (a generator-style implementation deferred registration to first `next()` and raced with publishes). - AbortSignal-aware: aborting the signal closes the iterator promptly. Bridge (`httpAcpBridge.ts`): - `BridgeClient.sessionUpdate` now publishes onto the session's EventBus instead of pushing to a plain array — every ACP notification the agent emits becomes a stream event automatically. - New `subscribeEvents(sessionId, opts?)` returns the bus's AsyncIterable; throws `SessionNotFoundError` for unknown ids. - Shutdown closes every live event bus before killing channels so pending consumers unwind cleanly. Route (`server.ts`): - `GET /session/:id/events` sets the SSE content type, advertises a 3s reconnect hint, and writes a 15s heartbeat comment frame to keep proxy/NAT connections alive. - Forwards the `Last-Event-ID` header to the bus. - `req.on('close')` triggers an AbortController that propagates into the bridge subscription so disconnects don't leak subscribers. - 404 when the bridge can't find the session. Capabilities envelope: `STAGE1_FEATURES` now advertises `session_create`, `session_prompt`, `session_cancel`, `session_events` in addition to `health`/`capabilities` so clients can light up UI for the routes that have actually shipped. Tests (16 new, 0 regressions in the 4995 baseline): - 9 EventBus unit cases — id sequencing, live delivery, replay, replay+live splice, fan-out to N subscribers, eviction on overflow, abort-signal unsubscribe, bus.close() drains subscribers, ring-size eviction. - 4 bridge subscribe cases — 404, sessionUpdate→event publishing via real ACP fake-agent, shutdown closes live subscriptions. - 4 SSE route cases against a live HTTP listener — frame format, Last-Event-ID forwarding, 404, abort propagation on disconnect. Verified end-to-end against a real `qwen --acp` child: - Subscribed to `/session/$SID/events`, fired `POST /session/$SID/prompt` with text content. Captured 13 distinct `event: session_update` SSE frames in real time during the model's response — `available_ commands_update` metadata, 9 `agent_thought_chunk` frames carrying the model's chain-of-thought, 3 `agent_message_chunk` frames with the actual reply, and a final usage frame with token totals. - Frames carry monotonic ids 1..13, the daemon-side counter, and are valid SSE per the EventSource spec. * feat(cli): wire POST /permission/:requestId for `qwen serve` (#3803) Stage 1 follow-up that turns `BridgeClient.requestPermission` from a hardcoded `cancelled` placeholder into a real first-responder vote loop, and ships the HTTP route any attached client uses to cast the deciding vote. Bridge: - `requestPermission` generates a UUID requestId, registers a pending entry on a daemon-wide map (and the owning session's `pendingPermissionIds` set), publishes a `permission_request` event onto the session's EventBus (so SSE subscribers see it), and awaits the resolution. - New `respondToPermission(requestId, response)` resolves the pending promise with the supplied outcome. First call wins — subsequent calls return false. On success the bridge publishes a `permission_resolved` event so other attached clients can update their UI when the race is decided. - `cancelSession` and `shutdown` both resolve every still-pending permission for the affected session(s) as `{ outcome: { outcome: 'cancelled' } }` per the ACP spec requirement that a cancelled prompt MUST resolve outstanding requestPermission calls with cancelled. - New `pendingPermissionCount` getter exposes inflight count for inspection / tests. Route (`server.ts`): - `POST /permission/:requestId` validates the body's `outcome` is either `{ outcome: 'cancelled' }` or `{ outcome: 'selected', optionId: string }`, then forwards to `bridge.respondToPermission`. - 200 on accepted vote, 404 when the requestId is unknown or already resolved (Stage 1 doesn't differentiate), 400 on a malformed outcome. Capabilities envelope: STAGE1_FEATURES gains `permission_vote`. Tests (14 new — 9 bridge + 5 route, 0 regressions in the 5011 baseline): - Bridge: publishes permission_request with a generated requestId and waits; respondToPermission first-responder wins; publishes permission_resolved on vote; respondToPermission false for unknown requestId; cancelSession resolves outstanding as cancelled; shutdown resolves outstanding as cancelled. - Route: 200 on selected outcome; 200 on cancelled outcome; 404 on unknown requestId; 400 on malformed outcome; 400 on missing outcome. Verified end-to-end against a real `qwen --acp` child: - Subscribed to /session/$SID/events, sent a prompt asking the agent to write a file at /tmp/qwen-serve-permission-e2e-test.txt. - The agent triggered a permission_request via the bus, surfacing the three options Qwen Code presents (Allow Always / Allow / Reject) with their option ids. - POSTed `{outcome:{outcome:"selected",optionId:"proceed_once"}}` to /permission/$requestId — got HTTP 200. - Bus published the matching permission_resolved event. - Agent proceeded with the writeTextFile tool call; file was actually created on disk with the expected content. * feat(sdk): add DaemonClient for the qwen serve HTTP API (#3803) Stage 1 follow-up that proves the cross-mode protocol-isomorphism design assumption: an SDK client can drive the daemon's HTTP routes end-to-end without going through ProcessTransport's stdio + stream-json path. DaemonClient is a sibling of ProcessTransport, not a replacement. The two speak different protocols (ACP NDJSON over HTTP vs stream-json over stdio). Existing `query()` users keep getting subprocess-mode unchanged; applications that want daemon-mode (cross-client attach, shared MCP pool, network reachability, first-responder permissions) opt in by constructing a DaemonClient against a running `qwen serve`. API surface (`packages/sdk-typescript/src/daemon/`): - `new DaemonClient({ baseUrl, token?, fetch? })`. The `fetch` override is for tests; defaults to `globalThis.fetch`. Trailing slashes on `baseUrl` are stripped. - `health()`, `capabilities()` — discovery. - `createOrAttachSession({ workspaceCwd, modelServiceId? })` — `attached: true` on the response indicates a session was reused under sessionScope:single. - `prompt(sessionId, { prompt: ContentBlock[] })` — returns PromptResult with stopReason. - `cancel(sessionId)` — tolerates 204; throws on 404. - `subscribeEvents(sessionId, { lastEventId?, signal? })` — async iterator over parsed SSE frames; AbortSignal-aware. Native Node AbortController only — jsdom polyfills are incompatible with undici. - `respondToPermission(requestId, response)` — first-responder vote; returns true on 200, false on 404 (lost the race or unknown id), throws on 400/500. `DaemonHttpError` is thrown for any non-2xx (besides the 404 "already-resolved" case on permission votes); carries `status` and `body` so callers can branch on standard daemon HTTP semantics. `parseSseStream(body)` is the underlying SSE parser; exported separately so applications can consume daemon SSE outside the DaemonClient surface. Handles split-chunk frames, comment/retry directives, malformed JSON (skip), trailing frame without final newline. Wire types live SDK-side (no SDK→CLI dep); the capabilities envelope's `v` field signals breaking changes. Tests (26 new, 0 regressions in the 201 baseline): - 7 SSE parser cases — single frame, multiple frames, comments, chunked-split frame, malformed JSON skip, trailing frame on close, empty stream. - 19 DaemonClient cases — health success/error, capabilities, bearer auth presence/absence, createOrAttachSession success/400, prompt body shape + sessionId url-encoding, cancel 204/404, permission 200/400/404, subscribeEvents header forwarding + 404, baseUrl normalization. Verified end-to-end against a real `qwen serve` daemon driving a real `qwen --acp` child: - `client.capabilities()` returned `{v:1, mode:"http-bridge", features: [...7 tags]}`. - First `createOrAttachSession` returned `attached:false`; second returned `attached:true` with the same sessionId. - `client.prompt(...)` with text content yielded `{stopReason: "end_turn"}` while the parallel `subscribeEvents` iterator streamed 10 distinct frames during the same turn. - AbortController on the events iterator cleanly severed the SSE connection. * feat(cli,sdk): list workspace sessions + set session model (#3803) Closes the §04 Stage-1 routes table for `qwen serve` with the two remaining endpoints, plus matching SDK methods. `GET /workspace/:id/sessions` - `:id` is the URL-encoded canonical absolute workspace path (Express decodes path params automatically; clients pass `encodeURIComponent(cwd)`). - Returns `{ sessions: [{ sessionId, workspaceCwd }, ...] }` for live sessions whose canonical workspace matches. - Empty array (not 404) when the workspace is idle so picker UIs don't have to special-case "no sessions yet". - 400 when the decoded path isn't absolute. `POST /session/:id/model` - Body: `{ modelId: string, ... }`. The route's `:id` overrides any spoofed sessionId in the body. - Forwards to ACP's `unstable_setSessionModel` and publishes a `model_switched` event onto the session bus so cross-client UIs update. - 200 with the agent's response on success, 400 on missing/empty modelId, 404 on unknown session. - The SDK method is currently unstable; documented in the bridge comment in case the spec renames the method when it stabilizes. Bridge: - New `listWorkspaceSessions(workspaceCwd)` iterates `byId.values()` and filters by canonical workspace path; works for both `single` and `thread` session scopes. - New `setSessionModel(sessionId, req)` forwards through `connection.unstable_setSessionModel`, normalizes sessionId, publishes `model_switched`, throws SessionNotFoundError on unknown ids. `STAGE1_FEATURES` capabilities envelope grows to 9 tags, adding `session_list` and `session_set_model`. SDK (`DaemonClient`): - `listWorkspaceSessions(workspaceCwd)` URL-encodes the cwd and returns the parsed `sessions` array directly. - `setSessionModel(sessionId, modelId)` POSTs the body and returns the agent response (currently opaque per ACP unstable spec). - Wire types `DaemonSessionSummary` and `SetModelResult` exported from the SDK barrel. Tangential cleanup: `sendBridgeError` now extracts a useful message from non-Error values via a small `errorMessage` helper. JSON-RPC errors from the agent (`{code, message, data}`) used to surface as `"[object Object]"` in the 500 response body; they now show the inner `message` field. Caught while running the model-set e2e. Tests (17 new — 9 bridge + 7 route + 4 SDK, 0 regressions in the 5022 + 227 baselines): - Bridge listWorkspaceSessions: matching cwd returns the live sessions; canonicalizes the lookup; empty for relative paths. - Bridge setSessionModel: forwards modelId + overrides body sessionId; publishes model_switched event; 404 unknown session. - Route /workspace/:id/sessions: returns the bridge list; empty for idle workspace; 400 for relative path. - Route /session/:id/model: 200 success; 400 missing modelId; 400 empty modelId; 404 unknown session. - SDK listWorkspaceSessions: URL-encodes the cwd; throws on 400. - SDK setSessionModel: posts body; throws on 404. Verified end-to-end against a real `qwen serve`: - SDK reports 9 capability features, list returns the existing session, attached:true on repeat create, and `setSessionModel` rejects with HTTP 500 when the modelId isn't registered (with the daemon now surfacing "Internal error" instead of "[object Object]"). - 404 path through SDK on unknown sessionId works. * fix(cli,sdk): audit round 1 follow-ups for `qwen serve` (#3803) Self-review pass on PR #3889. Two real correctness bugs and an ergonomics gap, plus the test-coverage holes the audit surfaced. The loudest finding ("host allowlist no-op when bind=localhost") was a false positive — the conditional was misread; existing tests already prove the validator is active on `localhost` binds. Real fixes: - Bearer-auth timing-attack: `parts[1] !== token` short-circuits per byte, leaking which prefix is correct via response latency. Replace with SHA-256 of both sides + `crypto.timingSafeEqual` so comparison is constant-time regardless of token length. - Concurrent `spawnOrAttach` race in single-scope: two parallel callers for the same workspace both passed the `byWorkspace.get` check, both spawned, and one entry ended up orphaned in `byId` while the other won `byWorkspace`. Violates the "at most one session per workspace" invariant. Coalesce via an `inFlightSpawns` map: parallel callers attach to the in-flight promise and report `attached: true`. The slot is cleared on both success and rejection so a failed spawn doesn't poison the workspace forever. New test asserts ONE channel spawns under parallel calls and that retry works after rejection. - `Number.parseInt('1.5e10z', 10)` returns 1, so a malformed `Last-Event-ID` header silently passes through. Tighten `parseLastEventId` to `^\d+$` so anything not a pure decimal integer is dropped. New test exercises 'abc', '-1', '1.5e10z'. Ergonomics: - `LOOPBACK_BINDS` and `LOOPBACK_HOST_BINDS` now include `::1` and `[::1]`. IPv6 loopback users no longer have to set a token. Host-allowlist allows `[::1]:port` Host headers. Documentation: - `BridgeClient` doc-comment now states the Stage 1 trust model explicitly: agent runs as the same UID, the file-proxy methods are NOT a workspace-cwd sandbox, restricting them would be theatre. The audit flagged this as a "design gap" but the daemon-and-agent-on-same-host posture makes a sandbox here redundant — Stage 4+ remote-sandbox swaps the Client for a sandbox-aware variant. SDK fix: - `DaemonClient.failOnError` previously called `res.json()`, which consumes the body even on parse-failure; the subsequent `res.text()` returned empty. New impl reads once as text and attempts JSON-parse; raw text is the fallback. New test asserts a `text/plain` 502 surfaces the body verbatim. Test gap fills (audit-flagged): - Bridge: in-memory file-proxy tests for `BridgeClient.{read,write} TextFile` including line/limit slicing. - SSE route: `stream_error` synthetic frame on iterator throw mid-stream; numeric Last-Event-ID forwarded; malformed Last-Event-ID dropped. - DaemonClient: text/plain error body coerced to `body` field; `respondToPermission` 5xx throws; `subscribeEvents` null-body throws; `cancel`/`respondToPermission` URL-encode session/request ids that contain slashes. Verified end-to-end with a token-required daemon: right token → 200, wrong/missing/malformed → 401. All paths return uniform 401 messages so a side-channel can't distinguish between "no header", "bad scheme", and "wrong token". Test counts: cli serve **89** (was 81, +8), sdk daemon **35** (was 30, +5). Full suites still green. * fix(cli): audit round 2 follow-ups for `qwen serve` (#3803) Second self-review pass on PR #3889. Three real bugs (one correctness, one resource-cleanup, one cosmetic) plus consolidation of the loopback bindings into a single source of truth. Real fixes: - Shutdown could hang forever on a long-lived SSE consumer: `server.close` waits for every in-flight connection to drain, and a paused EventSource client never disconnects. Added a `SHUTDOWN_FORCE_CLOSE_MS` (5s) timer that calls `server.closeAllConnections()` to force-destroy stuck sockets, then resolves so `process.exit(0)` can run. New test asserts close completes well under 5.5s even when an SSE GET is in flight. - Signal-handler race during shutdown: round 1 detached the SIGINT/SIGTERM listeners *up front* in `handle.close()`. If a second SIGTERM arrived during the drain, no handler existed and Node's default termination ran, orphaning agent children. Switch to detaching at the *end* of the close path (in `finish()`): during the drain window the handler is still attached and the `if (shuttingDown) return` guard makes a second signal a no-op; after drain completes we can safely remove the listeners (this also fixes a test-suite MaxListenersExceededWarning that fired once we ran the runQwenServe tests >10 times in a single process). - SSE response had no `error` listener. When the underlying TCP socket died (RST, kill -9 on the client), the next `res.write` threw EPIPE and Express forwarded it to the default error handler, logging noisily. Added `res.on('error', cleanup)` so the failure is absorbed and triggers the same teardown path the `req.on('close')` handler uses. Validation: - `createHttpAcpBridge` now throws on invalid `sessionScope` (anything other than `'single'` or `'thread'`) and on `initializeTimeoutMs <= 0`. Misconfigured callers used to silently degrade to thread behavior; now they fail loudly. Cleanup: - The `LOOPBACK_BINDS` set was duplicated between `auth.ts` and `runQwenServe.ts` (round 1 missed this). Extracted into `packages/cli/src/serve/loopbackBinds.ts` with a single `isLoopbackBind(hostname)` helper. Both files now import; drift is impossible. - `res.flushHeaders?.()` lost the optional chaining. The method is on `http.ServerResponse` since Node 1.6; our `engines` floor is 20. Tests added: - bridge: `sessionScope` validation, `initializeTimeoutMs` validation. - server: shutdown force-close timeout, SIGINT/SIGTERM listener detach-after-drain. False positives from the round 2 audit (verified and dismissed): - "EventBus nextId overflow at 2^53" — theoretical only (would require ~9 quadrillion publishes per session). No code change. - "Subscribe-during-close race" — JS is single-threaded; the close() flag is set synchronously before the loop touches state. - "Queued prompts on shutdown" — by design; documented via the promptQueue tail comment. - "10MB body parser limit" — design choice for Stage 1's in-memory buffering model; revisit if ACP streaming lands in Stage 2. - "Unbounded body read in DaemonClient.failOnError" — daemon is local in Stage 1; the threat surface for adversarial-large error bodies is the same as the daemon's other unbounded buffers. Test counts: cli serve **93** (was 89, +4), full cli **5047** (no regressions), sdk **236** (no regressions). * docs(cli): audit rounds 3 + 4 follow-ups for `qwen serve` (#3803) Two more self-review passes on PR #3889. No correctness bugs surfaced this time — round 3 found a HIGH-severity Windows-path claim that turned out to be a false positive (`path.win32.isAbsolute('/foo/bar')` returns true; verified against Node 20). Round 4 confirmed every prior decision and surfaced one latent-but-not-currently-triggered concurrency note. Changes are pure documentation + a tiny optional-chain cleanup: - Drop `?.` on `server.closeAllConnections()` in runQwenServe.ts — the method exists since Node 18.2 and our `engines` floor is 20. The optional chain dated from before round 2's force-close timer landed; clean it up. - Help text for `qwen serve --port` now documents that port 0 means "OS-assigned ephemeral port" (which the implementation has always supported but never advertised). - `defaultSpawnChannelFactory` gains a comment near the spawn site documenting the FD-budget implication (~3 FDs per session, bump `ulimit -n` for many concurrent sessions) and the `stdio: ['pipe', 'pipe', 'inherit']` choice (child stderr lands in the daemon's stderr, interleaved across sessions). Both are Stage-1-accepted; Stage 2/4+ revisit each. - Comment on the bridge's `byWorkspace`/`byId` Maps documenting the known gap that a child crashing between requests leaves a garbage SessionEntry until daemon shutdown — surfaced as a per-prompt failure when the dead session is touched, not a hang. Stage 2's in-process bridge eliminates the spawned-child failure mode entirely so this gap goes away naturally. - `EventBus.subscribe` doc-comment now states explicitly that the returned iterator is NOT safe to drive from concurrent `.next()` callers — the underlying queue isn't atomic. Daemon usage is the sequential `for await ... of` inside the SSE route, so this is safe in production. Documented so a future fan-out consumer doesn't accidentally rely on undefined behavior. False positives verified and dismissed (round 3 + 4 combined): - `path.isAbsolute('/foo/bar')` Windows breakage — `path.win32. isAbsolute('/foo/bar')` is true; verified empirically. - "Windows drive divergence" causing duplicate sessions — different drives are different on-disk paths; sessions intentionally differ. - "parseSseStream early-break leaks reader" — `for await ... break` triggers `iterator.return()` which runs the generator's `finally` that calls `releaseLock`. Standard JS semantics. - "Promise executor sync-throw fragility in requestPermission" — sync throws inside `new Promise(executor)` reject the outer promise; functionally correct, just stylistic. - "Force-close timeout test elapsed assertion flakiness" — assertion is `< 5500ms` but the natural happy-path is sub-100ms. Generous headroom; not flake-prone in practice. - "fetch reference stale after polyfill" — `globalThis.fetch.bind` captures at construction; tests inject `opts.fetch` instead of polyfilling, which is the correct pattern. Test counts unchanged (cli serve **93**, sdk **236**); typecheck + lint clean. STAGE1_FEATURES still matches every implemented route 1:1, fakeBridge in tests implements every HttpAcpBridge method. * fix(cli): PR #3889 review round 1 — critical correctness (#3803) Addresses the four critical findings from the PR #3889 reviewer pass: 1. ACP `ReadTextFileRequest.line` is 1-based per spec, but the bridge's `BridgeClient.readTextFile` was treating it as a 0-based slice index. A client asking for `{line:1, limit:2}` ("first two lines") was getting lines 2-3 — a sign-off-by-one bug that breaks every editor / SDK client following the ACP schema. Convert to 0-based via `Math.max(0, line - 1)`. The existing slice test was asserting the wrong behavior; updated to expect the spec-correct result and added a second `line:3, limit:2` case to lock in the offset. 2. `modelServiceId` was accepted by the SDK + server `POST /session` path, forwarded into `bridge.spawnOrAttach`, and then silently dropped: `doSpawn` never wired it into the agent. Callers requesting a specific model got the agent's default and no indication anything was wrong. Now `doSpawn` issues `unstable_setSessionModel` immediately after `newSession`. If the agent rejects the model id, the half-initialized session is torn down and the spawn rejects so the caller can retry cleanly instead of inheriting silent drift. Three new bridge tests: happy path, omit-when-undefined, agent-rejection cleanup. 3. The CORS middleware used `cors({ origin: (o, cb) => cb(new CORSError(...), false) })` for browser-Origin requests. `cors` flows the Error into Express's error chain; without an explicit error handler that produces a 500 + HTML body, which is misleading for what is really a deterministic 403 denial. Replace with a tiny `RequestHandler` that checks `req.headers.origin` directly and returns `403 { error: 'Request denied by CORS policy' }` JSON. Drops the `cors` and `@types/cors` dependencies — there's no other consumer in the cli package. 4. The SSE `stream_error` synthetic frame hard-coded `id: 0`, which would regress the client's `Last-Event-ID` tracker and trigger duplicate replays on reconnect. The frame is terminal and daemon-emitted — it has no place in the per-session monotonic sequence. Refactor `formatSseFrame` to omit the `id:` line when the input event has no id field, and emit `stream_error` without one. Test updated to assert `frames[1].id === undefined` while the preceding `session_update` still carries its monotonic id. Tangential cleanup: `errorMessage` now formats the SSE error body (was `err.message` only — would have shown `[object Object]` for JSON-RPC errors mid-stream, mirroring the round-1 SDK fix). Test counts: cli serve **96** (was 93, +3 modelServiceId cases); existing readTextFile slice test rewritten in place. Full typecheck + lint + suite green. * fix(cli,sdk): PR #3889 review round 2 — SSE robustness + EventBus polish (#3803) Second batch of reviewer-flagged fixes for PR #3889. Addresses 7 robustness issues across the daemon's SSE pipeline + the bus + the SDK's stream parser. Daemon SSE (`server.ts`): - SSE writes now respect backpressure. `res.write` returns false when the kernel send buffer is full; the previous code ignored that and Node accumulated payloads in user-space memory unboundedly. A slow consumer on a chatty session could balloon daemon RSS. New `writeWithBackpressure` helper awaits `drain` (or `close`/`error`) before scheduling the next write — for both per-frame writes and heartbeats. - `parseLastEventId` rejects values > `Number.MAX_SAFE_INTEGER`. With the prior `^\d+$` regex a malicious 25-digit value would parse to a number that loses precision and confuses replay comparisons. EventBus (`eventBus.ts`): - `Last-Event-ID` replay events now `forcePush` past `maxQueued`. A client reconnecting with a 1000-event gap on a subscriber whose cap is 256 was silently losing entries 257-1000 — a sign-off-by- nothing breakage of the resume contract. Live publishes still go through the normal cap (slow live consumer must be evictable); historical replay is bypassed. - `onAbort` now disposes the subscription immediately instead of only closing the queue. An aborted-but-never-iterated subscriber used to linger in `bus.subs` until the consumer drove `next()` / `return()`. New tests cover both abort-after-subscribe and already-aborted-at-subscribe paths. - `BoundedAsyncQueue.next` now checks `buf.length > 0` before shifting instead of `buf.shift() !== undefined`. The bus never pushes `undefined` today but the queue is generic — the prior pattern would mis-handle a queue whose element type legitimately includes undefined. SDK SSE parser (`sse.ts`): - Now flushes the TextDecoder on stream close. Without the final `decoder.decode()`, an incomplete multi-byte UTF-8 sequence at the tail of the last chunk was silently dropped — corrupting any frame whose JSON ended mid-character. New test feeds a stream split mid-byte through "中" (3-byte UTF-8) and asserts the character round-trips. - Frame separators now accept both `\n\n` and `\r\n\r\n`. SSE spec allows CRLF, and intermediaries (corporate proxies, some Node http servers) sometimes normalize. Frame field splitter also accepts `\r?\n`. Two new tests cover pure CRLF + mixed-LF/CRLF. Test counts: cli serve **99** (was 96, +3 EventBus); sdk daemon-sse **10** (was 7, +3). Full typecheck + lint + suite green. * docs(cli,sdk): PR #3889 review round 3 — minor + docs (#3803) Last batch from the PR #3889 reviewer pass: mostly docs + a ReDoS-tooling-silencing rewrite + a yargs-key cleanup. - `commands/serve.ts` ServeArgs interface dropped the camelCase `httpBridge` mirror; the handler now reads `argv['http-bridge']` matching the declared option name. The dual surface relied on yargs's camelCase expansion behavior — fragile if yargs config ever changes. - `DaemonClient` constructor's `baseUrl.replace(/\/+$/, '')` (which is end-anchored and linear, but CodeQL's polynomial-regex detector flags any `\/+$` pattern on attacker-controlled input) swapped for a hand-rolled `stripTrailingSlashes` loop. Same behavior, no rule trigger. - `defaultSpawnChannelFactory`'s `cwd: workspaceCwd` flow into `spawn` is the second CodeQL finding ("uncontrolled data used in path expression"). It IS user-controlled, by design — that's the Stage 1 trust model. Added a `// lgtm[js/shell-command- constructed-from-input]` suppression with a comment explaining the model and pointing at issue #3803 §11 for the Stage 4+ remote- sandbox replacement. - Stale doc comment on `createServeApp` that still listed only `/health`, `/capabilities`, `POST /session` as shipped — now enumerates all 9 routes that match §04 of the design. - Stale doc comment on `HttpAcpBridge` saying "Stage 1 buffers them in-memory; SSE wiring lands in the next PR" — SSE wiring landed in commit |
||
|
|
3b0b6c052b |
feat(cli): add API preconnect to reduce first-call latency (#3318)
Fire a fire-and-forget HEAD request early in startup to warm the TCP+TLS connection. Subsequent SDK calls share an undici dispatcher with preconnect, reusing the warmed connection to save 100-200ms on the first request. Skip conditions: - NODE_EXTRA_CA_CERTS set (enterprise TLS inspection) - Sandbox mode (process-restart context) - Non-default baseUrl (mTLS / private deployment) - Non-Node runtimes (Bun) Disable via QWEN_CODE_DISABLE_PRECONNECT=1. Closes #3223 |
||
|
|
5a43efcae4 |
fix(editor): detect Zed.app on macOS when CLI is not in PATH (#3303)
* fix(editor): detect Zed.app on macOS when CLI is not in PATH On macOS, Zed editor is typically installed via Homebrew or direct download, but the CLI command 'zed' is not automatically added to PATH. This fix adds detection for Zed.app bundle at: - /Applications/Zed.app - ~/Applications/Zed.app When the CLI is not found but the app bundle exists, the code now falls back to using the CLI inside the app bundle at Contents/MacOS/zed. Fixes #3287 * fix(editor): use shared getEditorExecutable in useLaunchEditor - Export getEditorExecutable() from editor.ts for use by both getDiffCommand and useLaunchEditor - Updated useLaunchEditor.ts to use getEditorExecutable instead of its own implementation - Updated tests to be platform-agnostic for macOS app bundle path testing - Fixes: Zed on macOS is now detected when installed via app bundle (not just CLI in PATH) * fix(editor): use correct Zed CLI path (Contents/MacOS/cli) - Changed from Contents/MacOS/zed (GUI binary) to Contents/MacOS/cli (actual CLI) - The GUI binary does not support --wait/--diff flags - Updated tests to verify correct CLI path with regex matching for cross-platform * style(editor): fix prettier trailing whitespace issues Trailing spaces and array line-wrapping in zed macOS detection code. * fix(editor): return null when editor not found + remove unused var - getEditorExecutable now returns null (not fallback string) so useLaunchEditor error handling actually works - remove unused getAppBundleCliPath in test file (typecheck fix) * fix: add vitest globals to eslint config for test files * fix: remove duplicate empty test with orphan toEqual call * fix: resolve ESLint errors in editor.test.ts (arrow-body-style, no-useless-escape) * chore: remove debug script check_braces.js * fix: sync checkHasEditorType with getEditorExecutable, remove pr-body.md - Replace zedAppExists() check in checkHasEditorType with getEditorExecutable() !== null, keeping availability detection and execution in sync (fixes partial install false positive) - Remove unused zedAppExists() function - Remove scratch file pr-body.md * fix(editor): defer os.homedir() call to avoid breaking tests with incomplete node:os mocks The zedMacOsPaths constant was calling homedir() at module initialization time, which caused 'homedir is not a function' errors in CLI test files (systemInfo.test.ts, shellCommandProcessor.test.ts) that mock node:os without providing a homedir mock. Fix: convert zedMacOsPaths from a constant to a lazy function getZedAppPaths() that computes the paths only when called. --------- Co-authored-by: lamb <[email protected]> |
||
|
|
dc833d9d94 |
feat: add bugfix workflow, test-engineer agent, and debugging skills
- Add test-engineer agent for bug reproduction and verification - Add /qc:bugfix command for structured bugfix workflow - Add e2e-testing skill covering headless/interactive modes, MCP testing - Add structured-debugging skill for hypothesis-driven debugging - Simplify AGENTS.md to focus on essential commands and conventions - Add terminal-capture scenario for bugfix workflow testing - Add .qwen folder to ESLint ignore list Known limitations: The /qc:bugfix workflow and e2e-testing skill are experimental and may be unstable or consume significant tokens. Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
8753245b5f |
feat(channels): add DM pairing flow for sender approval
- Add PairingStore for managing pending requests and approved users - Update SenderGate to support pairing policy with code generation - Add CLI commands: `qwen channel pairing list/approve` - Document pairing flow with rules and usage examples This allows unknown senders to request access via a pairing code that the bot operator approves through the CLI. Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
74b342623c | Merge branch 'main' into feature/arena-agent-collaboration | ||
|
|
6258ee53a1 |
chore: Fix lint errors in web-templates package
- Remove unused npmCommand variable from build.mjs - Add no-undef and .mjs file support to web-templates eslint config Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
9e4c5ee891 |
refactor: Extract web-templates package and unify build/pack workflow
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]> |
||
|
|
6b55c8161f |
feat(arena): Add agent collaboration arena feature
Introduces a new Arena system for running multiple AI agents in parallel terminal sessions with support for iTerm and Tmux backends. Core: - Add ArenaManager and ArenaAgentClient for orchestrating multi-agent sessions - Add terminal backends (ITermBackend, TmuxBackend) with feature detection - Add git worktree service for isolated agent workspaces - Add arena event system for real-time status updates CLI: - Add /arena command with start, stop, status, and select subcommands - Add Arena dialogs (Select, Start, Status, Stop) - Add ArenaCards component for displaying parallel agent outputs - Consolidate message components into StatusMessages and ConversationMessages - Add MultiSelect component for agent selection Config: - Add arena-related settings to schema and config Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
c243f1d90d | chore: update ESLint configuration and lint-staged command | ||
|
|
22aa6656a4 | feat: add new insight page with Vite setup | ||
|
|
4abec5c055 | Merge remote-tracking branch 'origin/main' into feat/debug-logging-refactor | ||
|
|
86a43618a7 |
refactor(export): built-in package for assets export
1. use built-in assets package to support html export 2. improve markdown export |
||
|
|
7f4579ee6a |
refactor(debug): add ESLint no-console rule with targeted allowlist
- Add 'no-console': 'error' to main source files (packages/core/src, packages/cli/src) - Configure targeted allowlist for: - Test files and scripts - VS Code extension (out of scope) - WebUI package (UI component library) - Integration tests - Intentionally excluded files (acpAgent.ts, stdioHelpers.ts) - Consolidate no-console overrides into a single clearly-marked section - Enforced in CI via npm run lint:ci Co-authored-by: Qwen-Coder <[email protected]> |
||
|
|
340becefb4 |
refactor(lsp): migrate remaining LSP console calls to debugLogger
- LspConfigLoader.ts: 7 console.warn calls → debugLogger.warn - LspConnectionFactory.ts: 1 console.warn call → debugLogger.warn - Add eslint no-console overrides for test files and scripts - Completes LSP subsystem migration (8 more calls) Co-authored-by: Qwen-Coder <[email protected]> |