Repository navigation
refactor(cli): enforce utils leaf-layer dependency direction (#9146) - #9737
Conversation
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.
There was a problem hiding this comment.
Pull request overview
Refactors the packages/cli dependency graph to make src/utils/ a true leaf layer (no runtime imports upward into domain directories) and adds mechanical enforcement via a custom ESLint rule, alongside file moves/import rewrites to match ownership.
Changes:
- Adds
architecture/no-utils-upward-importESLint rule + targeted tests to preventutils/**upward runtime imports. - Moves domain-coupled helpers out of
utils/into owning directories and rewrites imports throughout CLI, UI, serve, nonInteractive, and review command code. - Extracts/centralizes generic helpers (
normalizePartList) and relocatesMergeStrategytoutils/deepMerge.ts.
Reviewed changes
Copilot reviewed 104 out of 107 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| scripts/tests/no-utils-upward-import.test.js | Unit-tests custom ESLint rule logic. |
| scripts/tests/no-utils-upward-import-config.test.js | Verifies rule wiring in flat ESLint config. |
| packages/cli/tsconfig.json | Updates test include path after moves. |
| packages/cli/src/utils/normalize-part-list.ts | Adds shared normalizePartList helper. |
| packages/cli/src/utils/normalize-part-list.test.ts | Adds unit tests for normalizePartList. |
| packages/cli/src/utils/midTurnUserMessage.ts | Switches to new normalize-part-list helper. |
| packages/cli/src/utils/deepMerge.ts | Moves MergeStrategy enum into utils owner. |
| packages/cli/src/utils/deepMerge.test.ts | Updates imports for relocated MergeStrategy. |
| packages/cli/src/ui/utils/commandUtils.ts | Repoints command parsing imports to UI-owned module. |
| packages/cli/src/ui/update-relaunch.ts | Adjusts imports/dynamic imports after moves. |
| packages/cli/src/ui/update-relaunch.test.ts | Updates mocks/paths after update module moves. |
| packages/cli/src/ui/systemInfoFields.ts | Adds/moves system info field definitions into UI. |
| packages/cli/src/ui/systemInfoFields.test.ts | Adds tests for system info field ordering/formatting. |
| packages/cli/src/ui/systemInfo.ts | Updates CommandContext/version imports after moves. |
| packages/cli/src/ui/systemInfo.test.ts | Updates mocks/imports after systemInfo move. |
| packages/cli/src/ui/standalone-update.ts | Repoints helper imports to utils after move. |
| packages/cli/src/ui/standalone-update.test.ts | Updates source-path assertions after move. |
| packages/cli/src/ui/hooks/useProviderUpdates.test.ts | Updates settings utils mock path. |
| packages/cli/src/ui/hooks/useGeminiStream.ts | Uses extracted normalize-part-list helper. |
| packages/cli/src/ui/hooks/useCommandCompletion.tsx | Repoints command parsing imports into UI commands. |
| packages/cli/src/ui/hooks/slashCommandProcessor.ts | Repoints command parsing imports into UI commands. |
| packages/cli/src/ui/handleAutoUpdate.ts | Updates imports to new locations (types/utils). |
| packages/cli/src/ui/handleAutoUpdate.test.ts | Updates mocks/imports after move. |
| packages/cli/src/ui/components/ThemeDialog.tsx | Updates dialog scope utils import location. |
| packages/cli/src/ui/components/shared/ScopeSelector.tsx | Updates dialog scope utils import location. |
| packages/cli/src/ui/components/SettingsDialog.tsx | Updates settings/language/system info imports. |
| packages/cli/src/ui/components/SettingsDialog.test.tsx | Updates mocks/imports after moves. |
| packages/cli/src/ui/components/ApprovalModeDialog.tsx | Updates dialog scope utils import location. |
| packages/cli/src/ui/components/AboutBox.tsx | Updates system info imports after move. |
| packages/cli/src/ui/commands/update-command.ts | Updates dynamic import path for standalone update. |
| packages/cli/src/ui/commands/update-command.test.ts | Updates mocks after standalone update move. |
| packages/cli/src/ui/commands/languageCommand.ts | Moves language utilities import to i18n. |
| packages/cli/src/ui/commands/languageCommand.test.ts | Updates imports after language utils move. |
| packages/cli/src/ui/commands/doctorCommand.ts | Repoints doctor checks + standalone update import. |
| packages/cli/src/ui/commands/doctorCommand.test.ts | Updates mocks/imports after doctor checks move. |
| packages/cli/src/ui/commands/doctorChecks.ts | Moves doctor checks into UI commands ownership. |
| packages/cli/src/ui/commands/doctorChecks.test.ts | Updates imports/mocks after move. |
| packages/cli/src/ui/commands/config-command.ts | Updates settings utils import location. |
| packages/cli/src/ui/commands/commands.ts | Moves commands registry into UI commands folder. |
| packages/cli/src/ui/commands/commands.test.ts | Updates imports after commands move. |
| packages/cli/src/ui/commands/bugCommand.ts | Updates system info imports after move. |
| packages/cli/src/ui/commands/bugCommand.test.ts | Updates mocks/imports after move. |
| packages/cli/src/ui/commands/aboutCommand.ts | Updates system info import after move. |
| packages/cli/src/ui/commands/aboutCommand.test.ts | Updates mocks/imports after move. |
| packages/cli/src/ui/auth/useAuth.test.ts | Updates settings utils mock path. |
| packages/cli/src/ui/AppContainer.tsx | Repoints command parsing, update handler, and nonInteractive helpers. |
| packages/cli/src/ui/AppContainer.test.tsx | Updates mock path after update handler move. |
| packages/cli/src/startup/startup-prefetch.ts | Updates dynamic import paths after moves. |
| packages/cli/src/startup/startup-prefetch.test.ts | Updates mocks for moved modules. |
| packages/cli/src/services/housekeeping/scheduler.ts | Moves scheduler into services and reimports housekeeping utils. |
| packages/cli/src/services/housekeeping/scheduler.test.ts | Updates housekeeping imports after move. |
| packages/cli/src/services/housekeeping/non-interactive-scheduler.test.ts | Updates mocks/import paths after housekeeping move. |
| packages/cli/src/serve/sandbox.ts | Moves sandbox into serve and reimports shared utils. |
| packages/cli/src/serve/sandbox.test.ts | Updates imports after sandbox move. |
| packages/cli/src/serve/routes/workspace-settings.ts | Updates settings utils import location. |
| packages/cli/src/serve/routes/workspace-models.ts | Updates settings utils import location. |
| packages/cli/src/serve/daemon-status-provider.ts | Updates systemInfo import location after move. |
| packages/cli/src/nonInteractiveCliCommands.ts | Repoints command parsing imports. |
| packages/cli/src/nonInteractiveCli.ts | Repoints chat-recording + helper imports; uses extracted normalizePartList. |
| packages/cli/src/nonInteractive/tool-result-boundary-diagnostics.ts | Adjusts types import path within nonInteractive. |
| packages/cli/src/nonInteractive/tool-result-boundary-diagnostics.test.ts | Updates types imports after move. |
| packages/cli/src/nonInteractive/session.ts | Updates chat-recording import after move. |
| packages/cli/src/nonInteractive/permission-suggestions.ts | Adjusts types import path within nonInteractive. |
| packages/cli/src/nonInteractive/nonInteractiveHelpers.ts | Removes duplicated normalizePartList implementation. |
| packages/cli/src/nonInteractive/nonInteractiveHelpers.test.ts | Removes duplicated normalizePartList tests and updates type imports. |
| packages/cli/src/nonInteractive/io/StreamJsonOutputAdapter.ts | Updates diagnostics import after move. |
| packages/cli/src/nonInteractive/io/JsonOutputAdapter.ts | Updates diagnostics import after move. |
| packages/cli/src/nonInteractive/io/BaseJsonOutputAdapter.ts | Updates helper/diagnostics imports after move. |
| packages/cli/src/nonInteractive/control/controllers/permissionController.ts | Updates permission suggestions import after move. |
| packages/cli/src/nonInteractive/chat-recording-failure.ts | Moves chat recording failure helper into nonInteractive and updates imports. |
| packages/cli/src/nonInteractive/chat-recording-failure.test.ts | Updates mocks/imports after move. |
| packages/cli/src/i18n/languageUtils.ts | Moves language utils into i18n ownership (self-relative imports). |
| packages/cli/src/i18n/languageUtils.test.ts | Updates mocks/imports after move. |
| packages/cli/src/gemini.tsx | Repoints sandbox/language/update/housekeeping imports after moves. |
| packages/cli/src/gemini.test.tsx | Updates mocks/imports for moved modules. |
| packages/cli/src/dualOutput/DualOutputBridge.ts | Updates chat-recording-failure import after move. |
| packages/cli/src/config/settingsWatcher.ts | Updates settings utils import location. |
| packages/cli/src/config/settingsUtils.ts | Normalizes config-local imports + i18n language util import. |
| packages/cli/src/config/settingsUtils.test.ts | Updates mocks/imports after settingsSchema path change. |
| packages/cli/src/config/settingsSchema.ts | Imports MergeStrategy from new owner (utils/deepMerge). |
| packages/cli/src/config/settingsSchema.test.ts | Updates MergeStrategy import after move. |
| packages/cli/src/config/settings.ts | Updates settings utils import; uses deepMerge-owned MergeStrategy type. |
| packages/cli/src/config/migration/versions/v3-to-v4.ts | Updates settings utils import after move. |
| packages/cli/src/config/migration/versions/v2-to-v3.ts | Updates settings utils import after move. |
| packages/cli/src/config/migration/versions/v1-to-v2.ts | Updates settings utils import after move. |
| packages/cli/src/config/loadedSettingsAdapter.ts | Updates settings utils import after move. |
| packages/cli/src/config/loadedSettingsAdapter.test.ts | Updates mocks/imports after move. |
| packages/cli/src/config/dialogScopeUtils.ts | Normalizes config-local imports after move. |
| packages/cli/src/commands/update.ts | Updates standalone update import after move. |
| packages/cli/src/commands/update.test.ts | Updates mocks/imports after move. |
| packages/cli/src/commands/review/save-artifact.ts | Repoints findings import into review domain. |
| packages/cli/src/commands/review/save-artifact.test.ts | Repoints findings import into review domain. |
| packages/cli/src/commands/review/publish-assets.ts | Repoints findings import into review domain. |
| packages/cli/src/commands/review/lib/shell-quote.ts | Updates comment reference to moved standalone-update file. |
| packages/cli/src/commands/review/lib/review-settings.test.ts | Updates settings utils import location. |
| packages/cli/src/commands/review/findings.ts | Moves findings module into review domain; adjusts imports. |
| packages/cli/src/commands/review/findings.test.ts | Adds extensive tests for findings contract/behavior. |
| packages/cli/src/commands/review/compose-review.ts | Repoints findings imports after move. |
| packages/cli/src/commands/review.ts | Repoints findings command import after move. |
| packages/cli/src/acp-integration/session/Session.ts | Repoints helper imports after moves (normalizePartList/diagnostics). |
| packages/cli/src/acp-integration/session/history-replay-page.ts | Updates diagnostics import after move. |
| packages/cli/src/acp-integration/session/history-replay-page.test.ts | Updates diagnostics mocks/import paths after move. |
| packages/cli/src/acp-integration/session/emitters/tool-call-emitter.ts | Updates diagnostics import after move. |
| packages/cli/src/acp-integration/acpAgent.ts | Updates diagnostics/language/housekeeping imports after moves. |
| packages/cli/src/acp-integration/acpAgent.test.ts | Updates mocks/imports after moves. |
| eslint.config.js | Registers rule in flat config for packages/cli/src/utils/**. |
| eslint-rules/no-utils-upward-import.js | Implements utils/ upward-import boundary rule. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Code Coverage Summary
CLI Package - Full Text ReportCore Package - Full Text ReportFor detailed HTML reports, please see the 'coverage-reports-22.x-ubuntu-latest' artifact from the main CI run. |
|
Closeout round on top of latest
|
#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.
…eaf-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.
|
No blocking findings. The module moves and import rewrites preserve the existing behavior, and the new ESLint rule covers static imports, re-exports, and statically resolvable dynamic imports escaping Non-blocking: dedicated |
doudouOUC
left a comment
There was a problem hiding this comment.
Not reviewed: coverage — no plan was given, so this run cannot show that any of the diff was read.
— qwen-code-review via Qwen Code /review (v0.21.10)
doudouOUC
left a comment
There was a problem hiding this comment.
双模型代码审查结果 · Round 1
PR: #9737 refactor(cli): enforce utils leaf-layer dependency direction (#9146)
模型: deepseek-v4-flash
结论: 0 Critical / 0 Suggestion inline,仅 2 条非阻塞建议
汇总
13 个审查代理全部完成,未发现阻塞性问题。本次变更是干净的机械式架构重构:
- 43 个
utils/向上的值导入已消除,仅剩 2 处 type-only 引用。 - 17 个模块
git mv到归属目录,所有导入路径重写后可解析。 - 新 ESLint 规则
architecture/no-utils-upward-import已覆盖 type-only 豁免与动态导入检测。 normalizePartList正确去重提取,MergeStrategy正确归位。
非阻塞建议
- ESLint 规则中的路径规范化使用
nodePath.replaceAll('\\', '/'),可考虑补充 Windows 路径的显式测试。 - PR 描述中 Windows 测试状态标注为 "N/A",但规则已验证可在 Windows 路径下工作,描述可更新为已测试状态。
该评论由 qwen review bot 自动生成。
Review closeout — round at 2026-08-22T19:16Z (all 4 threads fixed, replied, resolved)Pushed
|
|
@qwen-code /triage |
…imModuleSyntax (#9146) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
…n the utils rule (#9146) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
…st marker (#9146) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
#9146) Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
…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.
|
@qwen-code /review |
|
Qwen Code review request accepted. Review is queued in workflow run. |
|
Addressed the two current-head review suggestions in additive commit 1445a76:
Verification: both rule suites pass (14/14), plus targeted ESLint, Prettier, and git diff --check. |
chiga0
left a comment
There was a problem hiding this comment.
No blocking findings.
Scope: reviewed the ESLint rule, its test suite, the .sb profile co-location, and the docs/comment sweep. File moves and import rewrites verified by green CI.
Checked:
no-utils-upward-import.js: correctly exempts only statement-levelimport type/export type; inline{ type X }specifiers are reported as value imports underverbatimModuleSyntax(fix commit21cfacf8). Computed dynamic imports fail closed when the statically known prefix is relative (fix commit764d603f). CLI baseUrl (src/-rooted) specifiers correctly resolved frompackages/cli/.- Seatbelt profiles:
sandbox-macos-*.sbfiles co-located withsandbox.tsinserve/(commit0dca7b09);resolveSeatbeltProfileFileresolves viaimport.meta.url→ same directory → resolution intact. - Docs sweep: all path references in design docs updated to post-move locations.
CI: Test (ubuntu-latest, Node 22.x) pass · Desktop Shell (ubuntu + windows) pass · web-shell E2E, Real daemon E2E, Java matrix all pass. Integration Tests (CLI, No Sandbox) SKIPPED — merge_group-only gate, standard for PR check.
Cross-check: prior CHANGES_REQUESTED items (R1: .sb stranding, R1-3: type-specifier exemption; R2-1: verbatimModuleSyntax inline; R2-4: computed dynamic imports) all addressed by commits on this head.
Reviewed with AI assistance.
doudouOUC
left a comment
There was a problem hiding this comment.
Independent review at 1445a767 — both Criticals verified fixed; no findings; approving
Same gate note as its core-side sibling #9778: this is a large refactor touching packages/cli/src/** and crossing packages, which is what AGENTS.md's two-tier rule targets — but the rule exempts maintainer-authored PRs, and yiliang114 holds admin here, so this gets a normal review rather than an automatic block.
The two Criticals — verified at this head
Stranded seatbelt profiles. Moving sandbox.ts into serve/ left the six sandbox-macos-*.sb profiles behind in utils/, while resolveSeatbeltProfileFile resolves them relative to the module — so every sandbox-enabled macOS start from source or an unbundled dist/ would have thrown FatalSandboxError. Fixed by moving all six profiles beside sandbox.ts; the diff shows them as pure renames (+0/-0) into packages/cli/src/serve/, which is the right shape for a git mv. This was the one finding on either PR with real user-visible blast radius, and it is the kind only a path-aware reader catches — a .sb file has no import edge to follow.
The inline type-specifier exemption (R2-1). This is the sharp one. The rule had exempted import { type X } from / export { type X } from on the theory that type-only constructs erase — but under this repo's verbatimModuleSyntax: true, import { type X } from './b.js' emits import {} from './b.js', a surviving runtime edge, so the exemption blessed precisely the upward dependency the rule exists to forbid, and a test pinned that wrong behaviour. At this head the rule reports them and says why in place:
Inline type specifiers (
import { type X } from/export { type X } from) are reported instead: under this repo'sverbatimModuleSyntax, tsc keeps the …
with the same reasoning repeated at the check itself (no-utils-upward-import.js:140-147), and only statement-level importKind/exportKind exempted. Correct, and correctly explained — this file is now the reference wording, which is why I asked #9778 to mirror it.
What I checked independently
A mechanical import refactor's characteristic failure is a moved module leaving a stale vi.mock first argument behind: the mock silently stops intercepting, the real module runs, and the test still passes. So I resolved every relative vi.mock/vi.doMock specifier in every test file on the branch against the branch's own file list, baselined on main:
origin/main 1275 specs 13 unresolved
pr-9737 (1445a767) 1275 specs 13 unresolved -> no new unresolved specs, none moved
I also checked for tests orphaned from their source by the moves. One candidate surfaced — packages/cli/src/services/housekeeping/non-interactive-scheduler.test.ts with no non-interactive-scheduler.ts beside it — but it is pre-existing rather than introduced: on main the same file sits at utils/housekeeping/ with no such sibling either, and at this head it imports './scheduler.js', which the PR moves into the same directory. Relocated, not orphaned. Nothing to report.
The rule is wired rather than declared: eslint.config.js carries it (+13/-16 there, consolidating the plugin block), and the added process-env-guard.test.ts (+54) and sandbox.test.ts changes (+22/-7) pin the two behaviours the moves put at risk.
Where I land
Approving, with no findings of my own. Both Criticals had real teeth — one would have broken sandboxed macOS startup, the other would have left the new rule licensing the exact edge it forbids — and both are closed at this head with the reasoning recorded beside the code rather than only in a thread.
CI is green apart from review-pr, still running. reviewDecision still reads CHANGES_REQUESTED, from a bot review several commits behind this head.
Not verified by me: I did not run the suites (no node_modules in this worktree — CI covers them green), so the mock-resolution result is static rather than a test run, and I did not exercise sandbox-exec on macOS to confirm the profile lookup end to end — that path is judged from the resolver and the file locations.
One conflict, in the workspace-scope strip this PR had added to. `main` (QwenLM#9098, QwenLM#9737) generalised that strip into a single data list: WORKSPACE_RESTRICTED_SETTINGS in settingsUtils.ts now drives the strip, the "your workspace value was ignored" warning, and the settings dialog's scope filter, so the three surfaces cannot drift apart. This PR had hand-rolled the same thing for permissions.planMode — a second branch inside stripWorkspaceSecurityBypasses and a third copy of the warning text. Both are deleted in favour of main's version, and the setting is registered as one entry in the list instead. The behaviour is unchanged and the four scope tests added here still pass against the generic mechanism; the dialog filter comes along for free, though planMode sets showInDialog: false.
… dialogs scaffolding Foundation batch of the OpenTUI migration tracked in QwenLM#8662. Adds the renderer-neutral foundation modules under ui/opentui: theme family, a11y (plain-text, screen-reader), clipboard, key-map, mouse hit/caret, link-click + osc8 parity, early-input, exit guard/lifecycle, kitty negotiation, event-adapter, item-projection, slash dispatch (+ command parsing), commands context/output, help content, input history, and the dialog scaffolding primitives (core/shared) with the theme dialog. Two helpers land inside ui/opentui rather than utils/ to respect the utils leaf-layer rule (QwenLM#9737). Stacked on the infra batch: consumes ui/model streaming model and @OpenTui deps. No reachable ink code changes beyond a one-line export addition in the shared osc8 module.
* feat(cli): OpenTUI foundation modules — theme, a11y, clipboard, keys, dialogs scaffolding Foundation batch of the OpenTUI migration tracked in QwenLM#8662. Adds the renderer-neutral foundation modules under ui/opentui: theme family, a11y (plain-text, screen-reader), clipboard, key-map, mouse hit/caret, link-click + osc8 parity, early-input, exit guard/lifecycle, kitty negotiation, event-adapter, item-projection, slash dispatch (+ command parsing), commands context/output, help content, input history, and the dialog scaffolding primitives (core/shared) with the theme dialog. Two helpers land inside ui/opentui rather than utils/ to respect the utils leaf-layer rule (QwenLM#9737). Stacked on the infra batch: consumes ui/model streaming model and @OpenTui deps. No reachable ink code changes beyond a one-line export addition in the shared osc8 module. * fix(cli): import originals instead of forking slash parser and dialog scope utils * fix(cli): address R1 review findings in OpenTUI foundation modules * fix(cli): align OpenTUI command host with the memory-file-count rename Upstream renamed setGeminiMdFileCount to setMemoryFileCount in the command UI contract; the rebase onto main surfaced the mismatch at build. Rename the host interface member, the bridge wiring, the dispatch stub, and the test mock to match. * feat(cli): OpenTUI migration live-session and input batch Third landing batch of the OpenTUI migration (QwenLM#8662): live-session stream fold and model, message rendering (markdown heal, MCP progressive, client tool runs, text batching), transcript adapter with resume/session-switch, sticky todos, the composer (input-prompt view/key/model), mouse rows and scrollbar, unified-diff rendering, and session-compaction notice. All additive — no reachable ink code path is touched, ink remains the default. Carries the first consumer of the remend dependency deferred from the infra batch, placed in devDependencies per the renderer-deps convention. The stacked-skill completion helpers import from the relocated ui/commands module following the upstream rename. * fix(cli): address R2 review findings in OpenTUI foundation modules Round-2 review fixes (17 Critical + 10 Suggestion resolved in code): - dialogs-shared: move number-select flush out of the setState updater (StrictMode double-fires onSelect); split setActiveIndex (ink SET_ACTIVE_INDEX, lands on any in-range row) from highlightIndex (arrow keys skip disabled rows) so wheel navigation never sticks - event-adapter: chat_compressed notice mirrors ink formatCount ('~' prefix for estimated counts); vision_bridge_notice renders summary\nnotice; explicit projections for task_execution / findings_list / terminal_image keep multi-MB payloads off the transcript; retry-countdown-clear forwards isContinuation - slash-dispatch: isSlashCommandInput drops the '?' branch (ink gate routes ? input to the model); executeSlashCommand races the action against the abort signal; dialog effects carry the OpenDialogActionReturn payload; projected added-item text surfaces alongside non-handled effects (notice); message-shaped items project to their text; ui.history comes from env; absent sessionStats stamp now, not epoch; telemetry parity (recordSkillInvocation / recordAutoSkillCommandUsage / makeSlashCommandEvent) - item-projection: model stats render per-(model,source) sections with N/A for unpriced entries; Tool Calls line uses ASCII x like ink; redactProxy deduplicated via systemInfoFields export - theme: palette/syntax colors resolve through color-utils toHex before parseColor (ink CSS names / *bright names no longer degrade to magenta); unresolvable values stay unset - key-map: kitty 'kpenter' normalizes to 'return'; resolveCommands exposes ink's key fan-out (Ctrl+C fires QUIT + CLEAR_INPUT) - a11y: hardWrap delegates to wrap-ansi (word-boundary parity with ink's screen-reader path); markdown reducer tracks fence length, keeps fence-like lines literal inside fences and inner backticks in multi-backtick spans; stripAnsi delegates to strip-ansi plus a private-parameter CSI pass (SGR mouse, DEC save/restore) - clipboard: OSC 52 write gated on a TTY (stderr preferred), tests spy the stream instead of writing real sequences to the runner's terminal - exit-guard: independent per-key arm windows like ink - dialogs-theme: diff preview pane receives syntaxStyle/filetype * fix(cli): harden kitty probe and screen-reader writer per maintainer review - kitty-negotiation: KITTY_REPLY_RE requires at least one flag digit (\d+), so an echoed bare query \x1b[?u in PTY/CI environments no longer resolves true and locks the renderer into kitty mode on a terminal that never answers queries; the accumulation buffer keeps only a 256-byte tail (bounded memory, bounded rescan under byte floods); the settle-window drain is removed — an EventEmitter data listener cannot consume chunks from other listeners, so late replies flow to the renderer's input parser like any other terminal noise - a11y-screen-reader: ScreenReaderOutputWriter sanitizes written content (stripAnsi + drop bare C0/C1 controls, keep newlines) so the plain-text-only contract is enforced at the writer instead of trusting every future caller — smuggled OSC 52 clipboard writes or title/cursor sequences cannot execute on the main screen * fix(cli): address ytahdn independent review findings in OpenTUI foundation All 15 findings from the independent static review verified in source and fixed (no false positives; none deferred): - quit effect carries QuitActionReturn.messages projected to text on a notice field — ink renders them via QuittingDisplay and the payload was permanently lost (Important QwenLM#1) - error and finished branches emit retry-countdown-clear like ink's handleErrorEvent/handleFinishedEvent, so a terminal event inside the countdown window no longer leaves a stale retry row (QwenLM#2) - projectContextUsage renders the compaction-threshold ladder and the per-item detail sections (tools/memory/skills, ink's sort order) when showDetails is on — /context detail transcripts no longer show strictly less than the compact view (QwenLM#3) - projectMcpStatus honors showSchema (parameter JSON under each tool) and showTips, so /mcp schema is distinguishable from /mcp (QwenLM#4) - SlashDispatchEnv.settings is required: the real CommandContext.services.settings is non-null and a null surfaced as a generic command failure on first .merged read (QwenLM#5) - dead singleColumn flag removed from the help width layout (clamp makes it always false; ink has no single-column mode) (QwenLM#6) - truncated SS3 tail (bare ESC O) is stripped like the truncated CSI tail, so a captured half F1-F4 no longer leaks 'O' into the composer (QwenLM#7) - readBufferRow trims cellColumns alongside text, so URLs ending at end-of-row on a wide character hit-test on both halves of the cell (QwenLM#8) - kitty probe writes guarded: a synchronous stream throw settles the probe (restores raw mode, removes the listener) instead of leaking (QwenLM#9) - eraseLines reuses the ansi-escapes helper (already a repo dependency) instead of a byte-identical hand-rolled copy (QwenLM#10) - truncateText passthrough wrapper dropped; callers use the exported truncateHelpText directly (QwenLM#11) - SkillsList truncate keeps total length n like ink, so the description column no longer shifts by one cell when a name truncates (QwenLM#12) - model_fallback names pass through sanitizeDisplayText like ink (QwenLM#13) - selectIndex fires onHighlight before onSelect (ink dispatches SET_ACTIVE_INDEX then SELECT_CURRENT), keeping highlight-driven stay-open dialogs synced on mouse input (QwenLM#14) - mcp_app without fallbackText renders empty instead of JSON-dumping the embedded HTML; projectAbout hides Base URL when selectedAuthType is empty, matching ink's formatBaseUrl (QwenLM#15) * fix(cli): address R3 review findings in OpenTUI foundation modules - executeSlashCommand catch checks the abort signal first: an ESC- cancelled command (action rejects AbortError) returns handled with no failure telemetry or error message, mirroring ink's processor — the race promise never resolves when the signal is already aborted at addEventListener time - submit effect carries the full SubmitPromptActionReturn contract (modelOverride, onComplete, refreshContextFilesOnWrite) so the backend can honor /model <id> <prompt>, /dream's manual-run record, and /remember's context refresh like ink instead of silently degrading them - closing fences cannot carry info text (CommonMark): a ```js line inside an open block is literal body, not an early close that drops the block and inverts parse state for the rest of the document - info items append their linkUrl/linkText footer (ink's InfoMessage renders it; headless/SSH users need the printed URL, e.g. /bug) - the screen-reader sanitize keeps TAB: it separates words in tool/model output and deleting it fused adjacent tokens * fix(cli): address R4 review findings in OpenTUI foundation modules - a11y-plain-text: split on all CommonMark line endings so CRLF markdown opens/closes fences correctly; private-param CSI regex covers ECMA-48 intermediate bytes; DCS/SOS/PM/APC and unterminated OSC sequences consumed before strip-ansi; code-span pattern mirrors ink's INLINE_CODE_SPAN_PATTERN (non-empty content, closing-run lookbehind) - dialogs-shared: clearNumberBuffer called from setActiveIndex, selectIndex, and resyncKey block so wheel/hover/click/resync can't commit a stale numeric-flush selection the user never made - event-adapter: tool_call_response carries visionBridgeNotice on the tool-result event (ink ToolMessage renders the egress disclosure) - item-projection: projectContextUsage reads memoryFiles as { path, tokens } (ContextMemoryDetail), not { name, tokens } - key-map: 10 kp* keypad-navigation aliases (kpleft→left, …) and super flag folded into meta (ink Cmd+Enter = newline, not submit) - link-click: cellColumns no longer truncated to trimmed text length (preserves the wide-glyph right-half boundary); findUrlAtRow end boundary is width-aware (stringWidth of the last glyph) - slash-dispatch: submit effect carries PartListUnion content + a textContent string for text-only consumers (image parts survive); toggleVimEnabled and startNewSession seams wired from env; abort race resolves immediately for an already-aborted signal - clipboard: OSC 52 self-write removed — copyToClipboard's existing fallback (writeOsc52 / wrapForMultiplexer) is the single source - a11y-screen-reader: appendStatic skips clean === '\n' (ink's hasStaticOutput guard) * fix(cli): address QwenLM#10383 R1 findings in foundation modules - event-adapter: finished branch emits retry-countdown-clear BEFORE the info notice so the countdown row is actually cleared (the fold only pops when the last item is the retry row) - item-projection: /mcp tips now include all 5 lines ink renders (added OAuth auth tip and Ctrl+T toggle tip) - link-click: wide-glyph end boundary uses the last code point (not UTF-16 code unit) so non-BMP emoji are measured correctly by stringWidth - a11y-plain-text: CSI_SEQUENCE replaces PRIVATE_PARAM_CSI — drops the marker requirement so any CSI (with or without private parameter marker, with or without intermediate bytes) is fully consumed * fix(cli): address QwenLM#10383 R2 Critical findings in slash-dispatch - abort race: already-aborted signal now skips command.action entirely (result = undefined) instead of eagerly evaluating it as a Promise.race argument — the action's side effects (clear, persist, addItem) must not run on a cancelled submission - parent command telemetry: logEvent (slash_command SUCCESS) is now called before the early return for parent commands with subCommands (help listing) and bare handled — matching ink's finally-block logging * fix(cli): address QwenLM#10368 R2 review findings in live-session batch - input-prompt: convert OpenTUI display-width cursor coordinates to code-point positions at the component boundary — the pinned @opentui/core reports logicalCursor.col/offset and el.cursorOffset in terminal-cell units (edit-buffer.zig), while the ported ink helpers work in code points; wide characters previously shifted placeholder backspace, the backslash continuation check, completion targeting, and history edge compares - input-prompt: bump both search sequence refs when Esc dismisses the completion dropdown so an in-flight search resolving afterwards cannot re-open it and hijack Enter - live-session-model: carry the vision-bridge egress disclosure through the tool-result fold (ink ToolMessage renders it under the result) - messages: recognize the producers' two-L 'cancelled' summary spelling so canceled tools get the CANCELED glyph with strikethrough instead of the red ERROR glyph - session-switch: wrap /resume and /branch in the telemetry swap transaction (begin before the outgoing-session capture, commit at the UI re-key, abort after a rolled-back swap) — restores the usage aggregate on failed swaps and rejects concurrent switches - tests: display-width fake editor, wide-char placeholder/continuation witnesses, Esc invalidation, fold notice, cancelled spelling, and the three swap-transaction lifecycle cases * fix(cli): declare cursorOffset on the FakeEditor test interface The display-width fake added in 656e996 implements a cursorOffset getter/setter but the interface it is cast through never declared the member, so tsc --build fails with TS2339 at the two reads in the wide-char placeholder test. Typecheck ran before that commit's files were staged and missed it. * test(cli): stub listStartingRunIds in the session-switch fake registry The workflow-run registry gained listStartingRunIds with the workflow tasks feature on main; backgroundWorkUtils iterates it when describing blocking work, so the fake registry in session-switch.test.ts now implements it (empty) to match the interface the merged code expects. * fix(opentui): address yiliang114 review findings (4 P2 + 1 P3) - transcript-adapter: FIFO queue for id-less tool call pairing so tool-start and tool_result share the same minted id - session-switch: move uiSwapped=true to right after startNewSession (the first irreversible host mutation) preventing core/UI divergence on mid-sequence throw; same fix for branch handler - session-switch: add error item when /resume targets an unloadable session instead of returning silently - diff-render: run diff content through escapeAnsiCtrlCodes matching the ink text-boundary convention (useTurnDiffs.ts) - package.json: move remend from devDependencies to dependencies (imported from production source markdown-heal.ts) * fix(transcript): address R6 review — thinking latch, cancelled status, text join - Replace one-shot `closed` latch with `thinkingOpen` state so [thought, text, thought, ...] patterns emit matching thinking-end for each burst (P2) - Mirror live path: treat cancelled tool status as failed, not ok (P3) - Join user text parts with newline instead of empty string (P3) - Regenerate package-lock.json so remend is in dependencies (P2) * fix(opentui): address review-pr bot R3 critical findings - session-compaction: add missing COMPRESSION_FAILED_EMPTY_SUMMARY, OUTPUT_TRUNCATED, and API_ERROR cases to match ink compression-text.ts - live-session: distinguish cancelled from error in tool-end summary so toolStatusMeta renders strikethrough instead of red X - transcript-adapter: gate slash_command replay on phase=invocation to prevent double-replay (recorder writes both invocation and result) - input-prompt: add key.meta/key.option to DELETE_WORD_BACKWARD branch to match the guard condition that intercepts Alt+Backspace * fix(opentui): address round-5 review findings R2-5 R3-2 R3-12 R4-1 R2-5: update session-compaction.test.ts to assert the three new parity texts (EMPTY_SUMMARY, OUTPUT_TRUNCATED, API_ERROR) added in 63a7f3c; the old assertion that EMPTY_SUMMARY returned '' is stale. R3-2: transcript-adapter replay producer folded cancelled tool status into summary 'error' (red ✕) instead of 'cancelled' (strikethrough). Add the cancelled branch to match live-session.ts. R3-12: hidden slash-command invocations (hiddenInvocation: true for /auth, /help, /settings, /status, bare /effort, /btw) replayed as visible user rows and entered composer history. Gate them on the hiddenInvocation flag in the invocation filter. R4-1: modelOverride was only carried on the first UserQuery send; ToolResult continuation sends omitted it, so a per-turn model override silently reverted to the session default after the first tool batch. Propagate modelOverride into every continuation send.
…-rewind (QwenLM#10383) * feat(cli): OpenTUI foundation modules — theme, a11y, clipboard, keys, dialogs scaffolding Foundation batch of the OpenTUI migration tracked in QwenLM#8662. Adds the renderer-neutral foundation modules under ui/opentui: theme family, a11y (plain-text, screen-reader), clipboard, key-map, mouse hit/caret, link-click + osc8 parity, early-input, exit guard/lifecycle, kitty negotiation, event-adapter, item-projection, slash dispatch (+ command parsing), commands context/output, help content, input history, and the dialog scaffolding primitives (core/shared) with the theme dialog. Two helpers land inside ui/opentui rather than utils/ to respect the utils leaf-layer rule (QwenLM#9737). Stacked on the infra batch: consumes ui/model streaming model and @OpenTui deps. No reachable ink code changes beyond a one-line export addition in the shared osc8 module. * fix(cli): import originals instead of forking slash parser and dialog scope utils * fix(cli): address R1 review findings in OpenTUI foundation modules * fix(cli): align OpenTUI command host with the memory-file-count rename Upstream renamed setGeminiMdFileCount to setMemoryFileCount in the command UI contract; the rebase onto main surfaced the mismatch at build. Rename the host interface member, the bridge wiring, the dispatch stub, and the test mock to match. * feat(cli): OpenTUI migration live-session and input batch Third landing batch of the OpenTUI migration (QwenLM#8662): live-session stream fold and model, message rendering (markdown heal, MCP progressive, client tool runs, text batching), transcript adapter with resume/session-switch, sticky todos, the composer (input-prompt view/key/model), mouse rows and scrollbar, unified-diff rendering, and session-compaction notice. All additive — no reachable ink code path is touched, ink remains the default. Carries the first consumer of the remend dependency deferred from the infra batch, placed in devDependencies per the renderer-deps convention. The stacked-skill completion helpers import from the relocated ui/commands module following the upstream rename. * feat(cli): OpenTUI migration batch 4 — dialogs, commands, and session-rewind Adds the dialog layer and command-routing infrastructure for the OpenTUI renderer: 19 dialog modules (auth, extensions, MCP, memory-status, misc, model family, modes, permissions, settings, stats/skills, help overlay, arena host, folder-trust gate), the commands registry with slash-to-dialog routing, the commands dispatcher (action interpreter connecting the slash gateway to the session and dialog layer), and the session-rewind viewer with its history-folding model. Also exports `isUserTextContent` from historyMapping so the rewind model can classify user turns without duplicating the predicate. Everything is additive: no reachable ink code path is touched, the default renderer stays ink, and the dep-direction gate passes. Stacked on the live-session batch. 56 test files / 886 tests, all green. * fix(cli): address R2 review findings in OpenTUI foundation modules Round-2 review fixes (17 Critical + 10 Suggestion resolved in code): - dialogs-shared: move number-select flush out of the setState updater (StrictMode double-fires onSelect); split setActiveIndex (ink SET_ACTIVE_INDEX, lands on any in-range row) from highlightIndex (arrow keys skip disabled rows) so wheel navigation never sticks - event-adapter: chat_compressed notice mirrors ink formatCount ('~' prefix for estimated counts); vision_bridge_notice renders summary\nnotice; explicit projections for task_execution / findings_list / terminal_image keep multi-MB payloads off the transcript; retry-countdown-clear forwards isContinuation - slash-dispatch: isSlashCommandInput drops the '?' branch (ink gate routes ? input to the model); executeSlashCommand races the action against the abort signal; dialog effects carry the OpenDialogActionReturn payload; projected added-item text surfaces alongside non-handled effects (notice); message-shaped items project to their text; ui.history comes from env; absent sessionStats stamp now, not epoch; telemetry parity (recordSkillInvocation / recordAutoSkillCommandUsage / makeSlashCommandEvent) - item-projection: model stats render per-(model,source) sections with N/A for unpriced entries; Tool Calls line uses ASCII x like ink; redactProxy deduplicated via systemInfoFields export - theme: palette/syntax colors resolve through color-utils toHex before parseColor (ink CSS names / *bright names no longer degrade to magenta); unresolvable values stay unset - key-map: kitty 'kpenter' normalizes to 'return'; resolveCommands exposes ink's key fan-out (Ctrl+C fires QUIT + CLEAR_INPUT) - a11y: hardWrap delegates to wrap-ansi (word-boundary parity with ink's screen-reader path); markdown reducer tracks fence length, keeps fence-like lines literal inside fences and inner backticks in multi-backtick spans; stripAnsi delegates to strip-ansi plus a private-parameter CSI pass (SGR mouse, DEC save/restore) - clipboard: OSC 52 write gated on a TTY (stderr preferred), tests spy the stream instead of writing real sequences to the runner's terminal - exit-guard: independent per-key arm windows like ink - dialogs-theme: diff preview pane receives syntaxStyle/filetype * fix(cli): harden kitty probe and screen-reader writer per maintainer review - kitty-negotiation: KITTY_REPLY_RE requires at least one flag digit (\d+), so an echoed bare query \x1b[?u in PTY/CI environments no longer resolves true and locks the renderer into kitty mode on a terminal that never answers queries; the accumulation buffer keeps only a 256-byte tail (bounded memory, bounded rescan under byte floods); the settle-window drain is removed — an EventEmitter data listener cannot consume chunks from other listeners, so late replies flow to the renderer's input parser like any other terminal noise - a11y-screen-reader: ScreenReaderOutputWriter sanitizes written content (stripAnsi + drop bare C0/C1 controls, keep newlines) so the plain-text-only contract is enforced at the writer instead of trusting every future caller — smuggled OSC 52 clipboard writes or title/cursor sequences cannot execute on the main screen * test(cli): strengthen /branch awaits handleBranch assertion with a deferred race The previous test asserted branchNames was populated after dispatch, but a fire-and-forget void call passed because microtasks drained before the check. Replace with a Promise.race that proves dispatch was still pending (blocked on the closed gate) before the gate was resolved — a void call resolves dispatch immediately, making the race return 'resolved' instead of the sentinel. * fix(cli): correct stale 67→69 count in commands-registry docblocks; clarify gate test Two docblock comments said "67 modules" but the table has 69 entries (verified against BuiltinCommandLoader.ts). Fixed to 69. The gated-commands test comment now explains that TypeScript enforces the CommandGate type at compile time, so the runtime loop is unnecessary — the literal name list is the intentional guard for a bogus gatedBy on an ungated command. * fix(cli): address dialogs-batch self-review findings in command registry - /theme route results include 'message': themeCommand returns a MessageActionReturn under NO_COLOR, so the declared results were incomplete - drop the unreachable 'branch' member from OpenTuiDialogRequest and make routeDialogToOpenTui throw on dialog-branch instead: /branch is a host action intercepted unconditionally by the dispatcher (ink parity), and a compile-time exclusion is not expressible because OpenDialogActionReturn is a single interface with a union dialog field — the loud throw guards against a future refactor dropping the interception; the branch route no longer advertises a dialogs entry no renderer opens - derive gate coverage from the loader instead of a hardcoded name list: the coverage test loads with every gate ON (plus the checkpointing flag the /restore factory needs) and asserts set equality between route names and registered built-ins — no escape hatches — and a new test proves every gatedBy route is genuinely absent from a gates-off load, so a bogus gate on an always-registered command fails * fix(cli): address ytahdn independent review findings in OpenTUI foundation All 15 findings from the independent static review verified in source and fixed (no false positives; none deferred): - quit effect carries QuitActionReturn.messages projected to text on a notice field — ink renders them via QuittingDisplay and the payload was permanently lost (Important #1) - error and finished branches emit retry-countdown-clear like ink's handleErrorEvent/handleFinishedEvent, so a terminal event inside the countdown window no longer leaves a stale retry row (#2) - projectContextUsage renders the compaction-threshold ladder and the per-item detail sections (tools/memory/skills, ink's sort order) when showDetails is on — /context detail transcripts no longer show strictly less than the compact view (#3) - projectMcpStatus honors showSchema (parameter JSON under each tool) and showTips, so /mcp schema is distinguishable from /mcp (#4) - SlashDispatchEnv.settings is required: the real CommandContext.services.settings is non-null and a null surfaced as a generic command failure on first .merged read (#5) - dead singleColumn flag removed from the help width layout (clamp makes it always false; ink has no single-column mode) (#6) - truncated SS3 tail (bare ESC O) is stripped like the truncated CSI tail, so a captured half F1-F4 no longer leaks 'O' into the composer (#7) - readBufferRow trims cellColumns alongside text, so URLs ending at end-of-row on a wide character hit-test on both halves of the cell (#8) - kitty probe writes guarded: a synchronous stream throw settles the probe (restores raw mode, removes the listener) instead of leaking (#9) - eraseLines reuses the ansi-escapes helper (already a repo dependency) instead of a byte-identical hand-rolled copy (#10) - truncateText passthrough wrapper dropped; callers use the exported truncateHelpText directly (#11) - SkillsList truncate keeps total length n like ink, so the description column no longer shifts by one cell when a name truncates (#12) - model_fallback names pass through sanitizeDisplayText like ink (#13) - selectIndex fires onHighlight before onSelect (ink dispatches SET_ACTIVE_INDEX then SELECT_CURRENT), keeping highlight-driven stay-open dialogs synced on mouse input (#14) - mcp_app without fallbackText renders empty instead of JSON-dumping the embedded HTML; projectAbout hides Base URL when selectedAuthType is empty, matching ink's formatBaseUrl (#15) * fix(cli): drop dead single-column branch in help overlay The foundation batch removed the always-false singleColumn flag from the help width layout (the 72-column clamp makes it unreachable and ink has no single-column mode); the overlay's conditional branch on it no longer compiles. Only the two-column path was ever taken. * fix(cli): address R3 review findings in OpenTUI foundation modules - executeSlashCommand catch checks the abort signal first: an ESC- cancelled command (action rejects AbortError) returns handled with no failure telemetry or error message, mirroring ink's processor — the race promise never resolves when the signal is already aborted at addEventListener time - submit effect carries the full SubmitPromptActionReturn contract (modelOverride, onComplete, refreshContextFilesOnWrite) so the backend can honor /model <id> <prompt>, /dream's manual-run record, and /remember's context refresh like ink instead of silently degrading them - closing fences cannot carry info text (CommonMark): a ```js line inside an open block is literal body, not an early close that drops the block and inverts parse state for the rest of the document - info items append their linkUrl/linkText footer (ink's InfoMessage renders it; headless/SSH users need the printed URL, e.g. /bug) - the screen-reader sanitize keeps TAB: it separates words in tool/model output and deleting it fused adjacent tokens * fix(cli): address R4 review findings in OpenTUI foundation modules - a11y-plain-text: split on all CommonMark line endings so CRLF markdown opens/closes fences correctly; private-param CSI regex covers ECMA-48 intermediate bytes; DCS/SOS/PM/APC and unterminated OSC sequences consumed before strip-ansi; code-span pattern mirrors ink's INLINE_CODE_SPAN_PATTERN (non-empty content, closing-run lookbehind) - dialogs-shared: clearNumberBuffer called from setActiveIndex, selectIndex, and resyncKey block so wheel/hover/click/resync can't commit a stale numeric-flush selection the user never made - event-adapter: tool_call_response carries visionBridgeNotice on the tool-result event (ink ToolMessage renders the egress disclosure) - item-projection: projectContextUsage reads memoryFiles as { path, tokens } (ContextMemoryDetail), not { name, tokens } - key-map: 10 kp* keypad-navigation aliases (kpleft→left, …) and super flag folded into meta (ink Cmd+Enter = newline, not submit) - link-click: cellColumns no longer truncated to trimmed text length (preserves the wide-glyph right-half boundary); findUrlAtRow end boundary is width-aware (stringWidth of the last glyph) - slash-dispatch: submit effect carries PartListUnion content + a textContent string for text-only consumers (image parts survive); toggleVimEnabled and startNewSession seams wired from env; abort race resolves immediately for an already-aborted signal - clipboard: OSC 52 self-write removed — copyToClipboard's existing fallback (writeOsc52 / wrapForMultiplexer) is the single source - a11y-screen-reader: appendStatic skips clean === '\n' (ink's hasStaticOutput guard) * fix(cli): address QwenLM#10383 R1 findings in foundation modules - event-adapter: finished branch emits retry-countdown-clear BEFORE the info notice so the countdown row is actually cleared (the fold only pops when the last item is the retry row) - item-projection: /mcp tips now include all 5 lines ink renders (added OAuth auth tip and Ctrl+T toggle tip) - link-click: wide-glyph end boundary uses the last code point (not UTF-16 code unit) so non-BMP emoji are measured correctly by stringWidth - a11y-plain-text: CSI_SEQUENCE replaces PRIVATE_PARAM_CSI — drops the marker requirement so any CSI (with or without private parameter marker, with or without intermediate bytes) is fully consumed * fix(cli): address QwenLM#10383 R1 findings in dialogs batch - dialogs-mcp: flatServers derived from grouped render order, not raw prop order, so keyboard selection matches the highlighted server - dialogs-misc: highlightScope syncs editor selection (setSel) so Enter persists the highlighted scope's own editor, not the previous one - dialogs-settings: buildSettingsListItems forwards excludeWorkspaceRestricted under Workspace scope, matching ink's filter that prevents dead settings entries - dialogs-extensions: all onDetailAction call sites now swallow async rejections (.catch), matching session-rewind.tsx's pattern - dialogs-stats-skills: metrics read from per-session bucket (getMetricsForSession) not process-global; Wall Time computed from uiTelemetryService.getSessionStartTime() not a module-load constant - dialogs-modes: MODE_DESC key 'auto_edit' fixed to 'auto-edit' to match ApprovalMode.AUTO_EDIT enum value * fix(cli): address QwenLM#10383 R2 Critical findings in slash-dispatch - abort race: already-aborted signal now skips command.action entirely (result = undefined) instead of eagerly evaluating it as a Promise.race argument — the action's side effects (clear, persist, addItem) must not run on a cancelled submission - parent command telemetry: logEvent (slash_command SUCCESS) is now called before the early return for parent commands with subCommands (help listing) and bare handled — matching ink's finally-block logging * fix(cli): address QwenLM#10383 R2 Critical findings in dialogs batch - dialog-data: buildModelEntries image mode gates on isImageGenerationCapable (not imageOnly) so dual-role and visionOnly image-capable models appear in the image selector like ink - dialogs-extensions: detailSelect gets resyncKey: view so the cursor re-syncs when re-entering detail (action list shrinks after checked-update state resets) - dialogs-stats-skills: subscribes to uiTelemetryService 'update' event so stats stay live while the dialog is open (ink re-renders via SessionStatsProvider) * fix(cli): address QwenLM#10383 R3 review findings in opentui dialogs/dispatch - buildModelEntries: keep visionOnly models in the image selector (ink ModelDialog parity: isVisionModelMode || isImageModelMode || !visionOnly) - useDialogSelect: re-sync the cursor on items changes like ink's useSelectionList INITIALIZE reducer — follow the active item's key, fall back to the initial index when it is gone, so a shrinking list never strands the cursor where Enter reads undefined - OpenTuiSlashDispatcher: skip the action entirely when the signal is already aborted before the race — a late 'abort' listener never fires, so the eager race would run side effects before discarding - tests: pin the pre-aborted skip in both dispatchers, the dual-role image/vision fixture, the items-shrink clamp, and restore the uninstall-backout guard assertion * fix(cli): address QwenLM#10368 R2 review findings in live-session batch - input-prompt: convert OpenTUI display-width cursor coordinates to code-point positions at the component boundary — the pinned @opentui/core reports logicalCursor.col/offset and el.cursorOffset in terminal-cell units (edit-buffer.zig), while the ported ink helpers work in code points; wide characters previously shifted placeholder backspace, the backslash continuation check, completion targeting, and history edge compares - input-prompt: bump both search sequence refs when Esc dismisses the completion dropdown so an in-flight search resolving afterwards cannot re-open it and hijack Enter - live-session-model: carry the vision-bridge egress disclosure through the tool-result fold (ink ToolMessage renders it under the result) - messages: recognize the producers' two-L 'cancelled' summary spelling so canceled tools get the CANCELED glyph with strikethrough instead of the red ERROR glyph - session-switch: wrap /resume and /branch in the telemetry swap transaction (begin before the outgoing-session capture, commit at the UI re-key, abort after a rolled-back swap) — restores the usage aggregate on failed swaps and rejects concurrent switches - tests: display-width fake editor, wide-char placeholder/continuation witnesses, Esc invalidation, fold notice, cancelled spelling, and the three swap-transaction lifecycle cases * fix(cli): declare cursorOffset on the FakeEditor test interface The display-width fake added in 656e996 implements a cursorOffset getter/setter but the interface it is cast through never declared the member, so tsc --build fails with TS2339 at the two reads in the wide-char placeholder test. Typecheck ran before that commit's files were staged and missed it. * fix(cli): address QwenLM#10383 R4 review findings in dialogs batch - commands-dispatch.test: type the pre-aborted action mock as SlashCommandActionReturn so tsc --build passes (the inferred { type: string } could not satisfy the literal 'message' kind) - dialogs-shared.test: pin the resyncKey numeric-flush disarm — an armed digit quick-select must not commit a selection in the view swapped to before the flush timeout - session-switch.test: pin the unarmed-swap settlement when the resumed session is not found (commit, never abort) so the single swap slot cannot stay latched forever * test(cli): stub listStartingRunIds in the session-switch fake registry The workflow-run registry gained listStartingRunIds with the workflow tasks feature on main; backgroundWorkUtils iterates it when describing blocking work, so the fake registry in session-switch.test.ts now implements it (empty) to match the interface the merged code expects. * fix(opentui): address P2 review findings in session-rewind and load_history - session-rewind: add useRef re-entrancy guard to prevent double onRewind from batched key events in single stdin chunk - session-rewind: dispatch restore-error on onRewind rejection so the dialog recovers from dead 'restoring' phase back to 'pick' - commands-dispatch: pass Date.now()-based timestamps to addItem instead of array indices in load_history branch
What this PR does
Makes packages/cli/src/utils/ a true leaf layer and enforces the boundary mechanically. This is the CLI slice of #9146.
This moves 17 domain-coupled modules out of utils/ into their owner directories: config, i18n, nonInteractive, serve, services/housekeeping, commands/review, ui/commands, and ui. All moves are git mv with import specifiers rewritten across the importing modules.
It also extracts the generic normalizePartList helper into utils/normalize-part-list.ts, moves MergeStrategy to its owner utils/deepMerge.ts, and adds the error-level ESLint rule architecture/no-utils-upward-import for relative imports escaping utils/ in production TS/TSX while allowing type-only constructs that are erased at compile time.
Why it's needed
Before this change, utils/ imported back into config, ui, i18n, nonInteractive, serve, and commands. #9146 measured 43 upward value imports across 20 files, which kept the CLI directory graph cyclic. After this change there are zero upward value imports out of utils/; the only two remaining upward references are import type, which cannot form a runtime cycle.
Reviewer Test Plan
How to verify
Evidence (Before & After)
Before: 43 upward value imports out of utils/ at #9146's baseline. After: zero value imports; the remaining upward references are exactly two type-only imports: utils/modelConfigUtils.ts imports the Settings type, and utils/sessionPaths.ts imports the CommandContext type.
Tested on
Environment (optional)
Local Node workspace. Verified on the rebased branch on top of main @ c10143a with TypeScript, ESLint, focused Vitest suites, and npm run build.
Risk & Scope
Linked Issues
References #9146.
中文说明
本 PR 做了什么
让 packages/cli/src/utils/ 成为真正的叶层,并用机制强制约束边界。这是 #9146 的 CLI 部分。
本 PR 将 17 个域耦合模块从 utils/ 移到其归属目录:config、i18n、nonInteractive、serve、services/housekeeping、commands/review、ui/commands 和 ui。所有移动均使用 git mv,并重写相关导入路径。
此外,本 PR 将通用的 normalizePartList 提取到 utils/normalize-part-list.ts,将 MergeStrategy 移到其归属 utils/deepMerge.ts,并新增 error 级 ESLint 规则 architecture/no-utils-upward-import,禁止生产 TS/TSX 中逃出 utils/ 的相对运行时导入,同时允许编译期擦除的 type-only 构造。
为什么需要
变更前,utils/ 会反向导入 config、ui、i18n、nonInteractive、serve 和 commands。#9146 测得 20 个文件里有 43 个向上的值导入,使 CLI 目录图保持循环。变更后,utils/ 不再有向上的值导入;仅剩两处 import type,不会形成运行时循环。
评审测试计划
如何验证
证据(Before & After)
Before:#9146 基线测得 utils/ 有 43 个向上的值导入。After:零值导入;仅剩两处向上引用且均为 type-only:utils/modelConfigUtils.ts 导入 Settings 类型,utils/sessionPaths.ts 导入 CommandContext 类型。
测试环境
环境(可选)
本地 Node workspace。在基于 main @ c10143a 的 rebase 分支上用 TypeScript、ESLint、聚焦 Vitest suites 和 npm run build 验证。
风险与范围
关联 Issue
References #9146。